Multiplying multiple relative rates - figuring out what it is asking.

Question: This problem really confuses me:
$$ \frac{\$ 542}{1 wk} . \frac{\ 1 wk}{5 days} . \frac{\ 1 day}{8 hr}$$
<code>where "wk" = weekday week
      "days" = work day
</code>
So what it's saying is, "five hundred forty-two per week, times 1 week per 5 days, times 1 day per 8 hours". I do not understand this at all. I'm not really looking to solve it as I think I can do that with my tutor, but wrapping my head around this is something that was left up to me until friday. Some one please help!
Comment: I guess "wk" should be interpreted as "weekday week" and "day" should be interpreted as "work day," or else we live on different planets :)
Comment: Yep! I'll edit.
Answer: This is a way to do conversions that works on any sort of problem.
If you look at this in words, we want to know what the hourly pay is for the 5 day work week based on the total earning for an 8-hour work day.
Look at how "wk", and "day" cancel.
Now, if you multiply across the numerator you get $542$.
If you multiply across the denominator, you get $40$.
All other units cancel out, so we have pay/hr.
So, we are left with:
$$ \frac{\$ 542}{40} \text{per hour}$$
Does that make sense?
As another example, use the same method to convert $24$ hours into seconds to see if it makes sense.
$$
\begin{array}{c|c|c|c}
\text{24 hours}& 60 ~minutes & 60 ~seconds\\\hline
\text{}& 1 hour& 1  minute\\
\end{array}
$$
See how the "hours" and "minutes" cancel.
Now just multiply numerators and divide by the multiplication of denominators and there is your conversion.
So, we are left with $\displaystyle \frac{24 \times 60 \times 60}{1 \times 1} = 86400$ seconds.
Comment: Ahhh. Okay! Thanks for the enlightenment. I will study this a little more. Thanks again.
Comment: @randmath: You are very welcome!
Comment: Nice work! I like your tables, and the follow-up from the OP!
Comment: @amWhy: That simple method saved me many a time in Physics classes! :-) Just know what the units are supposed to be at the end, using the given information, is very useful indeed! Thx


Qual é a diferença entre um "branch" e uma "tag"?

Question: No Git, qual é a diferença entre um branch e uma tag?
Comment: Só deixar um adendo, que conversarmos a um bom tempo, muitos repositórios, como o do Laravel por exemplo, usam os branchs pra dividir as versões pois eles costumam continuar a fazer updates em ambos branchs.
Comment: http://imasters.com.br/artigo/21127/software-livre/como-trabalhar-com-tags-no-git?trace=1519021197&source=single aqui explica bem a diferencia entre ambas.
Answer: A tag é apenas uma marca, em geral, em um branch específico que marca uma situação em um determinado momento.
O branch tradicional deve ser algo experimental, algo em paralelo, algo que potencialmente será incorporado ao desenvolvimento principal, ao branch principal.
A tag costuma marcar um release, uma versão ou algo assim. Então a tag é apenas um apontador para um commit específico enquanto que um branch é um caminho, um galho de desenvolvimento.
A tag é apenas um nome que se dá para um estado do desenvolvimento. Desta forma fica fácil acessar aquele estado sempre que for preciso.
No Git não há custo em ter uma tag, é algo simbólico e não ocupa espaço no repositório. Você não altera o que está na tag. É um ramo estático que pode ser usado a qualquer momento. A tag será usada eventualmente, quando há algum evento importante no desenvolvimento e que ali precise desta marca para voltar nela outras vezes. Normalmente este evento é um release.
Se trabalha no desenvolvimento sempre em cima de branches através dos commits. É nele que se faz o merge do estado anterior com o que foi desenvolvido agora. O branch vai recebendo evoluções do desenvolvimento. É incentivado que se faça um novo branch, sempre que possível, quando vai iniciar uma nova linha de desenvolvimento.

Coloquei no GitHub para referência futura.
Comment: @WallaceMaxters Nem todos incentivam o uso de branches - muitos as evitam. Trabalhei em projetos com todos commitando na mesma branch, e trabalhei em outros onde o custo de integração entre branchs foi sendo reduzido com integrações a intervalos cada vez menores, até que as integrações foram completamente removidas (todos commitando na mesma linha), trazendo muitos ganhos. Talvez os problemas na sua empresa sejam melhor resolvidos de outra forma. Dê uma lida sobre a prática de **Integração Contínua** (*Contínuos Integration*) aqui: http://martinfowler.com/articles/continuousIntegration.html
Comment: Taí uma coisa que temos que aprender a fazer aqui onde eu trabalho  (o último parágrafo)
Comment: No `SVN` isso é diferente né? @bigown
Comment: No SVN Temos o Trunk que funciona como a linha principal da árvore!
Comment: @WallaceMaxters E nesta resposta há um resumo muito singelo sobre utilizar uma única linha de desenvolvimento e utilizar branches apenas para construir releases de manutenção em versões estáveis: http://pt.stackoverflow.com/a/48866/14584
Answer: Para ficar clara a diferença, pense no repositório do Git como um grafo, sendo que cada nó deste grafo é um commit.
Tag é um ponteiro que você usa para apontar para qualquer nó deste grafo.
A tag, normalmente, é usado para marcar versões do sistema. Exemplo: você pode criar uma tag v1.2.1 em determinado ponto do seu repositório, continuar commitando no repositório e voltar para esta tag v1.2.1 facilmente.
Branch também é um ponteiro para um nó mas, diferente da tag, a branch pode gerar uma ramificação dentro deste grafo.
Veja o grafo a seguir. O master é uma branch, assim como minha-branch é. Há também uma tag v1.2.1 criada, apontando para o nó N03:
                            |minha-branch|
                                  |
                                  |
                             .---N05
                            /
N01<---N02<---N03<---N04<--´-----N06
               |                  |
               |                  |
           |v1.2.1|           |master|

Criar uma tag ou uma branch é tão simples e rápido quanto escrever 41 bytes em um arquivo no disco.
Como pode perceber, dentro do Git, elas são iguais, mas tratadas de maneiras diferentes:

Tão iguais que você não consegue ter uma branch com o mesmo nome de uma tag.
Tão diferentes que você não consegue commitar em uma tag (a não ser que crie uma branch a partir desta tag!), mas pode commitar em uma branch.
Comment: +1 pelo desenho, rsrs
Comment: Acho que o comentário sobre o SVN não se aplica...pelo que sei, no SVN branchs e tags são idênticos,e o custo de criação é muito baixo também.
Comment: @zentrunix, removido. Na época que eu usava uma branch no SVN este processo era muito pesado, mas não sei como está hoje em dia o SVN, acredito que tenha evoluído e melhorado.
Answer: Branch:
Uma ramificação da sua "árvore" principal de desenvolvimento, geralmente criado para gerar correções ou novas implementações, quando esse branch chega no final podemos fazer um Merge para a ramificação principal do seu projeto.
Tag:
Podemos olhar a tag com um "repositório" de releases das versões estáveis, essas versões não devem ser alteradas.
Tag
--release 1.0
---release 1.0.1
----release 2.0
-----release 2.1

Finalizando
O Branch fica com a responsabilidade de receber as modificações(commits) durante o sprint do desenvolvimento a cada nova implementação é recomendável gerar novas branches conforme o desenvolvimento vai evoluindo.
Quando o projeto já está maduro e estável é gerada uma nova release que será armazenada na TAG do repositório
Answer: Só um complemento a tudo que ja foi falado, existem 2 tipos de tag:
Light-weight tags
Que como já foi dito são como links simbólicos, apenas apontam para um commit.
Quanto a espaço no repositório, o git cria somente um arquivo com o nome da tag dentro, portanto é mínimo.
Annotated tags
Resumindo são tags com um pouco mais de informação, além de apontarem para o commit, também armazena o nome e email do criador da tag, data, e mensagem da tag, tipo a mensagem do commit.
Já que contem muito mais informação do que uma light-weight ela acaba sendo armazenada como um objeto completo do git, logo ocupa mais espaço do que a light-weight
Answer: Branch são ramificações (ao pé da letra) de um trabalho em paralelo do que já está em produção ou na master. Usamos branchs para codificar alguma funcionalidade específica ou então para corrigir bugs, por exemplo.
Já uma tag utilizamos para definir uma nova versão do produto. Por exemplo um sistema que estava em desenvolvimento e foi concluída a versão 1.0. Daí então se cria uma tag dizendo que a partir dali foi lançada a tal versão.


Find a model for the given WFF

Question: Find a model for the given WFF:
$\exists xp(x) \rightarrow \forall xp(x)$
I'm interpreting this as saying "There exists an x in the function p(x) which implies For all X in p(x)?
So my solution says that all I have to do is just let Let the Domain D be the set of Natural Numbers, and let $p(x)$ be x equals x + 1...
But I don;t understand how that is a model for the given wff? What is that even implying/saying?
Comment: It is an uninteresting model, the antecedent is false and therefore the implication is true. But it is a model. The sentence should be interpreted in a way that is a little different from yours. It says that if there is an object with the property $p$, then all objects have the property $p$. Another model, equally uninteresting, is again over the natural numbers, and $p(x)$ is $x=x$.
Comment: I see, but what does that have to do with let $p(x) = x + 1$
Comment: From my reading of your post, $p(x)$ is the formula $x=x+1$, which is false for all $x$.
Answer: Let $\mathbb{N}$ be the set of natural numbers, and let $p(x)$ be the formula $x=x+1$. For any natural number $a$, $p(a)$ is false. So $\exists x p(x)$ is false in the natural numbers, and therefore for any sentence $\varphi$, the sentence $\exists xp(x)\to\varphi$ is true in the natural  numbers. In particular, let $\varphi$ be the sentence $\forall xp(x)$.
Alternately, we could let $p(x)$ be the formula $x=x$. Then $\exists xp(x)\to \forall x p(x)$ is true in the natural numbers. For $\forall xp(x)$ is true, and therefore whatever sentence $\varphi$ we choose, $\varphi\to\forall xp(x)$ will be true.
Answer: The statement, $\;\exists x\,P(x) \; \to \; \forall x \,P(x)\;$ is "if there is something that satisfies $P$, then all things satisfy $P$".   (This is not a tautology; its truth depends on what $P$ is.)
An equivalent statement is: $\;\forall x\,\neg P(x) \;\vee\; \forall x\,P(x)\;$ "Either no thing satisfies $P$ or all things satisfy $P$".
So you must find an model where predicate $P$, in a domain of discussion, is such that it is either true for all things or false for all things.

All below use the set of natural/integer/rational/real/complex numbers as the domain (pick any one).
$$\exists x\, (x=x+1)\;\to\;\forall x\, (x=x+1)$$
Now the predicate $x=x+1$ is false for all $x$.   Because the antecedent is false, therefore the implication is considered true.   This is a viable model.
$$\exists x\, (x=x+1)\;\to\;\forall x\, (x=x+1)$$
Here the predicate $x=x$ is true for all things. &\nbsp; Because both the antecedent and consequent are true, therefore the implication is validated.   This too is a viable model.
$$\require{cancel}
\color{red}{
 \cancel{
  \color{black}{
   \exists x\, (x=5)\;\to\;\forall x\, (x=5)
  }
 }
}$$
However, the predicate $x=5$ is true for one thing, but not for all things.   Because the antecedent is true but the consequent is false, therefore the implication does not hold.   So this is not a viable model.

Find a model for the given WFF


Drupal 8, entityQuery with operand "AND" for a multiple values field

Question: I have 2 contents who contains a field 'field-test'. The 'field-test' contains an array of taxonomies (its a simple multiple values taxonomy field) :
Node A :

field_test : '1','2','3,'4' // where 1,2,3 and 4 are tids

Node B :

field_test : '4','5','6,'7'

With the entityQuery api, I can get nodes who contains the taxonomy '4' OR '5' with :
$test = \Drupal::entityQuery('node')
  ->condition('field_test', array('4','5'),'IN')
  ->execute();
// get nodes A and B in an array

But I want get only the node B (only the node who contains taxonomies 4 AND 5)
How can I do that ?
Thank you :)
Comment: Is there any reason you cannot do ->condition('field_test', 4)->->condition('field_test', 5)? As far as I know the default conjunction for eq is AND.
Comment: If I do that, the $test->execute() return nothing
Answer: I'm not sure if you can do that using an entity query.
You could specify the delta explicitly:
\Drupal::entityQuery('node')
  ->condition('field_tags.0.target_id', 1)
  ->condition('field_tags.1.target_id', 2)
  ->execute();

But of course that would only match if the ids are used in those specific deltas.
You probably need to use raw SQL for this, see https://stackoverflow.com/questions/3918351/sql-query-ensure-a-row-exists-for-each-value-in for the basic approach on how to do this.
Comment: Hmmm..Drupal query api can't manage all queries ? I mean, If a query become too 'complex', I need use raw query ? I'm surprising ! I thinked drupal api can manage all database request, isn't right ?
Comment: No, it can not. The *entity* query can't do everything. It is designed so that other entity storages can support it too, like MongoDB or even web services. It can not possibly support every possible query and never wil.
Comment: That's true if you added the terms in the original order that they are stored in the field. The following will not work : ->condition('field_tags.0.target_id', 2)->condition('field_tags.1.target_id', 1)
Answer: I had the same problem, and I found a way to do it with entityQuery and an andConditionGroup(). Try this out:
$tags = ['5', '6'];
$query = \Drupal::entityQuery('node');

foreach ($tags as $id) {
  $query->condition($query->andConditionGroup()
    ->condition('field_tags', $id));
  }

$query->execute();

This should loop over each id, and add it individually to the andConditionGroup().
See this page for more details, including a comment with a very similar example from another user.


"You are binding v-model directly to a v-for iteration alias"

Question: Just run into this error I hadn't encountered before: "You are binding v-model directly to a v-for iteration alias. This will not be able to modify the v-for source array because writing to the alias is like modifying a function local variable. Consider using an array of objects and use v-model on an object property instead." I am a little puzzled, as I don't appear to be doing anythong wrong. The only difference from other v-for loops I've used before is that this one is a little simpler, in that it's simply looping through an array of strings, rather than objects:

         <text-field :name="'run'+index" v-model="run"/>

        <button @click.prevent="removeRun(index)">X</button>

The error message would seem to suggest that I need to actually make things a little more complicated, and use objects instead of simple strings, which somehow doesn't seem right to me. Am I missing something?
Comment: How is `settings` defined in your viewmodel?
Comment: `settings` is a JSON object returned from the server, containing a property called `runs`, initially an empty array.
Answer: Since you're using v-model, you expect to be able to update the run value from the input field (text-field is a component based on text input field, I assume).
The message is telling you that you can't directly modify a v-for alias (which run is). Instead you can use index to refer to the desired element. You would similarly use index in removeRun.

new Vue({
  el: '#app',
  data: {
    settings: {
      runs: [1, 2, 3]
    }
  },
  methods: {
    removeRun: function(i) {
      console.log("Remove", i);
      this.settings.runs.splice(i,1);
    }
  }
});

      <input type="text" :name="'run'+index" v-model="settings.runs[index]" />

      <button @click.prevent="removeRun(index)">X</button>

    {{run}}

Comment: It should be at documentation. I'd very hard time searching for it.
Comment: Excellent! That did it, thanks, without adding extra complication.
Comment: Any idea in how to haldle index change? At any moment my index can change... That is my structure: `template.columns[0].columns[1].children[3].style.color`
Comment: @CaioKawasaki I can't understand the issue from your comment. You should probably ask a new Question.


System of differential equations

Question: Can you help me solve this system of differential equations
$ x'= 4x - 2y $
$ y'= 3x - y - 2e^{3t} $
Initial conditions are  $ x(0) = y(0) = 0 $
Answer: $\mathbf x' + \begin{bmatrix} -4&2\\-3&1\end{bmatrix} \mathbf x = \begin{bmatrix}0\\-2e^{3t}\end{bmatrix}$
$e^{At} \mathbf x' + A e^{At} \mathbf x = e^{At}g(t)$
$A = P^{-1}DP$
$A = \begin{bmatrix}1&2\\1&3\end{bmatrix}\begin{bmatrix}-2&0\\0&-1\end{bmatrix}\begin{bmatrix}3&-2\\-1&1\end{bmatrix}\\
e^{At} = P^{-1} e^{Dt}P$
$\mathbf x =$$ e^{-At}C + e^{-At} \int e^{At}g(t) dt\\
e^{-At}C + P^{-1}e^{-Dt} \int e^{Dt}Pg(t) dt$
$e^{Dt}Pg(t) =\begin{bmatrix}4e^t\\-2e^{2t}\end{bmatrix}$
$\mathbf x =e^{-At}C + P^{-1}\begin{bmatrix}4\\-1\end{bmatrix} e^{3t}\\
P\mathbf x(0) =C + \begin{bmatrix}4\\-1\end{bmatrix}\\
C = \begin{bmatrix}-4\\1\end{bmatrix}$
$\mathbf x = \begin{bmatrix}-4e^{2t}+2e^{t}+2e^{3t}\\-4e^{2t}+3e^t + e^{3t}\end{bmatrix}$
Comment: I know that you posted this awhile ago, but I'm quite confused by how you get to the $x=e^{-At}C...$. Do you mind elaborating, if you don't mind?
Comment: We have $x'+ax = g(t).$  Multiplying through by the integrating factor  $e^at$ leads to $e^{at} x' + ae^{at}x = e^at g(t)$  the expression on the left is the anti-derivative of $e^{at}x.$  Integrating both sides we get $e^at x = \int e^at g(t) dt + C.$  Multiplying though by $e^{-at}$ gives $x = e^-at\int e^{at}g(t) dt + Ce^{-at}$
Comment: Ah I see! Thank you. How did you get to $e^{Dt}Pg(t)=\begin{bmatrix}
4e^{t}
\\ -2e^{t}
\end{bmatrix}$ ? Sorry I'm having trouble following along. Then how does this follow onto the next line?
Comment: Oh! I feel silly about the above comment. I see it's just a multiplication. Then you integrate it, and times by -e^(-Dt)!
Answer: Subtracting both equations, you get
$$x'-y'=x-y+2e^{-3t}$$ which you can solve for $x-y$, giving
$$x-y=Ce^t-\frac{e^{-3t}}2,$$ where $C=\frac12$.
Then solve
$$y'=3\left(y+\frac{e^t-e^{-3t}}2\right)-y+2e^{-3t}.$$
Answer: With the operator $D:=d/dt$, $$\begin{cases}(D-4)x+2y=0\\3x-(D+1)y=2e^{-3t}.\end{cases}$$
Then by elimination of $y$,
$$6x+(D+1)(D-4)x=(D-1)(D-2)x=2e^{-3t},$$ which is an ordinary second order equation.
Its solution is readily obtained as
$$x(t)=C_1e^t+C_2e^{2t}+\frac{2e^{-3t}}{(-3-1)(-3-2)}.$$
The rest is straightforward.
Answer: By solution is more ad-hoc than formal. I used a general solution of the form
$$\begin{aligned}
x(t) &= \left( X_0 + X_1 {\rm e}^{\alpha t} \right) {\rm e}^{3 t} + X_2 {\rm e}^{\beta t} \\
y(t) &= \left( Y_0 + Y_1 {\rm e}^{\alpha t} \right) {\rm e}^{3 t} + Y_2 {\rm e}^{\beta t}
\end{aligned}$$
which I pluged into the IC first to solve for $X_0$ and $Y_0$ in terms of the rest of the coefficients, and the used this in the D.E.
The solution I got was
$$\begin{aligned}
x(t) &= \left( 2 -4 {\rm e}^{-t} \right) {\rm e}^{3 t} + 2 {\rm e}^{ t} \\
y(t) &= \left( 1 -4 {\rm e}^{- t} \right) {\rm e}^{3 t} + 3 {\rm e}^{ t}
\end{aligned}$$
NOTE: I solved for $X_2$ and $Y_2$ first, and then used the intermediate result $X_1 = \frac{2 Y_1}{1-\alpha}$ to find the coefficients $\alpha$ and $\beta$ that solve the D.E.

System of differential equations


half note and eighth note stems for voice parts

Question: With voice parts for piano the stems usually go on opposite directions, when they're on the same staff. But I have a book where a half note and an eighth note are one semitone apart but together like a chord. Does this mean that they share the stem? Shouldn't their stems go in opposite directions?
Comment: If you can put in a scan or picture it will help a lot to answer the question.
Comment: I'm looking for the option to upload pictures but i don't see any on this website.
Comment: Click "Edit" under your question and then click the little box that has a tiny mountain and sun in it above the text box with your question in it.
Answer: I believe the situation you're referring to should look something like this:

Note that their positions should be reversed if the 8th is the lower note, and also probably the 8th would be joined via a beam to other 8ths (as in the example at the bottom of this answer).
This is a good explanation from retmusic.com, emphasis mine:

When writing the interval of a second, the stem should be placed between the note heads. The higher pitch is always placed to the right, regardless of stem direction (this results in one of the note heads being "displaced"). [...] When the interval of a second is written with opposite stems, as with multiple voices sharing the same staff, the stems are aligned vertically — in the case of a second, this means that the higher note is placed on the left.

The second bar in the referenced image corresponds to the bolded text.  If your example looks like the first bar, then the two notes do not represent separate voices!  (Or the editor made a mistake.)
You even draw both stems when both voices share the same pitch:
Comment: My question looks like figure 1 but the half note doesn't have a stem, so it could be an editor's error.
Comment: @user26931Could it be a whole note?
Comment: I don't think so because they're 2 of them in the same measure, 4/4 time signature.


How I set up an Web Api end point hosted directly on Xamarin Forms?

Question: I would like to expose an http server on my xamarin forms app to expose data outside the phone, is it possible ? For example, an endpoind which returns log file inside phone. thank you
Answer: Yes it is possible. We are using EmbedIO.
Take a look at this github repo.
You can create your webserver like (basic example)
<code>var server = new WebServer(o => o
                    .WithMode(HttpListenerMode.EmbedIO))
                    .WithLocalSessionManager()
                    .WithWebApi("/api", m => m.WithController(() => new YourController()));

public class YourController : WebApiController
{
   [Route(HttpVerbs.Get, "/test")]
   public Task<string> Get()
   {
      return Task.FromResult("test");
   }
}
</code>
Ofc you need to know device IP address. Then you can set it for example
<code>_server = new WebServer(o => o
                    .WithUrlPrefixes($"http://yourIp:8088")
...
</code>


How to implement in-process full text search engine

Question: In one of our commercial applications (Win32, written in Delphi) we'd like to implement full text search. The application is storing user data in some kind of binary format that is not directly recognizable as a text.
Ideally, I'd like to find either an in-process solution (DLL would be OK) or a local server that I could access via TCP (preferably). The API should allow me to submit a textual information to the server (along with the metadata representing the binary blob it came from) and, of course, it should allow me to do a full-text search with at least minimal support for logical operators and substring searching. Unicode support is required.
I found extensive list of search engines on Stack Overflow (What are some Search Servers out there?) but I don't really understand which of those engines could satisfy my needs. I thought of asking The Collective for opinion before I spend a day or two testing each of them.
Any suggestions?
Answer: There are a number of options on the market. Either fully fledge commercial products or open source variants. Your choice of a search provider is very dependent on the customers you are targetting.
Microsoft has a free Express version of their Search Server. As far as I know the Express edition is limited to running the Application Tier on one server.
There is also the Apache Lucene project which is open source. It has a nice API that's easy to use and a large community of users. The original project is based on Java, but there are also other implementations such as NLucene for .NET that I have used personally.
Answer: I'd recommend having a look at SQLite -- full-text search is included in the latest version.
Answer: I suppose the answer depends on your db. For example SQL Server has full text search and also English Language Queries if ever needed.
Answer: Take a look at using PostgreSQL and tsearch.
Answer: Try using postgresql with tsearch
Answer: Sphinx is probably the most efficient and scalable option while SQLite - FTS3 is the most straightforward option.
Answer: While not in-process, Solr is very fast (based on Lucene) and easily accessible from any platform (HTTP)


Why isn't config for Views plugin module translatable?

Question: I am trying to write up a patch for this module: https://www.drupal.org/project/readmore. There is a patch for it: https://www.drupal.org/project/readmore/issues/3055200 which adds configurable text for the "read more" and "read less" links provided by this field formatter. But the configuration for these new settings are not translatable.
I noticed that the readmore.schema.yml did not include entries for these new fields (although the new configuration options do work). I added this:
readmore_text:
  type: string
  label: 'Read more link text'
readless_text:
  type: string
  label: 'Read less link text'

To the .schema file but it doesn't help.
What is missing to trigger translation of this view to show these new configuration options?
Answer: First of all, for translatable strings you need type: label. Then the Views entity field schema
views.field.schema.yml:
views.field.field:
  type: views_field
  label: 'Views entity field handler'
  mapping:
    click_sort_column:
      type: string
      label: 'Column used for click sorting'
    type:
      type: string
      label: 'Formatter'
    settings:
      label: 'Settings'
      type: field.formatter.settings.[%parent.type]

expects a field formatter schema with this structure:
field.formatter.settings.daterange_default:
  type: field.formatter.settings.datetime_default
  label: 'Date range default display format settings'
  mapping:
    separator:
      type: label
      label: 'Separator'
      translation context: 'Date range separator'

This example is extending a base class and so it is also extending the schema. Otherwise you can replace the type reference to the parent formatter with type: mapping. See also Language specific settings for field formatters
Comment: thanks for the reply. Took a while to try to see what all of that was.. but turns out my only issue was I had type: string when it needed to be type: label. :)


Issues with pipenv install on M1 Mac for python dependencies

Question: I'm trying to set up a local repository that was originally created on intel-based macs. The repository uses pyenv and pipenv to manage python dependencies. Whenever I try to run pipenv install, I get the following error:
ERROR:pip.subprocessor:[present-rich] pip subprocess to install build dependencies exited with 1
[ResolutionFailure]:   File "/Users/xur19/.pyenv/versions/3.8.10/lib/python3.8/site-packages/pipenv/resolver.py", line 782, in _main
[ResolutionFailure]:       resolve_packages(
[ResolutionFailure]:   File "/Users/xur19/.pyenv/versions/3.8.10/lib/python3.8/site-packages/pipenv/resolver.py", line 730, in resolve_packages
[ResolutionFailure]:       results, resolver = resolve(
[ResolutionFailure]:   File "/Users/xur19/.pyenv/versions/3.8.10/lib/python3.8/site-packages/pipenv/resolver.py", line 709, in resolve
[ResolutionFailure]:       return resolve_deps(
[ResolutionFailure]:   File "/Users/xur19/.pyenv/versions/3.8.10/lib/python3.8/site-packages/pipenv/utils/resolver.py", line 1105, in resolve_deps
[ResolutionFailure]:       results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps(
[ResolutionFailure]:   File "/Users/xur19/.pyenv/versions/3.8.10/lib/python3.8/site-packages/pipenv/utils/resolver.py", line 894, in actually_resolve_deps
[ResolutionFailure]:       resolver.resolve()
[ResolutionFailure]:   File "/Users/xur19/.pyenv/versions/3.8.10/lib/python3.8/site-packages/pipenv/utils/resolver.py", line 689, in resolve
[ResolutionFailure]:       raise ResolutionFailure(message=str(e))
[pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies.
  You can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation.
  Hint: try $ pipenv lock --pre if it is a pre-release dependency.
ERROR: pip subprocess to install build dependencies exited with 1

The repository has an existing Pipfile and Pipfile.lock
My steps for setup are:
brew install pyenv
pyenv install 3.8.7
pyenv global 3.8.7
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init)"\nfi' >> ~/.zshrc
brew install python
pip install pipenv
pipenv shell
pipenv install

My Mac is an M1 mac and I've tried the following:

Try to make the repo work with ARM architecture. I've tried using python 3.8.10 instead of 3.8.7 since that is the latest version that supports the M1 chip, and I've tried removing some dependencies that aren't being used that don't support M1 (cx-oracle). I've also tried running pipenv lock --pre and pipenv install --skip-lock but both of those result in the same error. I've also tried deleting my Pipfile.lock and only using the Pipfile, but that also fails.
Try to make the repo work with Rosetta 2. I've tried installing homebrew with Rosetta (to /usr/local/bin/brew) and I've used the arch -x86_64 prefixes with brew (with a separate Rosetta enabled terminal, changed my paths, etc). When I try that, I get similar errors. I've reviewed several stackoverflow and medium articles that describe how to install python/pipenv/pyenv with Rosetta, but I'm unable to get past this error.

I'm not sure what else to try - was wondering if anyone had advice on how to tackle this. For context, here is my Pipfile.
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]
autopep8 = "*"
flake8 = "*"
black = "==20.8b1"

[packages]
celery = "==4.4.7"
channels = "==3.0.3"
channels-redis = "==3.2.0"
#cx_Oracle = "==8.2.1" # Django DATABASE
Django = "==2.2.24"
django-allauth = "==0.44.0"
django-celery-beat = "==2.2.0"
django-cors-headers = "==3.7.0"
django-enumfield = "==1.5"
django-environ = "==0.4.5"
django-extensions = "==3.1.2"
django-filter = "==2.1.0"
django-graphql-jwt = "==0.3.1"
django-graphql-persist = "==0.1.1"
django-jet = "==1.0.8"
django-redis = "==4.12.1"
django-reversion = "==3.0.9"
django-reversion-compare = "==0.14.0"
django-measurement = "==3.2.3"
django-jsoneditor = "==0.1.6"
django-storages = {extras = ["google"],version = "==1.11.1"}
flower = "==0.9.7"
future = "==0.18.2"
google-auth = "==1.29.0"
google-auth-oauthlib = "==0.4.4"
google-cloud-storage = "==1.37.1"
google-cloud-pubsub = "==2.4.0"
graphene = "==2.1.7"
graphql-core = "==2.2"
graphene-django = "==2.7"
graphene-file-upload = "==1.3.0"
graphql-relay = "==2"
graphql-server-core = "==1.1.1"
gunicorn = "==19.9.0"
ijson = "==3.1.4"
ldap3 = "==2.9"
matplotlib = "==3.4.1"
munch = "==2.5.0"
numpy = "==1.20.2"
openpyxl = "==3.0.7"
pandas = "==1.2.4"
pillow = "==8.2.0"
psycopg2-binary = "==2.8.6"
pyhumps = "==1.6.1"
pyjwt = "==1.7.1"
pymongo = "==3.11.3"
pyteomics = "==4.4.2"
python-pptx = "==0.6.18"
pytz = "==2018.9"
redis = "==3.2.0" # Doesn't get installed by django-redis
requests = "==2.21.0"
tqdm = "==4.60.0"
xlrd = "==2.0.1"
jinja2 = "==3.0.2"
premailer = "==3.10.0"
docxtpl = "==0.14.2"
inflection = "==0.4.0"
sympy = "==1.9"

[requires]
python_version = "3.7"

Comment: Do you have any updates on this?
Answer: In my case I did the following:

arch -arm64 brew install libffi
export LDFLAGS="-L/opt/homebrew/opt/libffi/lib"
export CPPFLAGS="-I/opt/homebrew/opt/libffi/include"
CONFIGURE_OPTS='--with-system-ffi' pyenv install 3.7.10 pyenv local 3.7.10
pipenv install

And then it worked!
Answer: I'm not 100% sure, since I was dealing with 3.7.10, but my problem looked suspiciously similar. Based on this issue on pipenv, I was led to this article, which led me to a solution.
The summarized solution from that article is as follows.
I'm not sure you need to install libffi from brew and make these exports, but I was in a morass so it may help.
brew install libffi
export LDFLAGS="-L/opt/homebrew/opt/libffi/lib"
export CPPFLAGS="-I/opt/homebrew/opt/libffi/include"

This part you definitely need to do.
CONFIGURE_OPTS='--with-system-ffi' pyenv install 3.7.10
pyenv local 3.7.10

Then edit the file that causes the MemoryError. For 3.7.10 ~/.pyenv/versions/3.7.10/lib/python3.7/ctypes/__init__.py. Comment or remove the last line of this function.
def _reset_cache():
    _pointer_type_cache.clear()
    _c_functype_cache.clear()
    if _os.name == "nt":
        _win_functype_cache.clear()
    # _SimpleCData.c_wchar_p_from_param
    POINTER(c_wchar).from_param = c_wchar_p.from_param
    # _SimpleCData.c_char_p_from_param
    POINTER(c_char).from_param = c_char_p.from_param
    _pointer_type_cache[None] = c_void_p
    # XXX for whatever reasons, creating the first instance of a callback
    # function is needed for the unittests on Win64 to succeed.  This MAY
    # be a compiler bug, since the problem occurs only when _ctypes is
    # compiled with the MS SDK compiler.  Or an uninitialized variable?
    CFUNCTYPE(c_int)(lambda: None) # comment or remove me

Then it worked for me. pipenv installed many things without issue.
Comment: Doesn't works for me. Also my _reset_cache() function is different.
Comment: Okay, maybe you could explain in what way your function was different, so people could benefit from your findings.


MVC3: delete an object in an database from an array of selected objects

Question: I've successfully selected the Objects I want to delete. But the problem is when I remove an item from Object array, it doesn't make any changes. My code is following below..
My database
public List<Product> db = new ProductRepository().GetProducts();

Here it shows all the products with checkbox..
public ActionResult MultipleDeletes()
        {
            return View(db);
        }

On Submitting "Button named Delete", I got problem.
[HttpPost]
        public ActionResult MultipleDeletes(int[] selectedProducts)
        {
            var del_products  = from x in selectedProducts
                           from y in db
                           where y.ProductId == x
                           select y;

            foreach (var item in del_products)
            {
                //Product p = db.Find(item.ProductId);
                //db.Remove(p);
                //db.SaveChanges();
            }

            return View(db);
        }

Could anyone help me?
can you also tell me, how to write Lambda expression instead of LinQ?
Comment: This question isnt actually about MVC its about your ERM framework. Which database access technology are you using?
Comment: Thats your actual database file, how are you accessing the database? are you using entity framework or linq to SQL or some other ORM?
Comment: I'm using Entity Framework (Model First).. I've got 2 model. Product Model, it's the attributes. and ProductRepository creates products using NBuilder.
Answer: I think in this case you need to make use of Delete rather than remove.
Use following and see if it works
db.DeleteObject(p)
db.SaveChanges()

Comment: I already have from in the previous line. Product p = db.Find(item.ProductId).. it say that find has some invalid arguments. And then .DeleteObject doesn't appear in Intellisense.
Answer: The problem was in the model. I used NBuilder.. so it didn't really save the data.
I built an DbContext. Then it worked.
Solution is ..
public ProductDBContext db = new ProductDBContext();

        [HttpPost]
        public ActionResult MultipleDeletes(int[] selectedProducts)
        {
            foreach (int item in selectedProducts)
            {
               Product product = db.Where(p => p.ProductId == item).SingleOrDefault();
               db.Remove(product);
               db.SaveChanges();
            }
          return View();
        }


Como definir propriedades padrão para variável que começarem com um texto especifico?

Question: Existe alguma forma de definir as propriedades de uma variável como padrão pela iniciais da variáveis?
Algo como public string obsUsuario { get; set; }, todas que começarem com obs ter como padrão a propriedade IsOptional, (ou/e outras propriedades) sem ter que ficar declarando toda vez para cada uma variável?
modelBuilder.Entity<Usuarios>().Property(prop => prop.obsUsuario).IsOptional();

Answer: Só precisa usar um pouco de reflection
modelBuilder.Properties<string>()
        .Where(p => p.Name.StartsWith("descr"))
        .Configure(p => p.IsOptional());

Comment: Legal, posso até usar um `||` aqui para mais campos . tipo `.Where(p => p.Name.StartsWith("descr") || p.Name.StartsWith("obs"))`, isso vai me ajudar muito. Vlw


Heteroscedasticity that depends on the regression parameters

Question: Consider a vector of observations $\mathbf{Y}$ that can be modeled as
\begin{equation}
  \mathbf{Y} \sim \mathcal{N}( \mathbf{H}\boldsymbol{\beta} , \boldsymbol{\Sigma} )
\end{equation}
with $\mathbf{H}$ a linear parametric model, and $\boldsymbol{\Sigma}$ a diagonal matrix whose elements are given by $a_1 \mathbf{H}\boldsymbol{\beta} + a_2$, and where the constants $a_1$ and $a_2$ are known.
To properly estimate $\boldsymbol{\beta}$, and since the variance is heteroscedastic but depends on the regression parameters, a first estimation can be obtained applying OLS:
$$
  \widetilde{\boldsymbol{\beta}}^{\mathrm{ols}} = \left( \mathbf{H}^\mathrm{T} \mathbf{H} \right)^{-1} \mathbf{H}^\mathrm{T} \mathbf{Y} .
$$
Then, a rough estimation of the noise variance is obtained from $\widetilde{\boldsymbol{\beta}}^{\mathrm{ols}}$ by:
$$
  \widetilde{\boldsymbol{\Sigma}}^{\mathrm{ols}} = \mathbf{I}\times (a_1 \mathbf{H}\, \widetilde{\boldsymbol{\beta}}^{\mathrm{ols}} + a_2 ),
$$
where $\mathbf{I}$ denotes the identity matrix. This rough estimation of the covariance is thus reused to update the estimation of the expectation using WLS:
\begin{equation}
\label{eq:estimated_expectation_detect}
\begin{cases}
  \widetilde{\boldsymbol{\beta}} = \left( \mathbf{H}^\mathrm{T} {\widetilde{\boldsymbol{\Sigma}}^{{\mathrm{ols}}^{-1}}} \mathbf{H} \right)^{-1} \mathbf{H}^\mathrm{T} {\widetilde{\boldsymbol{\Sigma}}^{{\mathrm{ols}}^{-1}}} \mathbf{Y} , \\
  \widetilde{\boldsymbol{\Sigma}} = \mathbf{I}\times (a_1 \mathbf{H}\, \widetilde{\boldsymbol{\beta}} + a_2 ).
\end{cases}
\end{equation}
We can prove that the estimation $\widetilde{\boldsymbol{\beta}}^{\mathrm{ols}}$ is unbiased. However, is the estimation $\widetilde{\boldsymbol{\beta}}$ unbiased?
Another question is, is there a better way to estimate $\boldsymbol{\beta}$?
Answer: What you have here is a heteroscedastic linear model, which gives a non-linear function of the coefficients in the log-likelihood.  This occurs because your coefficients affect both the slope of the regression line and also the variance matrix, giving a complicated form in the  log-likelihood.  If you were to keep iterating your estimators in the way you have specified (though you have only done one iteration here), you would be doing iteratively reweighted least-squares (IRLS) estimation, which is a standard method of parameter estimation for this kind of model.
The use of IRLS estimation in heteroscedastic linear models is analysed in Chen and Shao (1993).  In that paper, the authors show that, under certain broad conditions, the IRLS estimator converges in distribution to normality, around the true coefficients (assuming the model is correctly specified).  The estimator is not generally unbiased, which is standard whenever you have non-linearity in a regression.  However, under broad conditions, it is asymptotically unbiased.  If you would like to know the details, I recommend reading up on IRLS estimation, and the linked paper.


Baseline Profile - variants effect in Android

Question: In my current project, I just can build non-prod variants base on my company's policy and I currently want to apply Baseline profile for the Prod version. So I wonder that when I generate a baseline profile in non-prod environment and put the profile under main folder, will it effect for the Prod version?
Hope to see answers for this question
Answer: If you put the generated profile into src/main/baselineProfile (or formerly src/main/baseline-prof.txt) then it will be correctly used in the prod version of your app.
Be aware that if the prod version has some custom code paths that can't be exercised with the generator, than you may be missing some potential improvement. Ideally you want to have the non-prod version as close as possible to the prod one.
But as with other improvements, you can start with something and iterate on it to squeeze even more improvements.


postfix/smtp Connection timed out

Question: usually my posftix/smtp works fine until now, it get timed out on almost every destinations.
I drop all the firewalls, and start to accept all. I check the firewall. and there is no problems.
$telnet a.mx.mail.yahoo.com 25
Trying 126.96.36.199...
Connected to a.mx.mail.yahoo.com.
Escape character is '^]'.
220 mta145.mail.ac4.yahoo.com ESMTP YSmtp service ready

but in the log, i see this:
Oct 13 13:13:55 ubr postfix/smtp[4003]: connect to yahoo.com[184.108.40.206]:25: Connection timed out
Oct 13 13:14:25 ubr postfix/smtp[4003]: connect to yahoo.com[18.104.22.168]:25: Connection timed out
Oct 13 13:14:55 ubr postfix/smtp[4003]: connect to yahoo.com[188.8.131.52]:25: Connection timed out
Oct 13 13:15:25 ubr postfix/smtp[4003]: connect to yahoo.com[220.127.116.11]:25: Connection timed out
Oct 13 13:15:55 ubr postfix/smtp[4003]: connect to yahoo.com[126.96.36.199]:25: Connection timed out
Oct 13 13:15:55 ubr postfix/smtp[4003]: E94B74B8C: to=<email@example.com>, relay=none, delay=154369, delays=154219/0.03/150/0, dsn=4.4.1, status=deferred (connect to yahoo.com[22.214.171.124]:25: Connection timed out)

I Try to test the resolved ip for yahoo.com in the log.
$telnet 220.127.116.11 25
   Trying 126.96.36.199...
Yes they timed-out
What did happend? It happend on
Answer: I had experiance the same as you.
If you have 2 nics, you should check which interface is listning for smtp. In my case, our server has two nics and private IP was listning for smtp.
And I have modified main.cf from inet_interface = 172.24.0.1 to inet_interfaces = all.
Answer: Timeouts like this can be a sign that you're being greylisted. Its a way some antispam systems use to slow down spammers by tying their outbound connections in a connection-timeout. You should check to see if your source IP address is showing up in any RBLs. Finding out if you're on any of the private lists can be a lot trickier.
Comment: my ip is 220.127.116.11, and I didn't find it in RBLs
Comment: I find, that postfix doesn't use the ip from MX, it use the ip from A. now how tho solve this?
Comment: Please post you dns related stuff from /etc/resolv.conf. Your DNS server list may be outdated. Try with a public one from opendns or google.
Comment: I add disable_dns_lookups = no at the end of my main.cf, and the problem solved.

postfix/smtp Connection timed out


Linux Postfix Setup on a fresh VPS

Question: I've launched a new VPS with CentOS 5. It's pretty skeletal, nothing setup.
I'm trying to configure my mail server to handle my email: firstname.lastname@example.com
My DNS settings live on GoDaddy.com. I have set up a contact name under the MX settings (not sure if that is correct) that points to the mail server (mail.domainname.com). Is that correct? or should it point to smtp.secureserver.com?
So that's the first thing, the second is setting up my server to handle mail.
Should I be using postfix for my mail server? At that, I'm a bit confused on setting this up. I've set myhostname and mydomain but still no luck.
I'd appreciate any tutorials and help, thanks!
Answer: First off, the MX record should point to whatever server is listening for incoming SMTP traffic. If you're planning to have your VPS handle mail traffic, then the MX record should point to it.
Second, the job that you're considering using postfix for is called a Message Transport Agent (MTA). There are lots of options listed at that link; postfix is perfectly valid but may be a bit overwhelming for a first-timer.
I wonder though; are you trying to run a mail server for production use, or to learn how to set one up? There are lots of tutorials for setting up postfix if you're trying to build knowledge, but if you're planning to use this in production, you're probably better off going with a hosted solution like Google Apps or GoDaddy's email service. Mail is tricky and hard to do right.
Comment: My VPS is for my personal website but I do all of my client work on there, so I need a fully ready server. I have my personal domain email with a couple other ones for personal use tied to it, so that's really the only thing I need it for.. I am setting up a google apps account now, I forgot about this.

Can I configure my server to send through google apps as well?
Comment: You really don't want to use Google's SMTP servers to send mail, since they need to be authenticated to and you'll have to store your username and password in plaintext somewhere on the server. I imagine the VPS provider has a SMTP server you can use? If so, then you can configure [`ssmtp`](https://wiki.archlinux.org/index.php/SSMTP) to forward mail there. Also, if you're using Google Apps for email, then you'll want to point your domain's MX record at them.
Answer: You should probably start here. It's pretty comprehensive.
That said, running a mailserver can be a complex task, especially when it goes wrong. I would recommend you look at installing a control panel onto your VPS like cPanel or Plesk if you don't feel capable of managing your own mailserver manually (of course, if you do that you won't learn anything!).
Comment: Oh by the way, i have installed cPanel + WHM myself on the server, can that setup a mailserver for me?

Linux Postfix Setup on a fresh VPS


FACETS : Add "Apply" button that will apply all filters in one query

Question: Is it possible in D8 to add an "Apply" button that will apply all facet filters in one query and not having an ajax reload on each option changed ?
i find this for D7 :
https://www.drupal.org/project/ajax_facets/issues/2700063
i am not quite sure  what's been the issue of that issue.
Comment: Isn't this counter point to what facets are?
Comment: Not sure i get your point and i quite like the ajax behaviour of the facets but when using more than one facet ,our UX designer consider that selecting all filters before applying is better, particularely when a selection of one make the others disappearing
Comment: why exposed filters have an apply button by default and facets have an option on change behaviour by default?
Answer: i have created an issue on the facet module and the situation is :
Not soon in the drupal 8 version. This would be a big refactor of the way queries are built right now.
https://www.drupal.org/project/facets/issues/3013702


The group $\mathrm{Diff}(F)$ and transition functions of a fibre bundle.

Question: Let $M$ and $F$ be differentiable manifolds, and let $F\to E\to M$ be a differentiable fibre bundle over $M$. A trivialising cover $\{(U_i,\phi_i)\,|\,i\in I\}$ of $M$ determines a set $\{t_{ij}:U_{ij}\to\mathrm{Diff}(F)\,|\,i,h\in I\}$ of transition functions satisfying the Čech cocycle conditions. In [Nakahra, Geometry, Topology and Physics, 2003], it is assumed that these transition functions actually take values in some Lie group $G$, and it is simply mentioned that the transition functions are smooth maps. I was pondering:

Why are they actually smooth?
If one considers the general case that the transition functions take values in $\mathrm{Diff}(F)$, are these functions still smooth? Is this even well-defined, i.e. is $\mathrm{Diff}(F)$ always a manifold?

Any help is much appreciated.
Answer: You have to be careful when $F$ is not compact, and I don't want to be careful today, so let $F$ be a smooth compact manifold without boundary. Then $\text{Diff}(F)$ is a Frechet manifold: it's locally modeled not on Euclidean spaces, but on topological vector spaces called Frechet spaces. Here the Frechet space that's the tangent space at the identity is precisely $\mathfrak X(F)$, the space of smooth vector fields on $F$.
The point of the topology on this space is that a continuous map $M \to \text{Diff}(F)$ is canonically the same as a continuous family of diffeomorphisms $M \times F \to F$, where each $f_m$ is a diffeomorphism. So the point of the smooth structure is that a smooth map $M \to \text{Diff}(M)$ gives me a smooth family if diffeomorphisms $M \times F \to F$, and vice versa.
Now, when you pick trivializations, they are always meant to be smooth trivializations (as opposed to fiberwise smooth trivializations); and therefore the transition maps $U \times F \to U \times F$ are smooth; composing with the projection map gives us a smooth family of diffeomorphisms $U \times F \to F$. So the cocycle this gives, $U \to \text{Diff}(F)$, is smooth. So indeed the transition maps are smooth. If you only demanded the trivializations be smooth on each fiber, $U \times F \to F$ would only be a continuous family of diffeomorphisms, and $U \to \text{Diff}(F)$ would only be continuous.
The theory of Frechet manifolds is well-developed (see Kriegl-Michor, a convenient setting for analysis), but having not read that book, I tend to try to use it as philosophy (like the above).
Comment: Point taken, thanks for this answer; it clarifies that this touches on stuff I have not seen before. However, in chapter 7 of this book by Michor (http://www.mat.univie.ac.at/~michor/gaubook.pdf, via http://www.mat.univie.ac.at/~michor/listpubl.html#books), it says that for a smooth manifold $M$ the group $\mathrm{Diff}(F)$ is a submanifold of $C^\infty(M,M)$. How can I see that with this answer?
Comment: @B.Pasternak I never told you what the smooth structure was, so you shouldn't see it here! $\text{Diff}(M)$ is an open subset of $C^\infty(M,M)$, so automatically inherits the latter's smooth structure. If it helps, I can tell you what the tangent space $T_f C^\infty(M,N)$ is; it's the space of sections of the pullback bundle $f^*TN$. When $N = M$ and $f = \text{id}$, this is exactly the same as saying it's sections of $TM$, aka vector fields.


ERROR: What does "use of class template 's_array' requires template arguments" mean?

Question: Im currently studying for an exam in c++.
I'm doing some practice questions on templates and have became totally stuck, i'v checked my code and it follows the solutions but this error keeps poping up. I'm unsure how I am passing in the wrong arguements (this is what I believe the issue is.
Code is listed below, any help is greatly appreciated
Tester
int main(){

    s_array array(10);
    array[5] = 5; //inbound access
    cout << array[5] << endl;

    array[-1] = 2;
    cout << array[15];
    return 0;
}

header, class and templates:
template <typename T>
class s_array {
    public:
    s_array(int size);
    ~s_array();

    T &operator[](int i);

    private:
    int size;
    T* data;
};

template <typename T>
s_array<T>::s_array(int size) : size(size)
{
    /*
     * If the size of the array is greater than zero
     * A new array is created at the value of size
     */
    if(size > 0) data = new T[size];
    else{
        std::cout << "Invalid array" << endl;
        exit(1);
    }
}

template <typename T>
s_array<T>::~s_array()
{
    delete [] data;
}
/*
 * Safety feature for the array going out of bounds
 */
template <typename T>
T& s_array<T>::operator[](int i)
{
    if(i < 0 || i >= size){
        std::cout << "index" << i << "is out of bounds" << endl;
        exit(1);
    }
    return data[i];
}

Comment: Check again how you are supposed to use a class template where the types can't be deduced from the constructor call.
Answer: You need to say what type the s_array is holding, for example this would define the array to contain int types. In the template definition, int will now be substituted everywhere that T used to be
s_array<int> array(10);


U-SQL Inner Join creates a huge big write file

Question: All -
I have some issues using ADLA joining tables and loading them into Azure SQL DW.
I am stuck on one of the loading process and not sure how can fix that problem. I have some purchase information which when I pull from on-prem system into ADLS creates output file of around 25 MB each and when I try to join them to using "INNER JOIN" in ADLA job it keeps running for a long time. While running I see the output file keeps going on to more then 5+ GB. I feel that's too much for a 25 MB file and not sure if am doing anything wrong (screen capture attached for reference while running from VS).
The process I do is - 1- load data from on-prem db to cloud ADLS store using ADF 2- run ADLA job to pull ADLS file into ADLA table and partition using ROUND ROBIN option to avoid data skew issues 3- ADLA job would create an aggregated file in ADLS store 4- ADF pipeline to load #3 file into Azure SQL DW
Any pointers or help could be very helpful.
Thanks, Shabbir
Here is the code (I have removed all field names and client information). Hope this helps.
DECLARE @dir = "/{date:yyyy}/{date:MM}/{date:dd}/<FILE PATH>/";
DECLARE @in_1 string = <FILE #1>;
DECLARE @in_2 string = <FILE #2>;
DECLARE @out string = <OUTPUT FILE>;

@file1 =
    EXTRACT
        <25 COL. WITH ALL NULLABLE>
        date DateTime
    FROM @in_1
    USING Extractors.Text(delimiter : '|');

@file2 =
    EXTRACT
        <40 COL. WITH ALL NULLABLE>
        date DateTime
    FROM @in_2
    USING Extractors.Text(delimiter : '|');

@output =
    SELECT
        <25 + 40 COL. FROM INPUT FILES>
    FROM @file1 AS f1
        INNER JOIN @file2 AS f2
        ON f1.join1 == f2.join2;

OUTPUT @purchase
TO @out
USING Outputters.Text(delimiter : '|');

This is run throw a ADF pipeline and using external parameters for date and file paths.
enter image description here
Comment: Please post the U-SQL code you are using.
Comment: Bob, I have added code snippet in my questions. Thanks in advance.
Comment: If your join is producing an increase in the data volume, a probable cause is that you have duplicated values in your join columns. If a value is present 100 times in the left table and 1000 times in the right table, that will lead to 100,000 lines in the output (cartesian product). Could you check that, for example by loading your data in Power BI?
Comment: Yes. Alexandre. This looks like more of cartesian issue. I am good for now. Thanks!
Answer: It looks like you are not using ADLA tables, but just dealing with files directly in U-SQL. This is fine, but I just wanted to check since you mentioned tables. Also, the code is outputting @purchase which doesn't exists in the script - I assume that you are actually outputting the right rowset in your real script.
A few questions:

Have you checked the format/content of the input files in ADLS? Have you done an output of @file1 and @file2 to check they create what you expect?
How do you know that the output file is growing to 5 GB? From the job graph? Can you attach that?
Are you using the "date" column for something?
Is your join column a single column, and what type is it?
Comment: Yes. I am not using ADLA tables for now. Though had tried that too and got same results.

I did checked output by running extract jobs and they show all expected contents

Yes, its showing up in the job graph.

Join column in int data type and its one-main relation between two tables

I have attached screen capture of job graph in the question. Please check.
Answer: If f1.join1 == f2.join2 is actually comparing a (more-or-less) unique key versus another (more-or-less) unique key, then you should get a reasonable number of rows.
But many people implement CROSS JOINs using this same syntax.  For example, f1.join1 could be 1 throughout table f1, and f2.join2 could also be 1 throughout table f2.  These data values would cause your output to be a CROSS JOIN of the two tables.


Codeigniter / PHP - A PHP Error was encountered Severity: Notice Message: Undefined variable

Question: Estou tentando realizar uma página de pesquisa, mas ao inserir qualquer informação no input e pressionar enter, recebo esta mensagem:
A PHP Error was encountered
Severity: Notice

Message: Undefined variable

Filename: views/pesquisa.php

Line Number: 60

Backtrace:

Model:
   class Busca_model extends CI_Model
{
    public function buscar($busca)
    {
        if(empty($busca))
        {
            return array();
        }

        $busca = $this->input->post("busca");
        $this->db->like("marca", $busca);
        return $this->db->get("lista_carros")->result_array();
    }
}

Controller:
<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Welcome extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->model("carros_model", '', TRUE);
    }

    public function gravar()
    {
        $info = $this->input->post();

        $id=$this->carros_model->gravar($info);
        return $id;
    }

    public function index()
    {

        $this->load->view('dashboard');
    }

    public function cadastro()
    {
        $this->load->view('cadastro');
    }

    public function lista()
    {
        $info = $this->input->post();
        if ($info) {
            print_r($info);
        } else {
            $data['listagem'] = $this->carros_model->listar();
        }
        $this->load->view('lista', $data);
        $this->load->model("busca_model", '', TRUE);
    }

    public function deletar()
    {
        $post = $this->input->post();
        $this->load->model("busca_model", '', TRUE);
        $retorno = $this->carros_model->deletar($post);

        // passos: enviar para a model para fazer a exclusão
        // em seguida, caso sucesso, vc vai enviar um parametro de sucesso ou erro
        if ($retorno == true) {
            $dados['error'] = 0;
            $dados['msg'] = "Carro deletado com sucesso";
        } else {
            $dados['error'] = 1;
            $dados['msg_error'] = "Erro ao deletar o carro escolhido";
        }
        echo json_encode($dados);
    }

    public function pesquisar()
    {
        $this->load->model("carros_model", '', TRUE);
        $this->load->model("busca_model");
        $this->load->view('pesquisa');
        $data["listagem"] = $this->busca_model->buscar($_POST);
        // print_r($data);
        // exit();
    }

    public function edit($id)
    {
        $this->load->model("carros_model");
        $data["carro"] = $this->carros_model->show($id);
        print_r($data);
        exit();
        $this->load->view("formulario");
    }
}

Answer: Dentro da sua Model você esta esperando um id "busca"
$busca = $this->input->post("busca");

Porém não existe, porque nos eu controller você está passando o $_POST direto:
$data["listagem"] = $this->busca_model->buscar($_POST);

Tente trocar por isso:
$data["listagem"] = $this->busca_model->buscar($_POST['busca']);

Isso, imaginando que da sua view você manda o id 'busca'
Como está sua view ?


How to create documents in the api but with place of signature

Question: I need create documents from my software to api integration but I would like of mark the place of signature for client.
Its possible?
Answer: Sure, easy-peasy. When creating the DocuSign envelope, include a sign here tab with the create call. And use anchor text to tell DocuSign where the signature request should appear.
Here is the recipe. And here is example software that you can run on Heroku for free.
Note: in order to run the recipe on Heroku, you'll need a free developer account on DocuSign, plus a free integration key.
Answer: When creating envelopes in the DocuSign system there are generally three different methods for placing signature and other tabs.

Absolute (or fixed) positioning.
Relative positioning (aka Anchor Tags or Auto-Place).
PDF Form fields.

(1): With absolute positioning you can set the (x,y) coordinates of where you want to place tabs through your documents.  You can set that manually by dragging and dropping through the DocuSign Website, or you can set those locations through the API. See Larry's API Recipes links.
(2): The anchor tagging (aka Auto-place) feature places tabs in your documents based on the actual document content itself. For instance, you can place a signature tab anywhere the text "Please Sign Here" is found in your document(s).  However please note that it will place a signature tab for each and every instance of that string it finds, not just the first.
(3): The third option for placing tabs only work with non-flattened PDF files. If you have a PDF with form fields in it, DocuSign can read those fields and locations and place tabs there. This is easy and powerful, but of course only works with PDF files.
Learn more about all these option at the DocuSign Developer Center.
Answer: What I've found is that it will place a signature tab for every document in an envelope, even if the other documents are using a different server template.


Equation for making an oval based on r=cos(th)

Question: I have a polar graph (on paper) with a curve similar to 7.8*cos(theta). Plotting the data estimate from a nice big print-out of the graph gives a fairly close fit, but I seems that the circle needs to made into an oval to fit better. In other words it looks like a scale factor in the "y direction" (if you'll forgive me, I know it's a polar plot.)
http://ibin.co/2V7RxQNKbqbO

deg rad     f(r)    Real Data
0   0       7.8000  7.8
10  0.174   7.6815  7.7
20  0.349   7.3296  7.4
30  0.523   6.7550  6.9
40  0.698   5.9751  6.2
50  0.872   5.0137  5.3
60  1.047   3.9000  4.2
70  1.221   2.6678  3

(Beyond 70 deg a different curve applies in my problem domain so I'm not too worried about that part of the curve)
Is there another form of equation that I can use to modify r=7.8cos(th) to stretch the curve? The purpose is to use an equation to calculate the values at intermediate points, and to avoid a potentially complex lookup system.
Answer: You stretch the plot vertically by a scale factor $\lambda\gtrsim1$.
Your equation was
$$\rho=r\cos(\theta),$$ and in Cartesian coordinates
$$x=r\cos^2(\theta),\\
y=r\cos(\theta)\sin(\theta)).$$
It is now
$$x=r\cos^2(\theta),\\
y=\lambda r\cos(\theta)\sin(\theta),$$
which is no more simple in polar coordinates, as
$$\rho'=r\cos(\theta)\sqrt{\cos^2(\theta)+\lambda^2\sin^2(\theta)},\\
\tan(\theta')=\lambda\tan(\theta).$$
Eliminating $\theta$, this gives this little monster:
$$\rho'=r\cos\left(\arctan\left(\frac{\tan(\theta')}\lambda\right)\right)\sqrt{\cos^2\left(\arctan\left(\frac{\tan(\theta')}\lambda\right)\right)+\lambda^2\sin^2\left(\arctan\left(\frac{\tan(\theta')}\lambda\right)\right)}.$$
You'd probably better stick to Cartesian coordinates with the ellipse
$$\left(\frac{x-r}{r}\right)^2+\left(\frac y{\lambda r}\right)^2=1.$$
Comment: That is some monster alright. I may simply transform to Cartesian, though I guess if the monster can be translated into code and tested properly it would do fine! Thanks Yves!
Comment: @djnz0feh: absolutely. But then one may wonder what is the relevance of using polar coordinates at all.
Comment: The goal is still to have a function in terms of theta (it is a wind direction) even if it has to be transformed along the way.
Comment: I see. The simplest is $\theta'\to\theta\to\rho'$ then.
Comment: OK. One more thing (you'll have to forgive me  - it's a long time since I was in university) $\theta\prime$ is the $\theta$, subject to checking which quadrant it should be in, no? Is $\rho\prime$ then the mangnitude but again subject to which quadrant and hence which direction?
Comment: @djnz0feh: if I am right, your curve is in quadrants I and IV for $-\pi<\theta<\pi$. Then using the tangent/arctangent will cause no problem.


set css and js custom group in carabiner using codeigniter

Question: friends
my problem is : my project is on codeigniter. when i refresh my page first html content loaded and after some seconds that pages js and css loaded. for that i tried carabiner.
step 1: i downloaded carabiner
step 2: i added it to app/third_party/carabiner/
step 3: now i add group in app/third_party/carabiner/config/carabiner.php
 like this-
$config['groups']['custom_js'] = array('js' => array(array('base_url();/assets/js/jquery.js','base_url();/assets/js/jquery.min.js', TRUE, FALSE)));
$this->carabiner->display('custom_js');/* for load that group */
$carabiner_config = array(
            'script_dir' => 'assets/scripts/',
            'style_dir'  => 'assets/styles/',
            'cache_dir'  => 'assets/cache/',
            'base_uri'   => base_url(),
            'combine'    => TRUE,
            'dev'        => FALSE,
            'minify_js'  => TRUE,
            'minify_css' => TRUE
);

i also set this array in config/carabiner.php but dont know what is
  problem still showing error due to missing jquery.min.js and
  jquery.js any suggestion ??
Answer: You assign the base_url() like string. So replace above coding like this
$config['groups']['custom_js'] = array(

    'js' => array(

        array(base_url().'/assets/js/jquery.js', base_url().'/assets/js/jquery.min.js', TRUE, FALSE)
    )

    );


Exchange 2010 - How could a mailbox be forwarding to users despite in mail-flow settings, delivery options, mail forwarding is not set?

Question: The mailbox that is forwarding and the mailboxes it's forwarding to were migrated from Exchange 2003 to 2010.
Maybe the attributes are actually set but are not showing correctly in EMC for some reason?
Comment: Have you checked for any rules in the email client?
Answer: Are you sure you don't have the "forwarding" mailbox's email address added as an email alias on the receiving mailbox?


How to reset formula in Crystal Reports when trying to show a section on every page

Question: My question is maybe not good, but here is the thing. I export my report in two types: PDF and HTML. In my designer, I am using Page Header for my grid and I need that section on every page of PDF file and only on the first page of HTML file. I made a bool parameter(which I pass through c# code) and use this formula on the "x-2" button of Suppress option of the section:
if MyBool = true
PageNumber > 1 // HTML case
else
"" // PDF case     I need a blank formula in else case because I will show this section on every page

So, the problem is else case, where I tried with "false", but it is not working. So, basically I need opposite of the "PageNumber > 1". In my code, I only passed the parameter like this:
mainReport.SetParameterValue("MyBool", false);

Thanks.
Comment: you want to supress the `page header` or you want to `PageNumber>1` when it is HTML?
Comment: @Siva Not sure you understood, I don't want to check Suppress option, I just want to find opposite of the "PageNumber > 1" and put it in else case. In the first case (HTML), I use PageNumber > 1 (without suppressing) and it shows Page Header section on the first page (which is good), but in PDF case, I only need that formula blank, or something in else.
Answer: I am not sure whether I have addressed your problem.. but I want to suggest below approach.
Since you are writing in supress formula:
If (MyBool = true  and PageNumber > 1)
true // HTML and XLS case
else
false // PDF case

Answer: OK, here is the situation:

Picture 1: What I do in the designer

Picture 2: What I want in the PDF file

Picture 3: What I want in HTML file
I hope it is clear now @Siva.
Comment: that I got and provided my approach.. but changed a bi will you try now?


are the solutions of stable $x' = x(1-x)$?

Question: I had difficulties finding the answer to the following question:
Determine whether the solutions $x(t) = 0$ and $x(t) = 1$ of the single scalar equation $x' = x(1-x)$ are stable or unstable.
I tried to do this with the definition for stability but I wasn't able to find eigenvalues here
Comment: Did you draw the phase portrait? Solutions that have an initial condition in $(0, 1)$ tend towards $1$; what does that tell you about the solutions?
Comment: @Did Thanks, I can't do arithmetic today.
Answer: 'Nough said? $$-\!\!-\!\!-\!\!\!\!-\!\!-\!\!-\!\!\longleftarrow\!\longleftarrow\!\longleftarrow\!\!-\!\!-\!\!-\!\!\stackrel{0}{\otimes}\!\!-\!\!-\!\!-\!\!\longrightarrow\!\longrightarrow\!\longrightarrow\!\!-\!\!-\!\!-\!\!-\!\!-\!\!-\!\!\stackrel{1}{\otimes}\!\!-\!\!-\!\!-\!\!-\!\!-\!\!-\!\!\longleftarrow\!\longleftarrow\!\longleftarrow\!\!-\!\!-\!\!-$$
Comment: @mobiuseng Derivatives are not necessary here, only signs and zeroes matter, and since the function is already written as a product, there is really nothing to do (that is, nothing else than to apply the theorem which is in the OP's notes).
Comment: The same result analytically: $f(x)=x(1-x)$, $df/dx=1-2x$, on the solution $x=0$ $df/dx=1>0$, hence it is unstable. On $x=1$, $df/dx<0$, hence, stable.
Comment: thanks you very much, as a check for myself, question b) was the same but then with function f(x)= -x(1-x), so f'(x)=2x-1 hence x = 0 is stable and x = 1 is unstable, right?
Comment: Funny, I just explained why derivative is not needed... Anyway, yes, for the dynamics $\dot x=-x(1-x)$, the fixed point $x=1$ is unstable and the fixed point $x=0$ is stable.


XNA: Have I clicked on anything?

Question: I'm making a game in XNA and currently I'm checking the coordinates of the mouse click against the coordinates of each object that can be clicked.
This is fine for my small game but for larger games it would become CPU intensive to check through every object for each frame.
Is there a better way to approach this?
Comment: You might get better answers on the Game Development site: http://gamedev.stackexchange.com/
Comment: I suppose it depends on how many objects. Wouldn't it be easier to always pass the click event, and if an object was clicked, have the object determine if something should happen?
Comment: So instead each object would check to see if the mouse clicked it?
Comment: This is a performance question, so the answer is, of course, **profile it**. This is something you shouldn't have to worry about until your'e getting into the 1000s of objects. And you have even less to worry about if it's per-click, rather than per-frame!
Comment: See also my answer here: http://stackoverflow.com/questions/4524710/xna-2d-mouse-picking/4525667#4525667
Answer: You will want to partition your world space with some sort of algorithm like Quadtree.
In your most basic form you'll want to be able to take all objects and be able to quickly throw out a bunch of them before you even do your detailed check.  For instance, if you are clicking on the right side of the screen you want to throw out everything on the left side of the screen automagically.
Comment: probably not worth it for 10/20 objects.
Comment: Looks like I have a new way of describing how computers work. +1
Comment: Thanks for this answer. I suppose the question for me now is whether or not it would be worth implementing this considering I will only have between 10 and 20 objects that the player can actually click.

XNA: Have I clicked on anything?


$\omega_1(p) \le \omega_2(p)$ for all projections $p$ implies $\omega_1 \le \omega_2$.

Question: Let $M\subseteq B(H)$ be a von Neumann algebra. Let $\omega_1, \omega_2$ be functionals on $M$ satisfying
$$\omega_1(p) \le \omega_2(p) \quad (*)$$
for all projections $p \in M$. Is it true that $\omega_1 \le \omega_2$, i.e. that $(*)$ holds for all positive elements $p \in M$ as well?
I think I need some decomposition result that says that a positive elements is a linear combination with positive coefficients of projections. Do we have such result?
Comment: Yes, we have such a result, it's called the spectral theorem. You probably need some continuity assumption on $\omega_1$ and $\omega_2$, though.
Comment: @MaoWao Thanks! What kind of continuity assumptions? I only assume $\omega_1, \omega_2$ to be norm-continuous.
Comment: That's enough, you can always approximate positive elements by positive linear combinations of projections - see my answer.
Answer: Let $x\in M$ be positive and $e$ its spectral measure (the projection-valued version). By the spectral theorem,
$$
x=\int_{[0\|x\|]}\lambda\,de(\lambda).
$$
For every $\epsilon>0$ there exists a tagged partition $(I_k,\lambda_k)_{1\leq k\leq n}$ of $[0,\|x\|]$ such that $|\lambda-\lambda_k|<\epsilon$ for $\lambda\in I_k$. Then $y=\sum_{k=1}^n \lambda_k 1_{I_k}(x)$ is a positive linear combination of projections in $M$ and
$$
\|x-y\|=\left\lVert\sum_{k=1}^n\int_{[0,\|x\|]}(\lambda-\lambda_k)\,d e(\lambda)\right\rVert\leq \epsilon.
$$
In particular, $x$ is the norm limit of positive linear combinations of projections.
Comment: Amazing! Thanks!
Comment: You're right, I corrected this.
Comment: Thanks again for the help.


Vue is not defined/not a constructor

Question: Hi so I know there are a few questions already related, if not, exactly the same but for some reason none of those answers have worked for me, so I am asking this based on my specific scenario.
I've been using laravel-mix and vuejs for a few months now and just to give you a background I am very new to using webpack or bundlers. I started using laravel-mix because it was required for a project and since then I've been using it even on solo projects. Now that I'm using the new version of laravel-mix and vuejs, I can't seem to make vuejs work!
Let me first show you my webpack.mix.js:
const mix = require("laravel-mix")

mix.js('src/javascript/app.js', 'assets').extract(['vue', 'vue-lazysizes', 'flickity', 'axios'])
   .vue()
   .sass('src/style/app.scss', 'assets')
   .options({
     postCss: [require('tailwindcss')]
   })

And this is my package.json:
{
  "name": "name",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.mix.js",
  "scripts": {
    "dev": "npm run development",
    "development": "mix",
    "watch": "mix watch",
    "watch-poll": "mix watch -- --watch-options-poll=1000",
    "hot": "mix watch --hot",
    "prod": "npm run production",
    "production": "mix --production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@vue/compiler-sfc": "^3.0.11",
    "autoprefixer": "^10.2.5",
    "laravel-mix": "^6.0.13",
    "lato-font": "^3.0.0",
    "postcss": "^8.2.8",
    "resolve-url-loader": "^3.1.2",
    "sass": "^1.32.8",
    "sass-loader": "^10.1.1",
    "tailwindcss": "^2.0.3",
    "vue-compiler": "^4.2.1",
    "vue-loader": "^15.9.5",
    "vue-template-compiler": "^2.6.12"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "flickity": "^2.2.2",
    "lazysizes": "^5.3.0",
    "vue": "^3.0.11",
    "vue-lazysizes": "^1.0.5"
  }
}

And this is what my app.js looks like:
import Vue from "vue";
import axios from 'axios';
import Flickity from 'flickity';
import vueLazysizes from 'vue-lazysizes';

export default {
  directives: {
    lazysizes: vueLazysizes
  }
}
// window.Vue = Vue;
window.Flickity = Flickity;
window.axios = axios;

require("./modules/_global")
require("./modules/_index")

And this is my first Vue object:
let featured = new Vue({
    el: '.featured--vue_js',
    delimiters: ['${','}'],
    data: {
        loadingAnimation: true,
        requestComplete: false
    },

    created(){
        this.requestData()
    },

    methods: {
        requestData(){
            console.log(this)
        }
    }

})

Now here's the problem, every time I uncomment window.Vue = Vue; to declare Vue as a global object, I get an error of Uncaught TypeError: Vue is not a constructor.
Now I've tried removing it and it gives me the error of Uncaught ReferenceError: Vue is not defined.
If I try window.Vue = require('vue'); it gives me Uncaught TypeError: Vue is not a constructor again.
If I try declaring just before my Vue object const Vue = require('vue'); it still gives me Uncaught TypeError: Vue is not a constructor
And I've been doing this all night long and I don't understand why it's not working, so I really need help now because I am going to build quite a lot of functions using Vue and if I can't make it work it's really gonna be bad for me.
So thank you very much! Please don't instantly flag this as a duplicate because no answers have been working for me. Thank you for those who will answer!
Comment: Have you tried to specify vue version in `.vue()` as suggested [here](https://laravel-mix.com/docs/6.0/vue)
Answer: It looks like your initialization code is for Vue 2:
import Vue from 'vue'

let featured = new Vue({
    el: '.featured--vue_js',
    /*...*/
})

But your project has Vue 3 installed, so you should be using Vue 3's createApp():
import { createApp } from 'vue'

let featured = createApp({
    /*...*/
}).mount('.featured--vue_js')

Comment: In Laravel 8 this solution with vue 3 worked for me.  '.featured--vue_js' is html selector,  i changed it to #app. https://v3.vuejs.org/guide/instance.html#creating-an-application-instance

Vue is not defined/not a constructor


Editor placeholder in source file error in handler

Question: I have tried a lot of things (putting   _ :UIAlertAction inside openPage func and inside handler trying different closure etc.) but when there is no Editor placeholder  error i get another error.
What is "Edtor placeholder  in source file" possible errors and solutions
@objc func resenje(){
    let ac = UIAlertController (title: "Prikaz dodavanja drugog tab-a", message: "Zbog novije verzije xCode-a", preferredStyle: .actionSheet)
    ac.addAction(UIAlertAction(title: "https://www.reddit.com",
                               style: .default,
                               handler:{ [weak self] action in self?.openPage() }))
                                       //Editor placeholder in source file !
    ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    present(ac, animated: true)
}
func openPage(){
    let url = URL(string: title!)!
    webView.load(URLRequest(url: url))
}

Comment: Seems like there's a special/invisible character on that line that you accidentally pressed from keyboard? Can you try deleting that line / writing it again? (DO NOT cut/paste).
Comment: (Or copy/paste into an editor like BBEdit that shows special charcters.)
Answer: When you use auto-complete to add template code into your source files, the templates often include placeholders, or strings marked with markup characters, that you are supposed to replace with actual values for your use-case. Function parameters are the most common example of this.
Example: When I type in UIImage(named:, Xcode fills it in with the full function template, plus a placeholder for the value. Viewed outside of Xcode, what I get is:
 UIImage(named: <#T##String#>)!
(Note the <#T##String#> bit, which stands for "variable of type String".)
I don't see any placeholders in the code you posted however.
Comment: I will post a whole code because this does not seems like a problem to simulator


Como classificar a os comentários mais uteis de uma tabela?

Question: Um seguinte cenário:
Cada Produto tem um comentário, cada comentário ira receber um like para informar se foi útil (é opcional informar se gostou do comentário)
Eu tenho uma tabela chamada CustomerReview e uma tabela chamada likeReview e dentro dessa tabela eu tenho a coluna isLike(valores true,falso ou null).Preciso ordenar essa tabela tal forma que os comentários com mais likes positivos ficam no topo da lista.
Como posso fazer isso?
Meu código SQL dá erro quando eu tento ordenar pelo isLike, Pois, haverá comentários da tabela CustomerReview que não estarão associados com a tabela Likereview
Código SQL:
SELECT {c.pk}FROM { CustomerReview c LEFT JOIN     LikeReview l     ON {c.pk  "} = {l.pk} }WHERE {c.product} = ?product AND      {c.LANGUAGE  } = ?languageGROUP BY {c.pk}ORDER BY SUM(CASE WHEN {l.ISLIKE } = "true" THEN 1 ELSE 0 END) DESC

Answer: Pelo que eu entendi de sua explicação, para cada registro em CustomerReview eu posso ter um ou mais  registros na tabela LikeReview, sendo que alguns podem estar marcados com o campo islike como true.
Para trazer os customerReview com maior quantidade de likes marcados como true, você poderia fazer assim:

SELECT {c.pk}FROM { CustomerReview c
LEFT JOIN
LikeReview l
ON {c.pk  "} = {l.fk} }
WHERE {c.product} = ?product
AND      {c.LANGUAGE  } = ?language
AND {l.ISLIKE } = "true"
GROUP BY {c.pk}
ORDER BY COUNT({l.pk}) DESC
Comment: Eu tenho esse erro aqui usando essa consulta que você me sugeriu: cannot search unknown field 'TableField(name='isLike',langPK='null',type=CustomerReview)'
Comment: Exatamente como você entendeu , mas como é opcional eu notificar se gostei do comentário.Entao, pode haver CustomerReview sem likeReview


How does this commutative triangle arises in the idea of freely generated things?

Question: I know that in category theory you normally abstract ideas. So I guess the Universal Mapping Property comes from other fields. In fact, I've already studied free modules and it was there.
I'm trying to figure out how this for every map $f$ there is a map $\overline{f}$ such that $\overline{f}\circ i = f$ comes from. I'm on page 17 of Steven Awodey's book and it talks about the Alphabet being freely generated.
The closet answer I could find was https://math.stackexchange.com/a/2469950/166180. It kinda talks about other map existing but I can't see the connection with this composition/commutative triangle thing. In this example the alphabet is also used. I understand it very well, but I still don't see the connection.
Comment: There's a whole lot of context you're omitting that you should include. For example: What is $i$? What categories are you working in? What are the "types" of $f$ and $i$, i.e. their domains and codomains? Are there conditions on $f$ or $\overline f$? Are you sure Awodey just say "there exists" a map?
Comment: A typical example of such triangle are [homotopy liftings](https://en.wikipedia.org/wiki/Homotopy_lifting_property).
Answer: As Derek Elkins well commented, you miss to give information about 'where do $i,f,\bar f$ live'.
The title of the question suggests that it's about the universal property of the free objects.
So, for a given set $X$, $\ i$ will be the embedding $X\to F(X)$ where $F(X)$ denotes the free whatever structure generated by $X$.
Now, freeness of $F(X)$ says that

For any function $f:X\to A$ which goes to [the underlying set of] some object $A$ of whatever structure, there is a unique morphism $\bar f:F(X)\to A$ (preserving the whatever structure) such that $\bar f\circ i=f$.

Once we know that $i$ is an embedding, $\bar f\circ i=f$ means nothing but that $\bar f$ extends $f$.
In other words, given an 'evaluation' $f(x)\in A$ for all the 'variables' $x\in X$, there is a unique way to extend this to the free object $F(X)$ to obtain a morphism $F(X)\to A$.
To make it precise, one usually states this triangle in $\mathcal Set$ (because $X$ is not assumed to have any structure), and in our formulas we might want to use the 'underlying set' functor $U$ to make things clearer. (Note that $U$ will map a homomorphism to the exact same mapping, but viewed as only a pure function.)
With that, we should rather write $U\bar f\circ i=f$:
$$\matrix{X & \overset i\to & UF(X) \\
&{}_f\!\!\searrow & \ \ \downarrow U\bar f \\
&&U(A) } $$

If you want to work out a specific example, I suggest semigroups (or monoids), as a free semigroup over a set ('alphabet') $X$ is just the set of finite 'words' (sequences) built from elements of $X$, with concatenation as the associative operation. (Free monoids include the empty word as unit element.)
Comment: I completely understand the triangle. What I do not understand exactly is the following:
Comment: Once we define an aphabet, we can multiply elements of the alphabet to come up with words. The set of all words is the free object. In order to define this set of all words, the commutative triangle appears. But why? I know it has something to do with the following:
Comment: given another map $f$ from the set of letters (the alphabet) to another set, then $|f|$ must exist such that $|f|\circ i = f$. Why? What is the purpose of this $|f|$ existing?
Comment: The free construction itself doesn't require the commutative triangles at all. We construct the free object in an appropriate way, *then* we prove it satisfies the universal property.
Comment: The purpose is that we can exchange a $\mathcal Set$ morphism targeted to a structured set for a *homomorphosm* with same codomain.


Difficulties install Drush using composer

Question: I have tried to install Drush on OSX 10.9 but it doesn't seem to have worked. In terminal 'drush status' gives

-bash: drush: command not found

I have followed the instructions on http://whaaat.com/installing-drush-7-using-composer
Composer's directory seems to be correct as my .bash_profile contains:
export PATH="$Trotter/.composer/vendor/bin:$PATH"

Drush exists in the vendor folder of composer

When I tried to install Drush via composer the feedback seemed to suggest it had worked:
Pauls-iMac:~ Trotter$ composer self-update
Updating to version 8e9659bd8317ad3f623c4d17940380443cf8772c.
    Downloading: 100%
Use composer self-update --rollback to return to version 1.0.0-alpha9
Pauls-iMac:~ Trotter$ composer global require drush/drush:7.*
Changed current directory to /Users/Trotter/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing pear/console_table (1.2.1)
    Loading from cache

  - Installing symfony/var-dumper (v2.7.1)
    Downloading: 100%

  - Installing symfony/yaml (v2.7.1)
    Downloading: 100%

  - Installing d11wtq/boris (v1.0.8)
    Loading from cache

  - Removing drush/drush (6.5.0)
  - Installing drush/drush (7.0.0)
    Downloading: 100%

pear/console_table suggests installing pear/Console_Color2 (>=0.1.2)
symfony/var-dumper suggests installing ext-symfony_debug ()
d11wtq/boris suggests installing ext-pcntl (*)
Writing lock file
Generating autoload files
Pauls-iMac:~ Trotter$ drush status
-bash: drush: command not found

(Note I had previously tried to install Drush 6 but hadn't got this to work either)
I would appreciate any advice on what is going wrong here.
Comment: Is `$Trotter` set above that line in the bash script? Any reason not to use the standard `~`? Have you re-`source`d the bash profile since changing it? I think your question just comes down to "why isn't composer's global path in my session's global path", which should hopefully be easy to figure out (and isn't really related to Drupal/Drush as such, in case you're trying to find a solution from either of those systems' points of view)
Comment: @Paul  What php version are you running ?
Comment: @Clive my basic command prompt when opening terminal is: Pauls-iMac:~ Trotter$
Comment: @darol I am running PHP version 5.5.11
Comment: Try changing that to `export PATH="~/.composer/vendor/bin:$PATH"` (assuming you run Drush under that user account), or `export PATH="/Users//.composer/vendor/bin:$PATH"`. Make sure you `source ~/.bash_profile` after making changes unless you start a new terminal session
Comment: @Clive export PATH="~/.composer/vendor/bin:$PATH" worked and now `drush stauts` gives good feedback on the Drush version etc. Thanks. Would you like to add that as an answer and I can mark it as correct?
Answer: Changing the .bash_profile to the following worked:
export PATH="~/.composer/vendor/bin:$PATH"

Now drush status gives good feedback on the Drush version etc. Thanks to Clive for suggesting this.
Comment: It helped me too, but I am too new, and too noob in Ubuntu to know why... Can someone please explain the mechanism behind it to me and further readers? Thanks,
Comment: Type "path in bash profile" into Google @benos. If you don't know what a bash profile, search for "bash profile" instead. These concepts aren't going to be explained on a site for questions about Drupal, they're unrelated
Comment: Sure I will look for it right now --- That suggestion by itself helps me very much, thank you,
Comment: @Clive, after I've closed the terminal via "exit" command I needed to run this again...  Is there a way to change it permanently ? I didn't have time to dive to it from yesterday; I just need a way to change the bash profile permanently so I wouldn't need to run it time and again...
Answer: The linked manual may be outdated. Please follow the steps below.
Installing drush
via Phar binary
Download latest stable release using the command below:
OS X/Unix:
sudo wget -O /usr/local/bin/drush http://files.drush.org/drush.phar
sudo chmod +x /usr/local/bin/drush

Linux:
sudo install <(curl http://files.drush.org/drush.phar) /usr/local/bin/drush

Windows and other
Download manually at https://github.com/drush-ops/drush/releases
via Composer
If you'd like to install drush globally (for all users) and /usr/local/bin is already in your PATH, try installing using the following syntax:
sudo COMPOSER_HOME=/opt/drush COMPOSER_BIN_DIR=/usr/local/bin COMPOSER_VENDOR_DIR=/opt/drush/7 composer require drush/drush:7

or:
sudo COMPOSER_HOME=/var/lib/composer COMPOSER_BIN_DIR=/usr/local/bin COMPOSER_VENDOR_DIR=/var/lib/composer/vendor composer require drush/drush:7

Change drush/drush:7 into drush/drush:dev-master for the latest development version.
via Homebrew (OS X)
Run:
brew install drush

See: Install/Upgrade a global Drush
Answer: I have found the simplest way is to install it with Homebrew
Once brew is installed and working simple type brew install drush.
Comment: But you can't install the latest drush using homebrew.
Answer: My .bash_profile contains exactly
export PATH="$PATH:$HOME/.composer/vendor/bin"

and my drush lies here (Acquia DevDesktop)
export PATH="$PATH:/Applications/DevDesktop/drush"

Answer: This article for installation of Composer with Drush included can be useful:
https://www.pcextreme.nl/community/d/138-drush-installation-for-drupal-shared-hosting


gostaria de saber como posicionar lista com links ao lado de imagens com html e css

Question:

body{
    background-image:url("backgorund.png");
    background-color: #cccccc;
    background-repeat: no-repeat;
    background-size: 800px;
    position:middle;
}

#nome{
    font-size:35px;
    left:60px;
    top:10px;
    position:relative;
}

.imagens{
    list-style-type: none;
    width: 100px;
    height: 100px;
    display: inline-block;
    position: relative;
    position: middle;
}

.links{
    color: black;
    width: 100px;
    height: 100px;
    display: inline-block;
    list-style: none;
    position: relative;
    position: middle;
    left: 80px;
}
<doctype>

            <title>Cartão visitas gabriel</title>
            <meta charset="utf8">

          <link rel="stylesheet" href="cartão.css">

marcos gabriel

@gabrioso__

Marcos Gabriel

gabrioso memes

Comment: sua pergunta não está muito clara, poderia nos dar mais informações de como você quer que aparcem os links na sua página?
Answer: Sua pergunta não ficou muito clara, mas acho que você quer deixar os links da rede social na horizontal junto com o seu nome e cada link respectivo.
Seu Html

      @gabrioso__

      Marcos Gabriel

      gabrioso memes

Seu CSS
.links {
  list-style-type: none;
  flex: grid;
  display: flex;
}

a {
  text-decoration: none;
  font-family: 'Arial';
  font-size: 10px;
}

Segue o exemplo do código acima funcionando: link
Comment: moço, muito obrigado :)


Error while uploading file in drupal "An HTTP Error occured 0"

Question: TLDR: I already figured out when exactly my problem happens so for people too lazy to read full thread please read here. Whenever I have some html content in any textfield in Open Atrium (I'm not sure if that happens just in OA or in Drupal) and I want to upload a file an error "An HTTP Error occured 0" pops up. When I'm disabling javascript I get Error: 403 Forbidden. The HTML must be there before I want to upload something, so it happens when I'm editing some field, not just creating it (so it must be in the database already). And one more thing - it happens also on newly installed instance of Open Atrium downloaded from Drupal's site. (version 1.7)
I'm using open-atrium in drupal. Recently an error started to pop up - "An HTTP Error occured 0" while I try to upload files while editing a node (not while I'm commenting - there it works).
EDIT: I figured when it happens and why, but I cannot figure how to repair it! This issue happens when I have HTML inside content editor. When I select plain text or Markdown the issue doesn't show up and I can upload files! What do you suggest I can try now?
I checked, the file is actually uploaded to server (so it's not permission to directory problem) and I have jQuery Update installed (as some other topics state).
I disabled JavaScript (so it wouldn't be sent with ajax) and the problem still persisted - this time with 403 Permission Error. My page is like this: http://example.com/example/node/225/edit and the permission error is showing something like this:
POST http://example.com/example/upload/js 403 (Forbidden)
Does anyone have any idea what might be wrong? How can I debug it to check what's happening before/after upload? Remember that I actually upload the file to the server, but it just won't attach to the topic while editing (it works on comments).
I'm attaching full HTTP headers sent with the request when JS was disabled:
http://example.com/example/node/225/edit

POST /example/node/225/edit HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:25.0) Gecko/20100101 Firefox/25.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: pl,en-us;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: http://example.com/example/node/225/edit
Cookie: __utma=118809371.977078118.1375778041.1376992641.1378820396.3; __utmz=118809371.1375778041.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); SESSc3f285b6f1567ee5f358af2cabd3c968=5ae3330852770b675d5a76c42a9bbcf1; Drupal_l10n_client=0; DrupalAdminToolbar=expanded%3D0; has_js=1
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------198552096025328
Content-Length: 277355
-----------------------------198552096025328
Content-Disposition: form-data; name="title"

testtest
-----------------------------198552096025328
Content-Disposition: form-data; name="casetracker[pid]"

128
-----------------------------198552096025328
Content-Disposition: form-data; name="casetracker[assign_to]"

Test Test
-----------------------------198552096025328
Content-Disposition: form-data; name="casetracker[case_status_id]"

4
-----------------------------198552096025328
Content-Disposition: form-data; name="casetracker[case_priority_id]"

2
-----------------------------198552096025328
Content-Disposition: form-data; name="casetracker[case_type_id]"

11
-----------------------------198552096025328
Content-Disposition: form-data; name="field_due_date[0][value][date]"

11/23/2013
-----------------------------198552096025328
Content-Disposition: form-data; name="teaser_include"

1
-----------------------------198552096025328
Content-Disposition: form-data; name="body"

fadsfdsf gfgdf fgd s

-----------------------------198552096025328
Content-Disposition: form-data; name="format"

4
-----------------------------198552096025328
Content-Disposition: form-data; name="notifications_team[selected]"

1,11
-----------------------------198552096025328
Content-Disposition: form-data; name="files[upload]"; filename="tinymce_4.0.6.zip"
Content-Type: application/octet-stream

PK
HTTP/1.1 403 Forbidden
Content-Encoding: gzip
Vary: Accept-Encoding
X-Powered-By: PHP/5.2.9
Content-Type: text/html
Transfer-Encoding: chunked
Date: Tue, 19 Nov 2013 11:57:47 GMT
Server: LiteSpeed
Connection: Keep-Alive
Keep-Alive: timeout=5, max=100
----------------------------------------------------------

Answer: This is one of those extremely frustrating errors that can be caused by a lot of things.
Here is a 300+ post long issue in the Drupal 6 Filefield issue queue: HTTP error 0 #297035
Basically, HTTP Error 0 means that an error occurred during some JavaScript or AJAX/AHAH behavior... and that's as helpful is it gets.  The linked issue suggests hundreds of potential causes, but I don't think the short summary's list of solutions necessarily applies to your specific case.  I'm also not 100% certain that the upload/js 403 issue is related.
You indicated that it only happens when a content field is set to allow HTML.  That makes me hopeful that if you enable error logging something is going to show up somewhere.  Even if you don't see anything in your Drupal logs it might be worth digging around for where your PHP is configured to put logs.
You might also want to skim the whole thread and see if one of the many many many solutions there will have a surprise solution.
Comment: I already figured out it only happens, when there are html tags in content (it doesn't matter if it's allowed - even in plain text if u put `` tags it happens). And it happens always like that and only then, maybe thats a bit more helpful info
Comment: Without error logs to work with it's just guesswork.  Maybe you have an installation of PHP whose htmlspecialchars() function crashes Apache.
Comment: `htmlspecialchars` works, but how do I get specific error logs?
Comment: If error logging is enabled in Drupal, it catches almost all the errors and warnings that happen and can be viewed at admin/reports/dblog.

Sometimes failures don't make in onto there, though, so you need to go to the source.
`grep error_log /etc/php.ini` to find out where PHP's logging is happening.  Then make the error happen and look in that log and cross your fingers.

You might also want to find your apache error log, but the config file you need to find is dependent on your operating system.
http://www.cyberciti.biz/faq/apache-logs/