Qt Creator C++ error: No documents matching "ui_mainwindow.h" could be found

Question: I'm currently using Qt Creator 4.15.2. I tried creating a new project in the creator, the .h, .cpp, and .ui files are perfectly linked. If I changed anything in the creator, everything is synchronized. When I selected action->Go to slot, it immediately finds everything.
Then I copied the mainwindow.cpp, mainwindow.h and mainwindow.ui files to my own C++ project. My project has lots of other dependencies so it's hard to create this project directly in the creator. I have successfully included QT5 in my project, so, if I don't use the creator but adding everything manually, everything works fine.
I added the UI file to my CMake list, then opened the UI file in Qt creator. When I changed anything in the creator, the UI file is synchronized and the ui_mainwindow.h file is generated. The problem then comes, if I click action->Go to slot, this error pops up:

No documents matching "ui_mainwindow.h" could be found. Rebuilding the
project might help.

I have tried every method online but none of them worked. Now if I want to include the actions, I have to manually add them in the ui_mainwindow.h file (in this way, it wouldn't automatically add the actions) or mainwindow.h file, which is tedious. Does anyone have an idea of how this could be solved?
Thank you very much!
Answer: I fixed it with these steps:

In my CMakesLists.txt I addded set(CMAKE_AUTOUIC ON)
Right-click on the project, then select "Run CMake"
Rebuild the project
If it doesn't work - restart QtCreator - that helped in my case (QtCreator 4.15.0)
Answer: It seems to be a path directory error. when your auto-generated ui_mainwindow file is not placed in the desired place
also, you can open your UI file with qt designer and from "form -> view source " action menu see the final ui_mainwindow file contents and manually create a ui_mainwindow in your new project.
Comment: Thank you for your kind help. But I couldn' t find this form-view source action in qt creator. Do I need to use qt designer studio instead? On the other hand, I could find the auto-generated file ui file in my project. It's just that none of the actions can be auto-generated. Do you mean that I always need to manually copy the ui_mainwindow.h contents to my new project?
Comment: yes, you can see view source action in the qt-designer application, not qt-creator->designMode.
absolutely no. qt5_wrap_ui command creates your UI files and simply you can access auto-generated UI files. but if you can not share your project and still have the problem, can manually fix this problem .
Comment: or you can use CMAKE_AUTOUIC, somethings like this repository :
https://github.com/jasondegraw/Qt-CMake-HelloWorld


Calculating Standard Deviation when given sample size, mean difference & p value

Question: I am trying to pool data in my meta-analysis and i need MEAN & SD. However the study has reported sample size (27), before (11.8) & after mean (11.9), and p value (0.540).
I need the SD.
Thanks for your help.
Comment: I'm pretty sure there is a way to compute the sd, write down the exact definition of your statistic (by editing your question) and we will be able to help you.
Comment: If a pooled standard deviation is desired then there may well be enough information to find it - if there are two separate SDs required for before and after, I can't see how that would be possible.
Comment: @Silverfish If it's before and after data I expect the data are paired; the $n$ would then presumably be the number of pairs. (However, the OP should be explicit about such details.)
Comment: I removed the `logistic`, `normal distribution` and `r` tags (the first of which seems  irrelevant, even misleading, and the second and third of no direct importance) and added some others that seem to relate to the question being asked. If `logistic` is actually relevant, it's critical you explain *how* exactly it comes into the problem. [You also chose the `self-study` tag -- Is this a problem for a class?]
Comment: @Glen_b Actually you're right, the fact the n is the same and it is before/after means it is very likely paired.
Answer: With before-after data, I presume this is a paired design, and that consequently the test actually being performed is a two-tailed paired t-test. You should clarify to be sure.
If you really only have the means to 3 figures, then 11.8 could represent anything between 11.75+ and 11.85-, while 11.9 could represent anything between 11.85+ and 11.95-.
As such the true difference in means is actually anything between about 0 and 0.2, but more likely to be near 0.1 than the end-values.
Let's take the actual difference in sample means to be $d$.
Then a one-sample t-test statistic would be $\frac{d}{s_d/\sqrt{n}}$, and I presume you're after the standard deviation of the differences, $s_d$.
With 26 d.f., the (absolute value of) a two-tailed t-value that gives a p-value of 0.540 will be 0.621. So we have:
$s_d=d\sqrt{27}/0.621 = 8.37 d$
Now if $d$ was actually 0.1, that would imply $s_d$ is 0.837, but with the information given in the question it might be anything between 0 and 1.674.
If you're able to get $d$ more accurately than this, you can get $s_d$ to similar percentage accuracy.
Even a tiny bit of information - for example, knowing that the original observations must be integer - could help narrow it down (in that case, it would imply that the difference in means would be restricted to lie between 0.037 and 0.148).
Answer: Try ?sd. The sd() function in R will return a standard deviation if you have the original data. However, if you do not have the original data and are trying to determine the SD from only the reported sample size and mean values, then I'm pretty sure you are out of luck. The standard deviation and the mean are describing different things (distribution and central tendency respectively), so you can't get one from the other.
HTH,
Tim
Comment: Thanks Tim. sadly I don't have the original data. Thought there was a way around it using the reported p values and data given. I guess I will have to exclude the study from my analysis. Thanks
Answer: If you can assume that before and after have the same s.d. then you might be able to get an estimate. For example:

s.d.assumed <- 1
print(
mean(replicate(1000,{
x.1 <- rnorm(n = 27,mean = 11.8,sd = s.d.assumed)
x.2 <- rnorm(n = 27,mean = 11.9,sd = s.d.assumed)
t.test(x.1,x.2)$p.value
}))
)

Gives a p.value of ~.48. That's assuming obviously the p-values were calculated using a t-test. You might be able to get an estimate of the sd by putting this idea into a form that you can run an optimization routine on. But a p-value of ~.5 corresponds to a s.d. of ~Inf so it might not be a very good estimate. It would of course be better to get the original data from the authors, if possible.


Daunting series of integrals: $\sum_{n=2}^\infty\int_0^{\pi/2}\sqrt{\frac{(1-\sin x)^{n-2}}{(1+\sin x)^{n+2}}}\log(\frac{1-\sin x}{1+\sin x})dx$

Question: My coleague showed me the following integral yesterday

\begin{equation}
I=\sum_{n=2}^{\infty}\int_0^{\pi/2}\sqrt{\frac{(1-\sin x)^{n-2}}{(1+\sin x)^{n+2}}}\log\left(\!\frac{1-\sin x}{1+\sin x}\!\right)\ dx=\frac{5}{4}-\frac{\pi^2}{3}\tag1
\end{equation}

He also claimed the following closed-form:

\begin{equation}
J=\int_{2}^{\infty}\int_0^{\pi/2}\sqrt{\frac{(1-\sin x)^{y-2}}{(1+\sin x)^{y+2}}}\log\left(\!\frac{1-\sin x}{1+\sin x}\!\right)\ dx\ dy=-\frac{4}{3}\tag2
\end{equation}

$(1)$ and $(2)$ seem difficult to deal with, but I believe there are some tricks that I can use but I'm not able to spot it yet. Using substitution $x\mapsto\frac\pi2-x$, one gets
\begin{equation}
I=\sum_{n=2}^{\infty}\int_0^{\pi/2}\sqrt{\frac{(1-\cos x)^{n-2}}{(1+\cos x)^{n+2}}}\log\left(\!\frac{1-\cos x}{1+\cos x}\!\right)\ dx\tag3
\end{equation}
and
\begin{equation}
J=\int_{2}^{\infty}\int_0^{\pi/2}\sqrt{\frac{(1-\cos x)^{y-2}}{(1+\cos x)^{y+2}}}\log\left(\!\frac{1-\cos x}{1+\cos x}\!\right)\ dx\ dy\tag4
\end{equation}
but I don't know how to use $(3)$ and $(4)$ to evaluate $(1)$ and $(2)$. I'm quite sure that the main problem here is to evaluate
\begin{equation}
K=\int_0^{\pi/2}\sqrt{\frac{(1-\sin x)^{n-2}}{(1+\sin x)^{n+2}}}\log\left(\!\frac{1-\sin x}{1+\sin x}\!\right)\ dx
\end{equation}
How does one prove $(1)$ and $(2)$?
Comment: Have you already tried to set $\frac{1-\sin x}{1+\sin x}=u$ then deal with the logarithm through differentiation under the integral sign?
Comment: Concerning $(1)$ it seems that if you first sum the series then you get an integral which you can handle with derivatives of the Euler beta function.
Comment: @SophieAgnesi Not really.
Comment: @JackD'Aurizio I did, but the different power in the square root make it difficult
Comment: @OlivierOloa I'm not so sure with that.
Comment: @SophieAgnesi Did you try the Tangent half-angle substitution?
Comment: @MarcoCantarini It'd be a hell of a lot of works
Comment: @SophieAgnesi We have $K\leq0$.
Comment: $$u=\frac{1-\sin x}{1+\sin x}\,\,\,\Rightarrow \quad du=\frac{-2\cos x}{{{(1+\sin x)}^{2}}}dx$$
$$\frac{1}{2\cos x}=\frac{1+u}{4\sqrt{u}}$$
Comment: $$I=\frac{1}{4}\sum\limits_{n=2}^{\infty }\int_{0}^{1}\left(u^{\frac{n-3}{2}}+u^{\frac{n-1}{2}}\right)\ln{u}\,du$$
Comment: @SophieAgnesi Can you please check the value of $J$? Thanks.
Answer: Let's employ the weirdo substitution taught by my brother: $\sin x=\tanh t$. Doing so, one will get
\begin{align}
K&=\int_0^{\infty}\sqrt{\frac{(1-\tanh t)^{n-2}}{(1+\tanh t)^{n+2}}}\ln\left(\frac{1-\tanh t}{1+\tanh t}\right)\ \frac{dt}{\cosh t}\\[10pt]
&=\int_0^{\infty}\sqrt{\left(\frac{\cosh t-\sinh t}{\cosh t+\sinh t}\right)^{n-2}}\frac{\cosh t}{(\cosh t+\sinh t)^2}\ \ln\left(\frac{\cosh t-\sinh t}{\cosh t+\sinh t}\right)\ dt\\[10pt]
&=-\int_0^{\infty} e^{-(n-2)t}\left(e^{-t}+e^{-3t}\right)\ t\ dt\\[10pt]
&=-\frac{1}{n^2+1}-\frac{1}{n^2-1}
\end{align}
Thus, evaluating $I$ and $J$ are  easy-peasy-lemon-squeezy.
Comment: Out of curiosity, what would compel someone to try out that substitution? What advantage does it offer (aside from making the problem EPLS)?
Comment: "EPLS" hahahaha +1
Comment: @user170231 I can't speak for Anastasiya's brother, but in my own experience, most unintuitive ('magical') substitutions are just a retrospective shorthand, and were initially a very intuitive *chain* of substitutions.
Comment: @user170231 The obvious fact: $\cosh t\pm\sinh t=e^{\pm t}$
Comment: @TheCount Why on earth did you put the bound in my answer since $K$ must be in the form of $n$??
Comment: @Anastasiya-Romanova秀 Oh my goodness you're right. I'm so sorry. Moment of silliness! Will revert.
Comment: This is a great answer. It shows a new-ish way of thinking, explains it concisely, and is easy to follow.
Comment: (+1) Cool as usual!! :-) Although there's nothing *weirdo* about the sub (successive $x = \arcsin y$ and $z = \frac{1-y}{1+y}$ subs work too!) :-)
Comment: @user170231  what's epls?
Comment: @YoTengoUnLCD A new classification of integrals coined by the OP :)
Answer: Hint.

One may evaluate $(1)$ with the following steps.  From the geometric
series evaluation $$ \sum_{n=2}^{\infty}\sqrt{\frac{(1-\sin
x)^{n-2}}{(1+\sin x)^{n+2}}}=\frac{1}{(1+\sin
x)^2}\frac1{1-\sqrt{\frac{1-\sin x}{1+\sin x}}},\quad
0<x<\frac{\pi}2, $$ one may write $$
I=\int_0^{\pi/2}\frac{1}{(1+\sin x)^2}\frac1{1-\sqrt{\frac{1-\sin
x}{1+\sin x}}}\log\left( \frac{1-\sin x}{1+\sin x}\right)dx. $$ By
the change of variable $u=\frac{1-\tan (x/2)}{1+\tan (x/2)}$ we
obtain a standard integral:

$$ I=\int_0^1\frac{1+u^2}{1-u}\:\log u \:du=\frac{5}{4}-\frac{\pi^2}{3}. $$

One may evaluate $(2)$ by first integrating with respect to $y$ :
$$
    J=\int_{2}^{\infty}\!\sqrt{\frac{(1-\sin
    x)^{y-2}}{(1+\sin x)^{y+2}}} dy=-\frac2{(1+\sin x)^2\log\left( \frac{1-\sin x}{1+\sin x}\right)},\quad
0<x<\frac{\pi}2,$$ then integrating with respect to
$x$ one gets a standard integral: $$
J=\int_{2}^{\infty}\!\!\int_0^{\pi/2}\sqrt{\frac{(1-\sin
    x)^{y-2}}{(1+\sin x)^{y+2}}}\log\left(\!\frac{1-\sin x}{1+\sin
    x}\!\right)\ dx\ dy=-\int_0^{\pi/2}\frac{2\:dx}{(1+\sin x)^2} $$ which gives

$$ J=-\frac43. $$
Comment: Let me check your answer later. (+1)
Comment: You turned out to be correct that $J=-4/3$. Merci beaucoup Olivier.
Comment: De rien, @SophieAgnesi.


drupal_set_title not setting $title variable

Question: I'm trying to use drupal_set_title() in my node.tpl.php but the text I'm setting the title to is only showing up in the $head_title (html.tpl.php) variable and not the $title variable. The $title variable is still set to the node's title.
This is in Drupal 7. I've used drupal_set_title() multiple times like this in Drupal 6 and it has worked perfectly.
Is this broken in D7?
This is how it is being used in node--news.tpl.php:
$actual_title = $title; // save for later use
drupal_set_title('News');

Comment: Could you please show us the code showing how you are using it?
Answer: By the time you've hit node.tpl.php it's too late to set the title as $head_title has already been set in template_process_html() and the $head_title variable has already been output.
You'll need to use template_preprocess_node() or similar to set your title as desired.
Answer: Apparently trying to set the title in node.tpl.php is too late in the execution order. Same goes for template_preprocess_node(). Instead, it can be set in template_preprocess_page:
function mytheme_preprocess_page(&$vars){
    if (isset($vars['node']) && $vars['node']->type == 'news'){
        drupal_set_title('News');
    }
}

Comment: it's poor form to reiterate the same answer Dave gave but mark yours as the accepted answer when asking a question. Please change.


Windows 7 CD keys, are they interchangable?

Question:
Possible Duplicate:
Can you help me with my software licensing question?

I am talking about during installation. Using regular licensing, not volume licensing.
Amongst OSes of the same class, are CD keys interchangeable or are they locked to a specific subset of CDs?
In other words: If I have 10 legally purchased copies of Windows 7 Professional, can I throw out the discs for all but one? And all the CD keys will work?
UPDATE: How about for service packs (when they come out). If I have Windows 7 Professional SP1 and a Windows 7 RTM original? Do they change CD keys between service packs?
Answer: Yes, you can interchange them. You can use a given license key with any media, 32 or 64-bit, for the same type of installation. If you try to activate a retail disk with an OEM key, or vice-versa, you may need to call the Microsoft activation hotline to complete the process. Service packs do not affect activation of legal copies of Windows.


Como inserir nova imagem em projeto com COMPASS

Question: Tenho as imagens que utilizo em meu projeto e desejo adicionar uma nova imagem para utilizar no site, porém não consigo fazer com que a imagem seja adicionada aos sprites gerados pelo COMPASS
Comment: Caçando assunto acabei de conseguir fazer...
1 - Na pasta ICONS adicione a imagem que deseja adicionar ao projeto;
2 - Na pasta images (antes de ICONS) exclua o sprite gerado pelo COMPASS para seu projeto;
3 - Recompile os arquivos que a imagem sera automaticamente gerada no local correto

Pronto, basta utilizar a imagem adicionada
Answer: Para fazer sprite com compass precisamos isolar as imagens que desejamos juntar em uma pasta, que se chamará sprite e ficará dentro da pasta imagens.
Precisamos avisar o Compass que sempre que houver um arquivo .png na pasta, ele precisa ser atualizado. Para isso, iremos ao seu principal.scss e acrescentaremos uma linha que diga isso:

@import 'sprite/*.png'

Veja que apos salvar o terminal vai responder

create imagens/sprite-s1e1f3a7a9e.png

Ele comunica que o Compass criou um sprite com aquele nome
E após fazer e desfazer com essa  pequena alteração no seu principal.scss, apenas para que o Compass detecte uma alteração e compile novamente, voce pode verificar o resultado na pasta imagens.


ASP.NET and HTTP 404 problem (IIS problem)

Question: net webforms application which is a new version of an old webshop. I have a lot of inbound links from the Internet, that point to a particular category page: http://www.example.com/category1.html, the path to this category in the new setup is similar to: http://www.example.com/category.aspx?id=42.
I have setup the Category.aspx page to handle errors and redirect to a custom page, log the error and redirect to my front page.
I have setup the Global.asax Application_Error to do the same
I have setup the Web.config, with custom errors to relay 404 using the same concept as above.
Everything is working as it should in Visual Studio (the build in web server), when i publish it to my web host, it doesn't work, they say it is running in integrated mode... anyone got a solution to this?
Comment: And if you want to access just category.aspx does it work? Does it log any error? Is HTTP 404 based on your redirection or is it fired by IIS? The web application in IIS can be incorrectly configured so that http://www.example.com/... doesn't point to your application.
Answer: With the build-in webserver, every request is handled as if it were an asp.net page, so your web.config is always used in that case.
In IIS however, .html is not handled by asp.net but by the static file handler, so the web.config is ignored (altough IIS7 looks at the web.config for some stuff, but that's not relevant for your problem)
So you need to either have .html handled by asp.net (set the .html extension to be handled by the same dll as the .aspx pages in IIS) or you should set the error-page in IIS (and not in your web.config).
Answer: The IIS running in Integrated mode, so i finally found out that i couldnt handle this the way i did, i write a httphandler, registered it in the web.config and assigned it to intercept all calls made to *.html files. All i had to do was then to rediret to the proper source page.


ActiveRecord collection level relation accessor

Question: Given a model Event which
has_many :user_events

And a model UserEvent which
belongs_to :event

I could get the related user_events from a single event object, like so:
event = Event.find(1)
user_events = event.user_events

But is there an equivalent relation accessor for a collection of events? For example:
events = Event.where(:event_type => 'fun')
user_events = events.user_events

Which would return the user_events which belong to any 'fun' events using something like.
SELECT user_events.* FROM user_events JOIN events on (events.id = user_events.event_id) where (events.event_type = 'fun');

Answer: No, there isn't a relation accessor for a collection of events.
In the meantime, you can do:
events = Event.includes(:user_events).where(:event_type => 'fun')
user_events = events.map(&:user_events).flatten

The user_events are eager loaded thanks to includes(:user_events). That's commonly used.
We use the same logic when we do things like that (simplified):
# controller
@posts = Post.includes(:comments)

# view
<% @post.each do |post| %>
  # display your post
  <% post.comments.each do |comment| %>
    # display each comment
  <% end %>
<% end %>


Show total value by month and difference in spotfire

Question: Ive got the following plot in spotfire showing the total value per month and the difference of value from one month to the next

I need to show each month the total value of the month, not cumulative with past months, and also the difference, like shown below

Any suggestions?
Thanks
Answer: This is not possible using Spotfire. I would suggest you to have 2 different visualizations:

A Bar chart with the Sum(Closing Value)
A Waterfall chart with the Difference


Problems with FasterCSV (Ruby)

Question: I'm writing a program, that creates a csv-File. And I have a problem right at the beginning.
So, my code is
  def create_csv
      destfile = Rails.root.join("public", "reports", "statistic_csv#{id}.csv")
      csv_string = FasterCSV.generate do |out|
         out << ["row", "of", "CSV", "data"]
      end
   FasterCSV.open(destfile, "w") do |csv|
      csv << csv_string
   end
  end

I thought, I will get 4 columns in the output file, smth like this row|of|csv|data. But what I get is "row,of,CSV,data" in one cell A1. How can i solve the Problem? Thanks in advance!
PS. I use ruby 1.8.7 and FasterCSV 1.5.5
Answer: You are encoding the CSV string twice. This should work:
def create_csv
  destfile = Rails.root.join("public", "reports", "statistic_csv#{id}.csv")
  FasterCSV.open(destfile, "wb") do |csv|
    csv << ["row", "of", "CSV", "data"]
  end
end

You can also specify a custom column separator:
FasterCSV.open(destfile, "wb", { :col_sep => "|" }) do |csv|
  # ...
end

Answer: I presume you're opening this in Excel.  Excel may not be detecting the file as a CSV file.  Try importing the data into an excel workbook as opposed to opening the file in Excel.
Comment: Thanks, I did as you said, and now it looks much better. But now there are some quotation marks in the text "row of CSV data
" "blabla
"

Problems with FasterCSV (Ruby)


Rational numbers from irrational numbers

Question: Can any real function of irrational numbers  be rational ? If possible, please give examples. Special case  $ e^ {\pi i } = -1 $ seems to restrict solutions entirely to complex numbers. The question is right now vague as I do not know how to  exclude "obviously  derived " examples.
Comment: @YvesDaoust $f(x)=|x|$?
Comment: Maybe more interesting to try to find a surjection $\mathbb{R}\setminus\mathbb{Q}\rightarrow\mathbb{Q}$.
Comment: On the opposite, can you find a continuous function that never maps an irrational to a rational, other than a rational fraction ?
Comment: @Wojowu: all piecewise functional inverses of rational fractions with rational coefficients never map an irrational to a rational. $|x|$ is such a function.
Answer: Sure. Choose any constant function $f : \mathbb R \setminus \mathbb Q \to \mathbb Q$, for example
$$f(x) = 1 \quad\text{ for all } x \in \mathbb R \setminus \mathbb Q$$
If this answer seems flippant, you may want to sharpen the question.
Comment: For kicks, define it as conways base 13 function everywhere else.
Answer: The cosine of $\pi$ is -1, a rational number.
Answer: You can construct required function from any real function, rounding the result to finite number of decimals.
Answer: What about $f(x)=x^2$? One has $f(\sqrt2)=2$.
Comment: should work for any, not only for square roots ...
Comment: @oops, algebraic of course.
Comment: More generally, all algebraic numbers evaluate to $0$ for some polynomial function.
Comment: @YvesDaoust, what you say is ambiguous (in English!). Better to say, "Every algebraic number evaluates to $0$ for some polynomial function".
Comment: @Lubin: I agree.
Answer: A well-known example.
Is $m:=\sqrt{2}^{\sqrt{2}}$ rational?  If yes, that is your answer.
If no, then $m^\sqrt{2}$ is your answer: $m$ and $\sqrt{2}$ are irrational, but
$$
m^\sqrt{2} = \left(\sqrt{2}^\sqrt{2}\right)^\sqrt{2}
=\sqrt{2}^{(\sqrt{2}\cdot\sqrt{2})} = \sqrt{2}^2 = 2
$$
is rational.
Comment: [This question](http://math.stackexchange.com/questions/1223725/) generalizes this example.
Answer: I don't understand your question, since it seems to be insufficiently quantified. Do you mean, "Is there a function that takes every irrational number to a rational?"? Or do you mean, "Given an irrational number, is there a function that takes it to a rational image?"? Your example seems to support the second interpretation, in which case I'd suggest the function $f(x)=x/a$, if your given irrational number is $a$.
And you didn't say what kind of function you were allowing. Any continuous function? Analytic? I can suggest all manner of discontinuous functions that take irrationals to rationals, beyond of course the ultimate in continuity, the constant functions.
Comment: I meant a situation about any  function of rationals  mapped  from independent irrational variable numbers,
Answer: According to a famous theorem about trascendental numbers for all $\alpha$ real algebraic with $1\ne\alpha\ne0$ the number $\ln \alpha$ is trascendental. Consider the function $f(x)=e^x$ which is a bijection of $\mathbb R$ onto $]0,\infty[$; take now un $r\in$ $\mathbb Q^+ $, for instance $r=7$; there exists x such that $f(x)=7$ but $f(x)=e^x=7\iff x=\ln 7$ hence $x$ is a trascendental number whose image by $f$ is rational.
You have this way infinitely many rational $r$ such that if $x=\ln r$ then $f(x)=r$ where x is irrational (it is trascendental indeed).
Comment: Is the theorem that you mention a particular case of the [Lindemann-Weierstrass theorem](https://en.wikipedia.org/wiki/Lindemann%E2%80%93Weierstrass_theorem)?
Answer: Several.
f(x) = x - x = 0
f(x) = x / x = 1, for x in R - {0}
f(x) = round(x, 5), where round() rounds a number to the specified quantity of decimal places.
The Dirac delta.
f(x) =
    1 if x in Q,
    0 if x not in Q

f(x) =The average of the first 10^6 digits of x (in base 10).
And so on...


How can I load content on the same page from a search

Question: So the idea is to load the results of the search on the same page. I was told to look into SOLR, but it looks like we have something similar to SOLR , and we just need to know how to load new page content into our drupal site. Alternate to iFrame.
Answer: you to load the search results on the same page - the same page as what? do you mean without a page refresh? If that's the case, then I think you're looking for Search API Ajax:
This module can ajaxify Seach API pages and views. Ajax made possible by
Drupal 7 core's jQuery BBQ (previous YUI3 History library is dropped).

and perhaps Ajax Facets:
This module allows you to create facet filters which working by AJAX.
Filters and search results will be updated by AJAX.

There are a few more suggestions here
Comment: Yeah, without a page refresh. Thank you for your answer. I was just told that none of the information the user will be searching for will be in the drupal site. Our catalog is being hosted and serviced by a 3rd party. So the question now is can we display the information from the search result on the same page with ab iframe?
Comment: so, are you trying to use the Drupal site as a front-end and then feed the search criteria to another site that will do the actual search and return the results to the Drupal site, or is the search itself as well as the results part of the other site (i.e. - is all of the search page elements contained within the frame)?
Comment: Yes, exactly, feed the search criteria to another site that will do the actual search and return the results to the Drupal site
Comment: First you will need to create a custom Form, and then doing that depends on the API for the other site. The answer depends on the type of data returned from the search API


Dot product/Scalar product with lengths

Question: I have a question about finding the dot product when I am given only $\left|a\right|=5$, $\left|b\right|=3$ and $\left|a-b\right|=6$. Have no given angle between vectors so how am I supposed to do this?
Comment: Hint: $\left|a-b\right|^{2}=\left$, now expand the expression.
Comment: @yolobird What do you know about dot product? I'll just note that $\left=a\cdot b$ in case you are not familiar with this notation.
Comment: @eranreches still doesn't help me :(
Comment: @eranreches (Not OP) I'm not sure I understand the hint, could you elaborate a bit more slightly? How does a scalar, $|a-b|^2$, equal a vector?
Comment: @AndrewTawfeek $\left$ is the dot product of the vector $a-b$ with itself, hence a scalar.
Comment: @eranreches I do know that **⟨a,b⟩=a⋅b**, but I still don't know how that hint would help me.
Comment: @eranreches Ahhhh, it was the notation that threw me off! I usually see $a \cdot b$ as you realized. I recall sitting in on a Lie Algebra class while visiting somewhere and seeing the $\left< a,b\right>$ notation used for inner products, so I apologize for not realizing that immediately :)
Comment: @yolobird So use the fact that $\left=\left+\left$ and $\left=\left+\left$ to simplify the expression.
Answer: You have
$$\left<a-b,a-b\right>=|a-b|^2$$
and simplifying:
$$\left<a,a-b\right>-\left<b,a-b\right>=\left<a,a\right>-\left<a,b\right>-\left<b,a\right>+\left<b,b\right>=36$$
and because
$$\left<b,b\right>=b\cdot b=|b|^2=9$$
and
$$\left<a,a\right>=a\cdot a=|a|^2=25$$
and because of commutativity
$$\left<a,b\right>=\left<b,a\right>=a\cdot b$$
we get
$$25-2a\cdot b+9=36$$
$$-2a\cdot b=2$$
$$a\cdot b = -1$$

Dot product/Scalar product with lengths


Sampler Track Resets In Logic Pro X

Question: I've chopped up an audio file into smaller pieces, selected them all and created a sampler track through the Convert To New Sampler Track feature in Logic Pro X. I've set the project to copy audio files and copy EXS instruments and samples into the project via File->Project Settings->Assets and checking off the appropriate boxes.
Every time I reload the project it gives me an error saying"EXS24 instrument '<filename>' not found.". How can I stop this from happening. I know how to relink the sampler track to the file, but it's annoying that I have to go through this process every time I open the project. Anyone have any ideas on how to fix this?
Here's what happens and here's how I fix it, but like I said, it's a fix I have to apply each time I load the project:
1) After loading the project I get this message

2) Here's an image of the sampler track (it was derived from the audio track above it)

3) Open the instrument settings

4) Reset the instrument
Comment: I'm not familiar with LogicX but am very familiar with Logic9.  I'm not completely sure I understand what is going wrong for you but if I am understanding it correctly, it seems like you could just save the instrument as a preset, like you would find in the 'Library', and access it like any other preset.  Again, I'm not really sure if this would be helpful, so that's why I'm suggesting in the comments instead of an answer.
Comment: I see what you're saying. Unfortunately it did not work. I went to the dropdown where it says `User Default` and I clicked on `save as` and then saved the preset. The same error message comes up when I reload the project though. I'll update my question so that you see exactly the process I have to do to fix it.
Comment: I'm thinking that you would want to save the preset in the original project, then open the preset on a track in the new project.  It may be terribly obvious but don't forget to save once you have made the changes.
Comment: Just tried it. In the new project, it allows me to load the preset, but the underlying samples that are mapped to each key are not present.
Comment: What I see above is a little different than I was thinking but should work no different than what my suggestion would have done. I meant to suggest that you save the Track as a preset, not the instrument within the plugin, but I now suspect this wouldn't resolve the issue. It might be the way the presets are named, with ".exs_#" in the name. The extension being included in the name might be confusing Logic when trying to load the plugin. Maybe try renaming the preset without ".exs" in the name.  I would also try saving another instrument and doing the same thing to see if you can replicate.
Answer: You need to go into the EXS24 instrument that you've created and "export" the instrument and samples and then reload from the exported EXS24 instrument.
The detailed steps follow, but first and overview.  You are going to

Export your EXS24 Instrument and save it somewhere (anywhere).
Remove the plugin from the track.
Reload it from your export.

Now here are the details:

Copy and paste your .logicx package in the finder to make sure you have a backup.
Open your .logicx project.
Do what you have been doing to clear the error and get your EXS24 instrument working properly.
Open the EXS24 Plugin.
In the upper-right of the instrument you should see two buttons, "edit" and "options", click "edit"
In the EXS24 Instrument Editor window that opens, find the "Instrument" menu along the top.
Select Instrument->Export Sampler Instrument and Sampler Files
A typical Mac OS X Save Dialogue will open.  Create a new folder somewhere and save your EXS24 instrument inside it.
Close all the EXS24 windows and get back to your main Logic arrange window.
In the inspector (or in the Mixer) click on your EXS24 instance and get rid of it by selecting "No Plugin"
File -> Save As.  Make absolutely certain that "Copy the following items into your project -> EXS24 Instruments and Samples" is checked.  If so, you can cancel the Save AS.  If not, then check it and click Save.
Do a Save As again, make absolutely certain that item is checked!!!
Go back to your track, add an EXS24 plugin.
Open the new EXS24 instance, At the top it should say Factory Default
Click the "edit" button in the upper right.
In the EXS24 Instrument Editor, select Instrument->Open
Open the exs file you created in step 8.
Close the EXS24 windows to get back to your arrange window.
Save your project.

Now Logic should save your instrument and samples properly and the next time you open the project you should not be prompted to find the instrument/samples.
If this fails, try these folks http://www.logicprohelp.com/
Comment: Cool...yes, please clarify your answer a bit, I'm not quite following. Thanks for the initial post though.
Comment: Is your project saved as a "folder" or a "package"?
Comment: It's a package.
Comment: I don't know what went wrong the first time, but basically what I'm suggesting is try to get logic to do the right thing by getting rid of the instrument and reloading it.

Sampler Track Resets In Logic Pro X


SQL Server query - Min, Max, Avg aggregates issue

Question: I would like to have some statistic data (min, max, average) from a database but I am currently facing a problem. I think the syntax is incorrect but I am not sure. I can not get expected results.
Here is the table;
name          period    b   c
-----------------------------
KONYA       July - 2014 7   3
KONYA       July - 2014 8   5
KONYA       July - 2014 9   9
KARAMAN     July - 2014 5   2
KARAMAN     July - 2014 4   5
LYON        July - 2014 5   1
LYON        July - 2014 6   9
LYON        July - 2014 7   7

Here is what I expect;
name          period      max(b)    min(b)   max(c) min(c) ...
--------------------------------------------------------------
KONYA       July - 2014     9        7         9      3
KARAMAN     July - 2014     5        4         5      2
LYON        July - 2014     7        5         9      1

And my sql query;
SELECT
    name,
    max(b), max(c), min(b), min(c)
FROM
    tablename
GROUP BY
    name, b, c;

Could you please help me ?
Thanks in advance.
Comment: You should only be GROUP'ing on 'name'
Answer: Remove b,c from group by and add period instead
SELECT name,period,
max(b), max(c), min(b), min(c)
FROM tablename
group by name,period


Size of the image (rank) in $T_n$

Question: For $\alpha, \beta \in T_n$ (full transformation semigroup/monoid - set of all maps from $\{1,2,\ldots, n\}$ to itself), show that $|\text{Im}(\alpha\beta)| \leqslant |\text{Im}(\alpha)|$ and $|\text{Im}(\alpha\beta)| \leqslant |\text{Im}(\beta)|$.
How do you show this (apparently it's easy)?
Answer: I haven't read Sammy Black's proof in detail, but I think an answer consisting mainly of words might be more illuminating.
Let $X = \{1,\ldots,n\}$.  Let $k = |\operatorname{Im}(\alpha)|$ and $m = |\operatorname{Im}(\beta)|$.
You didn't say whether your transformations are acting on the left or the right.  I'll assume they act on the right.
To obtain $\operatorname{Im}(\alpha\beta)$, we act on $X$ first by $\alpha$ and then by $\beta$.  Once we have acted by $\alpha$, we have $k$ points left to be acted on by $\beta$.  Since $\beta$ is a function, this can produce at most $k$ points.  But also, since $\beta$ maps the whole of $X$ to $m$ points, it certainly maps $\operatorname{Im}(\alpha)$ (which is a subset of $X$) to at most $m$ points.
So $|\operatorname{Im}(\alpha\beta)|$ is bounded above by both $k = |\operatorname{Im}(\alpha)|$ and $m = |\operatorname{Im}(\beta)|$.
Answer: If $k \in \operatorname{Im}(\alpha\beta) \subseteq \{1, \dots, n\}$, then there is some $i \in \{1, \dots, n\}$ such that $\alpha(\beta(i)) = k$.
This equation shows that $\alpha$ maps $\beta(i) \mapsto k$.  In other words, $k \in \operatorname{Im}(\alpha)$, and so $\operatorname{Im}(\alpha\beta) \subseteq \operatorname{Im}(\alpha)$.  Note that we only have equality $\operatorname{Im}(\alpha\beta) = \operatorname{Im}(\alpha)$ if $\beta$ is onto (hence bijective, as $\{1, \dots, n\}$ is finite).
For the second inequality, the correspondence $\operatorname{Im}(\alpha\beta) \to \operatorname{Im}(\beta), k \mapsto \beta(i)$, which involves arbitrarily choosing a preimage $i$, is injective.  Why?  Let $k, k' \in \operatorname{Im}(\alpha\beta)$ and choose $i, i' \in \{1, \dots, n\}$ such that $\alpha(\beta(i)) = k$ and $\alpha(\beta(i')) = k'$.  If $\beta(i) = \beta(i')$, then by application of $\alpha$, it follows that $k = k'$.  Note that we only have the bijection $\operatorname{Im}(\alpha\beta) \cong \operatorname{Im}(\beta)$ if $\alpha$ is one-to-one (hence bijective, as $\{1, \dots, n\}$ is finite).

Size of the image (rank) in $T_n$


partial fraction decomposition of $\frac{(2l+1)(l+1)}{K+(l+1)(l+2)(l-1)}$

Question: I am struggling with the partial fraction decomposition of
$$\frac{(2l+1)(l+1)}{K+(l+1)(l+2)(l-1)},$$
where $K$ is a positive real number.
I would like to decompose it in a sum of simpler polynomial fractions.
I tried the Mathematica's function "Apart" but it is returning the fraction so I am thinking there is no simple partial fraction decomposition.
Could you help me?
Comment: The decomposition depends on how $K$ and $l$ are related. There is no general decomposition that will work for all $K.$
Answer: i think the simpliest form is this here $${\frac {2\,{l}^{2}+3\,l+1}{{l}^{3}+2\,{l}^{2}+K-l-2}}$$
Comment: Is it possible to have simpler than that? That's because I am eventually looking  at series of legendre polynomials having that fraction as coefficient


How much time does it take to manage sites within a multisite architecture as compared to multiple single installs?

Question: A service my company offers is similar to managed hosting where we help keep a server, Drupal, related modules, and backups up to date on behalf of clients who can't or don't want to do that in house, and typically this averages out to be about 30 to 90 min of work per site per month.
A client has asked me to manage their entire portfolio of 70 Drupal sites, all of which are part of a multisite architecture with site files on one server and DB on another.
I can't imagine that this is 70 hours of work, but I'm not familiar enough with multisite installs of this size to understand fully what this would entail.
To ensure that I estimate time correctly, what would I need to take into consideration when comparing management solutions for single server / single site installations as compared to the same number of sites in a multisite installation?
Comment: It's really difficult to answer this, as keeping something up to date can mean a lot of things. The main difference between multi site setup and non multisite setup, is that they share code, which means you probably can deploy a lot / all of the sites with a single script. If the sites a very different and you have to test that updates wont break anything etc, it wont matter much that they are multi sites. If the site are near identical you can potentially save a lot of time.
Comment: As a small hint about keeping modules up-to-date you can use some common services, e.g. https://www.drop-guard.net/. They are doing all the updates. But I do not know if they are working with multisiting, you can ask.
Answer: Short: It really depends.
Long: Each individual multisite installation adds complexity to the whole. If these 70 sites are more ore less the same in terms of individual content but (nearly) same codebase, modules and similar themes (imagine a large organization spread over the world with region specific characteristics), you'll most likely need less time to maintain.
If these are 70 profoundly individual sites, you'll probably end up checking dependencies over dependencies for modules and themes, debugging deadlocks and incompatabilities. Maintaining this can be a real challenge and 70 hours a month are gone faster than you have "drushed and rollbacked" everything to working.
Accurate documentation and a SLA designed fair for both parties should be the key to a successful maintenance.
(I maintain a multisite installation with around 30 instances for a large organization with all the pros described above.)
Comment: Would you mind sharing about how long maintaining 30 takes you and example tasks you spend that time on? (If commenting publicly about that info would be ok, that is.) An experience like yours is exactly what I'd like to draw from.
Comment: I can't share numbers, but gut feeling says it's about a third of the time compared to single installations when it comes to keeping modules and core up to date. The most time-consuming tasks are the feature-requests from single divisions. We process all this with a ticketing system and a good SLA. As you can imagine a global organization tends to spread in different directions, both form and content-wise. So keeping everything in line is the real challenge (thank god there's a marketing office with the last word).
Answer: Maybe you should include Aegir in management. Aegir, along with Drush, can help you a lot to automate some tasks, from backups, verification, enabling / disabling SSL, adding new or removing existing platforms and their multisites.
Answer: I can say that you should take into consideration that managing multisite drupal installation usually takes less time then handling same amount of single installations. I will briefly explain how it can be done for drupal 7
1) when you download drupal you can find sites folder in root;
2) You can add as many websites as needed inside sites folder, just create for example "example" folder;
3) In example folder create settings.php file
<code>$databases['default']['default'] = array (
  'database' => 'example',
  'username' => 'admin',
  'password' => 'admin123,
  'host' => 'db_host_address',
  'driver' => 'mysql',
);
</code>
4) create modules, themes, libraries folder for site specific modules, themes and libraries in sites/example folder. All common (used by more then one site or features which potentially can be used in future by multiple sites) modules, themes, libraries can be added into corresponding folders inside sites/all directory.
5) To establish http connection with example website you should create server alias then add sites.php file inside sites folder.
<code>$sites['localhost.example'] = 'example';
</code>
where localhost.example is your server alias and example is your site folder.
you should take into account that in future it will be easier to update drupal core and contributed modules but as cons you should take into account that during each common change all websites which use changed module, theme should be tested well. In case of updating core all sites should go through round of testing.
From my personal experience multisite installation is easier to maintain. I wish you good look with your task!


Como manter os 100 últimos objetos inseridos em um ArrayList?

Question: Como manter os 100 últimos objetos inseridos em um ArrayList? Este será constantemente alimentado mas quero manter apenas os últimos 100.
Comment: Qual é a dúvida?
Comment: Um Arraylist sempre adiciona novos elementos ao fim da fila. Você terá que criar um método que trate a adição, verificando antes se a lista já possui 100 itens e em caso positivo, remover o primeiro antes de adicionar um novo, usando algo como  `if(lista.size == 99){lista.remove(0);}lista.add(element);`
Comment: Eu acho de extrema importância você resolver esse problema sozinho. Então depois, jogue aí o código que você conseguiu, que agente ajuda.
Answer: A maneira mais simples de resolver este problema é aplicanto o conceito de FIFO (First in, first out).
Fifo refere-se a uma estruturas de dados do tipo fila.
As listas são amplamente utilizadas em programação para implementar filas de espera. Em uma fila de tipo FIFO os elementos vão sendo colocados na fila e retirados (ou processados) por ordem de chegada. A ideia fundamental da fila é que só podemos inserir um novo elemento no final da fila e só podemos retirar o elemento do início.

Você pode ver mais aqui
Além deste conceito será preciso limitar o volume de registros que vc quer armazenar, desta forma indico utilizar o Apache Commons Collections
Se estiver utilizando maven poderá fazer o import:
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.1</version>
</dependency>

Se estiver utilizando gradle
`compile group: 'org.apache.commons', name: 'commons-collections4', version: '4.1'`

Basicamente você so precisa adicionar a biblioteca commons-collections4 em suas dependencias, para exemplificar utilizei a verão 4.1.
Após fazer o import você pode criar suas listas previamente limitadas por exemplo:
 new CircularFifoQueue<String>(100)
 new CircularFifoQueue<Integer(100)

entre outros.
Para exemplificar melhor fiz um exemplo criando string aleatórias e armazenando na fila, ao final exibo os valores restantes:
public static void main(String args[]) {
    Collection<String> fifo = new CircularFifoQueue<String>(100);
    for (int i = 1; i <= 500; i++) {
        String id = UUID.randomUUID().toString();
        System.out.println(i + " - " + id);
        fifo.add(id);
    }

    System.out.println("----> Result Fifo <----");
    int i = 1;
    for (String id : fifo) {
        System.out.println(i++ + " - " + id);
    }
}

Comment: Excelente e mais elegante! .. vou usa-la!
Answer: Consegui chegar no que eu queria com while..
public static void main(String[] args) {
    // TODO Auto-generated method stub

    ArrayList<String> arr = new ArrayList<>();

    for(int i = 0;i < 150 ; i++){
        arr.add(Integer.toString(i));
    }

    while(arr.size() >= 100){
        arr.remove(0);
    }

    for(String x : arr){
        System.out.println(x);
    }

}

Comment: Só uma correção: este site [NÃO é um fórum](https://pt.meta.stackoverflow.com/q/2068/28595).
Comment: Limite-se a colocar na resposta somente aquilo que responda a pergunta. Use os comentários (quando tiver reputação para isso) para fazer comentários adicionais, que não competem à resposta.


Why is map changing my original array while iterating over?

Question: const z = [
    [
        "Almond",
        54
    ],
    [
        "Oats",
        75
    ],
    [
        "Raisins",
        undefined
    ]
]
let temp=[];
z.map((item, index) => {
    temp.push(item);
    if (item[item.length - 1] === undefined) {
      temp[index][1] = 'Not available'
    }
  });
console.log(temp)
console.log(z);

I'm changing the undefined entry to 'Not available' by creating another array.
I'm not able to understand my z array is changing along with temp.
Comment: Because temp and z both hold references to the same arrays.
Comment: You're also misusing `.map()`. Either use a `.forEach()` (or even better, a regular for-loop), or use `.map()` properly by returning the new element value and using the array returned by `.map()`.
Comment: [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language)
Comment: `const result = z.map(([product, stock]) => [product, stock ?? "Not available"])` I assume that the second element is the stock, but if it represents something else you can rename the parameter to whatever you want.
Answer: A better approach would be to return a result array, mapping each entry in the item array to 'Not available' if it is undefined and then last entry in the item array.
This will leave the original z array untouched.

const z = [ [ "Almond", 54 ], [ "Oats", 75 ], [ "Raisins", undefined ] ]

let result = z.map((item, index) => {
    return item.map((val, idx) =>  {
        let notAvailable = (val === undefined) && (idx === item.length -1);
        return notAvailable ? 'Not available': val;
    })
})

console.log('z:', z);
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
Comment: And there's no duplicate for that?


Proper name or term of comma thousandths grouping notation

Question: What is the proper name or terminology of notation for using a comma to separate and group thousandths of a number?
As in, formatting large numbers for readability:
<code>comma delimited    real number
          1,000           1000
         10,000          10000
        100,000         100000
      1,000,000        1000000
</code>
How would you refer to this grouping of every third digit?
Comment: https://en.wikipedia.org/wiki/Decimal_mark#Digit_grouping
Answer: Thousand separation or digit grouping.
Answer: Perl users use the term "commify", probably a reference to "sub commify" in the Perl FAQ "How can I output my numbers with commas added?".


Usiung border on QWebView

Question: I'm trying to change the QWebView border just as I do with QLineEdit, setting the QWebView stylesheet for this:
QWebView
{
    border: 20px;
    border-radius: 5px;
}

The border is just ignored. I've tried changing the background of it and it works alright.
Am I doing something wrong? Or is there a way of doing that?
There it is. Code and print that refers to QWebView.
materialViewer = new QWebView(Study);
materialViewer->setObjectName(QString::fromUtf8("materialViewer"));
materialViewer->setGeometry(QRect(190, 10, 591, 531));
materialViewer->setContextMenuPolicy(Qt::NoContextMenu);
materialViewer->setUrl(QUrl("about:blank"));
materialViewer->setRenderHints( QPainter::Antialiasing |
                                QPainter::HighQualityAntialiasing |
                                QPainter::NonCosmeticDefaultPen |
                                QPainter::SmoothPixmapTransform |
                                QPainter::TextAntialiasing );

Link: http://imageshack.us/f/684/semttulomym.png/
Thanks in advance.
Comment: Could you perhaps provide a screen shot of exactly what you are seeing, maybe also provide a complete code listing for the screen shot. I suggest you do so by first reducing the code the as little as possible to see this problem
Comment: Done. I just edited the post.
Comment: Year later in Qt 4.8.5 this bug is still there.
Answer: There it is. Code and print that refers to QWebView.
  materialViewer = new QWebView(Study);
    materialViewer->setObjectName(QString::fromUtf8("materialViewer"));
    materialViewer->setGeometry(QRect(190, 10, 591, 531));
    materialViewer->setContextMenuPolicy(Qt::NoContextMenu);
    materialViewer->setUrl(QUrl("about:blank"));
    materialViewer->setRenderHints(QPainter::Antialiasing|QPainter::HighQualityAntialiasing|QPainter::NonCosmeticDefaultPen|QPainter::SmoothPixmapTransform|QPainter::TextAntialiasing);

Link: http://imageshack.us/f/684/semttulomym.png/
Comment: is this an image of the problem you are trying to solve, or of the solution?
Comment: I should edit the post with that. I was going to do that, but i forgot, sorry.

Usiung border on QWebView


How to enable click-sorting for views table display based on Search API index?

Question: I'm trying to create a view with table display based on Search API (database search) index, with column-sorting (column set as Sortable in the display settings). However, this option isn't available for my view fields, no matter if they are based on string or fulltext Search API fields. Is there anything I can do to enable this?
I'm using latest Drupal 8.7.x nad Search API 1.12
Edit:
It seems that availability of click-sorting is determined in \Drupal\search_api\Plugin\views\field\SearchApiFieldTrait::clickSortable method. The check inside that fails, because field definition array doesn't contain a search_api field key. So is there anything I can do to add it there?
BTW. th support for click-sorting was added in https://www.drupal.org/project/search_api/issues/2816979. There are some SOLR-related issues mentioned, but noting related to my use-case.
Comment: Do you have indexes created on those fields?
Comment: Yes, otherwise these fields wouldn't be available to the view, AFAIK.
Answer: As it turned out, it was my stupid mistake - search index field can be added to views (as a views field) in 2 ways, with one of them having (Indexed field) appended to the field label.
When I added field with (Indexed field) appended, I can set that field a Sortable.


How to refresh the website with Nancy if model data changed?

Question: If my model data is changing how to refresh the site automatically to display the changed data?
Is this possible at the server or do I have to write some client code for this?
Thanks for helping.
Michael
Answer: You have to write client side code to do this, the server has no relationship with the client once its sent the response - the connection is closed, the server moves on to other requests.
You need to use Javascript to poll the server and update based on server side changes - you can use a data binding framework such as Knock Out, or a larger framework such as Angular to make this easier.
SignalR may help you here, in that its a system which plugs into both the client and server side, keeps open a connection so you can send data to the client side instantly from the server.


SqlBulkCopy Timeout when used within a WCF Sercive that sets TransactionScopeRequired

Question: Situation:
WCF Service with TransactionScopeRequired OperationBehaviour.
WCF Service runs a process that used SqlBulkCopy to insert many rows to a db.
When used without the TransactionScopeRequired behaviour, the SqlBulkCopy inserts records with no issue, however when this behaviour is set to true, not even a small amount of records can be inserted.
Further info - The WCF Service uses a MSMQ Endpoint.
Answer: ok.. It was late when I posted the above..:)
Following further analysis (I am ashamed to be writing this..!) the issue was due to the implementation of my service making use of the Task Processing Library - i.e. I had multiple processes making DB calls wrapped within a TransactionScope - for example -
-First process performs actions against DB.  This action appends a transaction to the transactionscopes transaction and caused a db lock.
-Second process is then spawned and attempts to write to the same table - it is unable to as the transaction is not part of the original transaction scope.
Solution - Some redesign will be required to provide smarter transaction management!


Para exibir o dia da semana de qualquer data nos últimos 1.000 anos

Question: Usei este comando
select to_char(to_date('18-apr-1972','dd-mon-yyyy'),'day') day from DUAL;

mas deu erro na execução:
ORA-01841: ano (completo) deve estar entre -4713 e +9999 e não pode ser zero
01841. 00000 -  "(full) year must be between -4713 and +9999, and not be 0"
*Cause:    Illegal year entered
*Action:   Input year in the specified range

Alguém poderia me mostrar outra forma? Uso o Oracle.
Comment: @WilliamAparecidoBrandino errado. Isso é o POSIX time, em boa parte dos DBs se usa o Proleptic Gregorian Day, que começa em 4714 BC (indicado por -4713, pq nao tem ano zero) - e mesmo assim, em posix você pode usar numeros negativos para datas anteriores a 1970. Além disso, DBs que usam Posix não costumarm adotar microssegundos na armazenagem, por padrão. O campo é variante de INT normalmente.
Comment: @WilliamAparecidoBrandino se resolver apagar, basta depois sinalizar o meu como obsoleto (na bandeirinha ao lado dele), que a moderação limpa depois. Se quiser mais detalhes: https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar - normalmente é armazenado como Float nos DBs, sendo que a fração é o tempo, e o inteiro os dias. Exemplo: Sétimo ano, ao meio dia, fica `7.5`. Em Posix já são inteiros, sendo o número de segundos corridos desde a data que vc mencionou (ou anterior a ela se for número negativo) e toma por base sempre 86400 segundos todos os dias (sem _leap_).
Comment: Só lembrando que, em qualquer sistema, a base de contagem começa em 01-01-1970. Pelo menos os microssegundos começaram a partir dessa data.
Comment: @Bacco Boa! Uma que não sabia. Por essa informação nem apagarei meu comentário para constar.
Answer: Assim funciona:
select to_char(to_date('18-04-1972','dd-MM-yyyy'),'day') day from DUAL;

Comment: Muito obrigada!!!


How do I find subsequent work done on a paper?

Question: This question consists of a general question and a specific question. My general question is simple. Suppose I read a paper I like and I want to find out more about the topic. How can I do this ? The natural place to start is to go through the references at the end of the paper. However, there is a problem with this. References are only provided in one direction in time, namely the past. If the paper I'm reding was written in 1960, there's a good chance that extensive work has been done on the topic. How do I find references to how the topic has progressed after the paper has been published ?
Now, for my specific question, which is a special case of my general question.
Courtesy of the wonderful Canadian Mathematical Society which allows free access to their back issues, I discovered a paper written in 1959 in the Canadian Mathematical Bulletin. The paper answers the question about how the set of non negative integers can be partitioned into two sets such that sums of pairs of distinct integers in both classes will be the same.
Here's a link to the paper.
http://cms.math.ca/openaccess/cmb/v2/cmb1959v02.0085-0089.pdf
This paper is special to me, because it's the first research paper I read where I understood everything ! So, I was wondering if you guys could recommend some sources to me which either carry the problem forward, or which are written at the same level as this paper.
Comment: look for a paper in google scholar, you can click "cited by" to get a list of papers that cite the given paper
Comment: I read somewhere (many years ago) that there was an effort to attack this kind of problem, creating lists of papers that cite a particular paper as a reference. I don't know what came of it.
Comment: @Blue Nice blog. I'm thinking of subscribing. What do you personally do when you face this problem ?
Comment: @user230452: Thanks for the blog-compliment ("blog-liment"?). I haven't written enough hard-core academic papers to have developed a robust forward-citation search strategy, so I can't offer specific tips. (BTW: I don't *think* Google Scholar was the initiative I mentioned before, but no matter. GS is now the name I'll attached to that memory. :)
Comment: @Blue Is it possible to subscribe to your blog for email notifications via Wordpress ? Earlier in the day, I was browsing a question on this site titled big list for math blogs and subscribed to them. I encourage you to post your blogs as answers to that question.
Comment: If you have access to MathSciNet (which is the online version of Math Reviews), then you can look up the review of the paper, and it will have links to reviews of other papers that refer back to your paper. If you have access to a university library, they probably have access to MathSciNet.
Comment: @user230452: Ah, thanks for the info. I haven't (yet) added a dedicated "subscribe" action to my blog, but you can always subscribe to it (or any other WP blog) via RSS using by attaching a "feed" parameter to the base URL: [http://trigonography.com/?feed=rss2](http://trigonography.com/?feed=rss2). I post links to [https://twitter.com/trigonography](https://twitter.com/trigonography), and (less-reliably) to [https://facebook.com/trigonography/](https://facebook.com/trigonography/). I'll look into supporting email subscriptions.
Comment: @Blue Here's the link you should post about your blog to. http://math.stackexchange.com/questions/81/list-of-interesting-math-blogs . I don't know what RSS and WP is. Please elaborate on how I can subscribe to it. Throughly Feedly ? I understand running a blog is a lot of work, you don't have to put email notifications of it's too much to do :)
Comment: @Blue The RSS button is opening in Podcasts app. Do you have a podcast ? For what it's worth, I added trigonometry and bloog to Wordpress, but it doesn't open the website when I click the link. Guess something's wrong. I don't log into Wordpress often and only keep track via email ... But, I'll try bookmarking the site.
Comment: @user230452: No podcast. WP = WordPress. RSS = "Really Simple Syndication", which allows blogs and posts to be aggregated by "feed readers"; [Here's short NYTimes article on RSS and some readers.](http://techland.time.com/2013/07/01/r-i-p-google-reader-hello-four-best-rss-reader-replacements/). (It doesn't mention [NetNewsWire](http://netnewswireapp.com) (Mac/iOS), which is my reader of choice.) Finally, I've decided that I won't be doing email subscriptions for now. I don't want the responsibility of managing people's addresses; too many privacy/security concerns. I appreciate your interest!
Answer: Concerning the specific question of the 1959 paper, here's a reviewer's note on MathSciNet, written by Ernst Straus:
"Reviewer's note: While the method of proof, by a clever use of generating functions, uses the fact that one is dealing with integers, the result is clearly valid for arbitrary infinite cyclic semi-groups and, by an obvious extension, for direct products of such semi-groups. This includes the case of the natural numbers under multiplication which is treated separately in the paper."
The paper is referred to in reviews of two other papers:
MR0399468 (53 #3312)
Straus, E. G.
Real analytic functions as ratios of absolutely monotonic functions. Spline functions and approximation theory (Proc. Sympos., Univ. Alberta, Edmonton, Alta., 1972), pp. 359–370. Internat. Ser. Numer. Math., Vol. 21, Birkhäuser, Basel, 1973.
MR0492264 (58 #11408)
Goldstein, R.
On meromorphic solutions of certain functional equations.
Aequationes Math. 18 (1978), no. 1-2, 112–157.
Also, this paper cites Lambek-Moser in its references:
MR2014728 (2004m:68172)
Allouche, Jean-Paul; Shallit, Jeffrey
The ring of k-regular sequences. II.  Words.
Theoret. Comput. Sci. 307 (2003), no. 1, 3–29.
Comment: Thanks, Gerry. The generalization is too sophisticated for me. Please tell me what I need to know to understand it.
Comment: Which generalization?
Comment: Are you still here?
Comment: Yes, sorry. I am not able to access this site everyday due to time constraints. I meant the extension referred to by the reviewer.
Comment: Ah. I don't know. I guess you'd have to know what an infinite cyclic semigroup is, and what a direct product of semigroups is. Since I'm not familiar with the details of the 1959 paper, I can't say much more than that.
Answer: I don't know much about number theory, so i will only give a possible answer to the first, more general question (which probably deserves a thread on its own).
One possibility I know of is to use paperscape. Paperscape is a "landscape representation" of arXiv (basically a huge graph), clustering together related papers. There is also the very nice function allowing you to select a paper and "export it" to my.paperscape, where you can see all other papers cited and citing it.
Of course, the disadvantage is that you only get to see paper that are on arXiv.
Comment: Can you apply it for my special case ?
Comment: @user230452 The paper you want is not on arXiv, unfortunately.


Calling GET request with parameters from first HEAD response

Question: In my Angular app I have to call two HTTP request. First request is HEAD which return important parameter in header response (total number of records). Second request is GET and returns all records when HTTP header contains number for total records from header response.
Now I have two methods getHeader() and getData(records: number).
this.appService.getHeader().subscribe(
  (response) => {
    const records = response.headers.get('X-Total');

    this.appService.getData(records).subscribe(
      (data) => {
        this.data = dataFromServer;
      }
    );

  }
);

That works pretty well, but I would like to know if exist more elegant solution?
Comment: Which version of rxjs are you using?
Comment: I am using Angular 6 and RxJS 6
Answer: It would obviously be simpler if you modify the backend, so that only one request is required. That said, if it's not an option,you can use switchMap, like so:
import { switchMap } from 'rxjs/operators';

//...

this.appService.getHeader().pipe(
    switchMap(resp => this.appService.getData(resp.headers.get('X-Total')))
).subscribe(data => {
    this.data = data;
});


How can I multitrack record my band practices?

Question: I would like to start recording my band practices. Current configuration is bass, guitar, and drums. I would like to record individual tracks to my computer so that we can add other parts, work on vocal lines, splice jams together in to full songs, etc. I figure that will require a mic for guitar, 3 for the drums, and mic or DI for the bass.
What I'm missing is the piece of hardware that sits between the mics and my computer. What do I need there? How do I evaluate different options? What affects sound quality? Do I need a built in mic pre-amp to mic up an amp? What am I not asking because I'm a recording n00b?
Also, I'd like to do this on a budget. We're not trying to cut a demo, but what are the trade offs associated with price? We're all good musicians with good ears, what should we avoid skimping on so that we don't just end up getting frustrated?
I cross posted to Sound Design, as I wasn't sure where this really belonged.
Comment: Yossarian - the cross post now over on Sound has been better received and has good answers. I'm tempted to close it here and leave the better one there.
Comment: since you haven't mentioned any, I guess you're also missing the piece of software.
Comment: @slim, I have reaper and audacity. I also see that a lot of these interfaces come with a DAW, so I wasn't really worried about that aspect.
Comment: Not every DAW allows simultaneous recording from multiple inputs. I don't know which ones do -- it would be nice to know.
Comment: @slim, really? Any that I've ever used do. Both Audacity and Reaper certainly support it. Maybe that's a restriction that companies put on their entry level DAWs?
Comment: Good to know that Audacity does it. I have not found the facility in GarageBand. I'm not sure that it should count as a "restriction", as it's an ability you put in, rather than take out, if you know what I mean.
Comment: Although if you view GarageBand as Logic-Lite, and we assume Logic does it, I suppose it has been removed.
Answer: I think this would belong more on the audio site. However, what you're looking for is an audio interface. You can get them ranging from 1 to maybe 10 inputs, possibly more. As the number of inputs go up, so does the price, in a big way. Also, with mic's, you may get some bleed of other instruments into the mics unless you've got a really nice setup with a way to separate the musicians. I would imagine you would get more useful and specific advice to your situation on the audio.se though. Good luck!
Comment: This is a practice question so I think it does belong here.
Comment: @JPM, seems to me the question is about the missing hardware for recording, this isn't about *how* to practice an instrument.
Answer: I suggest you get a stand-alone multi-track recorder like the Zoom R16.   In stand-alone mode it is a simple 16-track playback, 8-track simultaneous recording device. It can also be used as an 8-input audio interface connected by USB to your computer, and is generally bundled with a lite version of Cubase.
If you record 'live' using microphones - all instruments playing at once - you will get leakage between tracks.  The sort of surgical manipulation and editing you read about in the home studio magazines may not be practical.  That takes perfectly isolated tracks, probably recorded individually against a click.  Not a terribly musical way of working, and an invitation for everyone to over-play.  It can work well for very experienced musicians who know exactly what their part should be and when NOT to play.   The rest of us end up spending hours doing 'remedial mixing' and timing correction.
Answer: It depends on whether your setup is part of the band PA or not.  For pure recording, a recording interface (or standalone recorder) with enough microphone inputs is needed.  In my experience, if you buy second-hand, the typical old Firewire interface works more reliably than the typical old USB interface.  In any case, check driver support.
If your setup is part of the band PA, you want to have a mixer with a suitable number of recording outputs (or a built-in computer interface: I am using a Mackie 1620 with Firewire card).  Insert connectors can be used for recording as well but are lower quality than balanced outputs.  What do you record with?  See the first paragraph, just that you don't need microphone inputs on your recording equipment then.
There also is the option of recording only the band mix from the mixer in which case you'll get along with 2-track recording (for which handheld recorders or even tapedecks are reasonably useful) but lose the ability to fix the results afterwards.  Still good for control recordings, but not the best option for listeners other than yourselves.
The software for doing mixes is called a "Digital Audio Workstation".  Quite a few soundcards with multiple inputs come with some trial version of one.  A free one is Ardour (in my opinion best under GNU/Linux but also supported for a few other operating systems).


How do we configure SElinux to not break Drupal?

Question: I've installed Drupal on Red Hat 7 in Amazon Web Services, using a database on a separate RDS instance.
My original problem was that I couldn't make the Drupal installer recognize the /sites/default/ or /sites/default/files directories as writable, even after I confirmed they were writable by the ''apache'' user or temporarily set the permissions to writable by all. (This year-old issue may be similar.) When I filled in settings.php myself, then Drupal gave this connection error:

PDOException: SQLSTATE[HY000] [2003] Can't connect to MySQL server on
  'my-database-endpoint.rds.amazonaws.com' (13) in
  lock_may_be_available() (line 167 of /var/www/html/includes/lock.inc).

Disabling SElinux allows the installer to finish and allows Drupal to work. Re-enabling SElinux ('''setenforce 1''') stopped the installer; re-enabling SElinux after installation breaks Drupal, resulting in the same connection error given above. Drupal.org mentions the problem, but doesn't give a specific solution for this case.
I figure many other people must have run into the same problem when installing Drupal.
Obviously I have to re-enable SElinux, so does anyone already know how to modify SElinux configurations to enable Drupal to work properly (and not degrade security)?
Answer: Looks like you are connecting to a remote host. You may need to allow httpd to make remote connections. Run these commands as root to set the SELinux variables.
<code>setsebool -P httpd_can_network_connect 1
setsebool -P httpd_can_network_connect_db 1
</code>
http://alexbilbie.com/2013/02/selinux-php-mysql/


Office 365 Outlook Autodiscover using a reverse proxy - bad approach?

Question: Background. Outlook Autodiscover has a certain order of trying to figure out configuration, and it's somewhat unchangeable, at least for Office 365 users with BYOD devices:

Domain apex https://example.com:443/Autodiscover/Autodiscover.xml. As this is typically a public web site hosted elsewhere, this seems like an unnecessary step for most.
https://autodiscover.example.com:443/Autodiscover/Autodiscover.xml is a way more reasonable alternative. Unfortunately, as of Sep 2019, Microsoft has screwed this up: for Office 365 users this is instructed to be a CNAME autodiscover.outlook.com., but...
$ curl -vvv https://autodiscover.outlook.com:443/Autodiscover/Autodiscover.xml
*   Trying 188.8.131.52...
* TCP_NODELAY set
* connect to 126.96.36.199 port 443 failed: Connection refused
*   Trying 22.214.171.124...
* TCP_NODELAY set
* connect to 184.108.40.206 port 443 failed: Connection refused
*   Trying 188.8.131.52...
* TCP_NODELAY set
* connect to 126.96.36.199 port 443 failed: Connection refused
*   Trying 126.96.36.199...
* TCP_NODELAY set
* connect to 22.214.171.124 port 443 failed: Connection refused
*   Trying 2603:1026:207:15::8...
* TCP_NODELAY set
* connect to 2603:1026:207:15::8 port 443 failed: Connection refused
*   Trying 2603:1026:207:109::8...
. . .

Fallback to HTTP redirect method, the only method working.
This time http://autodiscover.example.com:80/Autodiscover/Autodiscover.xml, configured as a CNAME autodiscover.outlook.com., answers with a redirect to a working site.
Location: https://autodiscover-s.outlook.com/Autodiscover/Autodiscover.xml

This one is serving correctly in most cases, although lines seems to be long for new Application Passwords to make it this far. This, how ever, takes a lot of request and additional time. (Also, this makes it harder to debug why certain versions of Outlook can't currently connect to Office 365 at all, but must be ugraded before even trying...)

Possible solution to make this faster is to add a reverse proxy at the domain apex, pointing to the working Office 365 Autodiscover site. E.g. with Apache this is as easy as enabling the module with a2enmod proxy_http and adding a simple configuration to the VirtualHost:
# Office 365 Autodiscover Hack 20190918
SSLProxyEngine on
ProxyPass "/Autodiscover/"  "https://autodiscover-s.outlook.com/Autodiscover/"
ProxyPassReverse "/Autodiscover/"  "https://autodiscover-s.outlook.com/Autodiscover/"

According to the Microsoft Remote Connectivity Analyzer test for Outlook Autodiscover this seems to work perfectly fine, and it also seems to make Outlook Autodiscovery seemingly faster on actual Outlook installations.
As this is a hack rather than an actual solution documented anywhere, my question: is there any possible consequences from this approach you could think of?
Is the autodiscover-s.outlook.com for example a static hostname for the service, or does it ever give other redirects? Wouldn't Outlook just continue with steps 2 & 3 in any case this proxy gives unexpected results?
Comment: Related question: [Can HSTS includeSubDomains break Office 365 autodiscoveries?](https://serverfault.com/q/958307/274176)
Comment: Hey Esa, have you ever experienced any (negative) consequences from the redirect in the meanwhile? It has been almost 2 years. Perhaps you can answer your own question and/or add a comment. :) I just took a similar turn, [with a redirect at DNS provider](https://serverfault.com/a/1074992/), but if there are any downsides, I would like to know.
Answer: Office 365 and Exchange Online environment has a different character from the Exchange on-Premises environment. In Exchange on-Premises environment, the organization uses a dedicated Public facing Exchange server, which serves as a "representative" for the organization public domain name.
The "cloud environment" (Office 365), cannot provide this type of "dedicated Exchange server" that will represent the particular domain name of the Office 365 tenant. Please refer to this article:
https://o365info.com/autodiscover-flow-in-an-office-365-environment-part-1-of-3-part-29-of-36/
Comment: This partly answers the question on why the phase 2 is supposed to fail, but the other parts are just repeating what has already been established in the question. It doesn't answer if there's any reason not to take the shortcut with a reverse proxy. As it has a matching certificate, it's working.
Answer: Yes, adding a reverse proxy works without problems and prevents from trying unencrypted connections to http://autodiscover.example.com:80/Autodiscover/Autodiscover.xml. However, as A71 noticed, Outlook also follows HTTP redirects from the HTTPS URIs on phases #1 & #2, omitting the plain HTTP phase #3.
A redirect might even be better from security perspective, as Office 365's Autodiscovery requires authentication. With a reverse proxy this authentication would be unnecessarily passed through the web server.
Also, as the URI from the domain apex web server is always requested first, a compromised content management system (CMS) could hijack these and steal user passwords. Therefore, having this configured on the web server level prevents any web application from getting these requests.
As a result, the Office 365 Autodiscover gets both faster and more secure.
Apache:
# Office 365 Autodiscover Redirect
Redirect permanent "/Autodiscover/" "https://autodiscover-s.outlook.com/Autodiscover/"

Nginx:
# Office 365 Autodiscover Redirect
location /Autodiscover/ {
    return 301 https://autodiscover-s.outlook.com$request_uri;
}

Comment: Thanks, @A71, for this better alternative. Here's my reasoning on why this is better & why it could even be considered as a best practice.


Por que não usar sempre o Optimize Code?

Question: No Visual Studio existe a opção Optimize Code que tem a função de criar otimizações executadas pelo compilador para tornar seu arquivo de saída menor, mais rápido e mais eficiente.
Por que não posso usar sempre essa opção em meus projetos?
Answer: A opção Optimize Code é habilitada por padrão quando você realiza o build em release mode. As otimizações realizadas pelo compilador podem acabar dificultando o debug enquanto você está desenvolvendo, isto porque o código compilado é reorganizado para uma melhor eficiência, e o resultado disto pode impactar diretamente no debugger, que não poderá identificar que determinado código fonte pertence a um conjunto específico de instruções compiladas.
Trecho do MSDN

When the compiler optimizes code, it repositions and reorganizes
  instructions. This results in more efficient compiled code. Because of
  this rearrangement, the debugger cannot always identify the source
  code that corresponds to a set of instructions.

Segundo o artigo da MSDN, um bug pode aparecer apenas na versão otimizada pelo compilador, cenário este onde você deve realizar o debug no código otimizado para encontrar a causa do problema.

a bug might appear only in an optimized version of a program. In that
  case, you must debug the optimized code.

Referências

https://stackoverflow.com/questions/472599/why-should-i-not-use-the-optimize-switch-to-compile-my-c-sharp-code
https://msdn.microsoft.com/en-us/library/606cbtzs.aspx
Answer: Porque nem sempre estas otimizações são desejáveis. Nem sempre produz o que se espera. Cada caso é um caso e você deve optar por ligar ou não depois de testar ambos. Além disso é possível que algum tipo de otimização possa tornar o código incompatível com códigos de terceiros (raro). Grande parte delas não geram ganhos tão expressivos. A maior parte das aplicações ninguém notará quando a otimização está ligada ou não.
Pode atrapalhar em especial a depuração, mas não só.
Lista desatualizada de otimizações.
Segundo a documentação as otimizações são desabilitadas por padrão. E nunca vi uma informação oficial dizendo o contrário.
Comment: São habilitadas por padrão para release pelo Visual Studio, não pelo compilador.
Answer: Porque o código é alterado de alguma forma automática, mesmo que em teoria não mude muita coisa.
Se tudo der certo, só atrapalha debug (já que o código pode não mais corresponder ao binário) e deve demorar mais para compilar, já que ele tem que otimizar (a diferença pode ser mínima).
Já vi também bugs de otimização no compilador atrapalharem o resultado final, mas nunca vi um problema no C# relacionado a isso.
Answer: Serve para compilar o código de forma mais eficiente.
Porém existem casos (pinvoke por exemplo) onde o código otimizado não funciona corretamente, então você pode desativar a otimização em alguns métodos. Basta decorar o método usando o atributo <code>[MethodImpl(MethodImplOptions.NoOptimization)]</code> no método.
Exemplo:
<code>[MethodImpl(MethodImplOptions.NoOptimization)]
private void CallMethodsWithOptimizationDisabled()
{
    //método compilado sem otimização
}
</code>


regex/python to find and replace specific number within string

Question: I need to replace numbers (corners) that occur within a longer string that all look similar to this:
[ 17 plane_17 \ 23 25 17 99 150 248 \ noname ]

My function takes an "old" number to be replaced with a "new" number, and e.g. if that old number is 17 and the new is 19, then the outcome should be:
[ 17 plane_17 \ 23 25 19 99 150 248 \ noname ]

Note that only the numbers within \ \ should be replaced (these could also be / / ).
To do this I tried to set up a regex substitution with the intention of avoiding numbers outside of \ \ or / /:
newplane = re.compile(r"[^[_] (" + str(oldcorner) + ")").sub(str(newcorner), oldplane)
I quickly realised that this doesn't work since regex searches from the start of the line and then fails if it doesn't match the pattern.
There must be some clever way of doing it still that I don't know about.. Any suggestions?
Comment: will they be between '\\', or single '\'? My first instinct would be to split it at '\' (or double), call plain old replace( old, new ) on every second element of the result and then join them back together at '\'. Not very pythonic though, interested to see if someone has a neat way
Comment: They'll all be either within single '\' or single '/'. That's not a bad idea! Would remove the regex too....
Comment: yeah would keep things simple, not sure how you would handle both '\' and '/' in the same line though
Answer: You can use a callback function inside the sub part of the regex:
import re

def callback(match):
    return match.group(0).replace('17', '19')

s = "[ 17 plane_17 \ 23 25 17 99 150 248 \ noname ]"

s = re.compile(r'\\.+?\\').sub(callback, s)

print s

Prints:
[ 17 plane_17 \ 23 25 19 99 150 248 \ noname ]

Comment: Where did the slashes get to?
Comment: Thanks for this, vpekar! Really clever with a callback function!
Comment: One issue with this: if there's a three digits (or more) number with the '17' as part of it, the callback will also replace it.
Comment: Callback means that first the callback runs and then sub? callback gets parameter s?
Comment: Does the question mark (non-greedy operator) make sense because there is no decision between greedy and non-greedy?
Comment: @Timo, the callback gets each match as an argument; sub first finds matches and then each match is passed to callback and gets replaced with the output of the callback. The question mark makes sure the change is between the first slash and the second. If you remove the question mark, the change will be between the first slash and the last (if there are more than two).
Answer: In addition to vpekar answer, you can also use backreferences of your pattern on the replacement string, so you can try to match all between / or \ and recreate the string using your new number and backreferences:
line = '[ 17 plane_17 \ 23 25 17 99 150 248 \ noname ]'
re.sub(r'([\\|/].*\s)(?:17)(\s.*[\\|/])', r'\g<1>19\2', line)

which returns:
'[ 17 plane_17 \ 23 25 19 99 150 248 \ noname ]'

Comment: Thanks asermax! I really like this one-liner solution too! There are clearly some gaps in my regex knowledge. Thanks!
Comment: Can you explain parts of it. sub has 3 parameters: old, new, string. You could leave the first `r`. Where is backreference no.1? no.2 is \2.
Comment: A non capturing group is not needed, simpler: `re.sub(r'([\\|/].*\s)(17)(\s.*[\\|/])', r'\g<1>19\3', line)`


Comments inside HTML/SGML/XML/DTD declarations

Question: In the W3C HTML 4.01 DTDs and earlier, inline comments are frequently used within declarations.
For example, the HTML 2.0 Strict DTD has:
<!ENTITY % HTML.Version
    "-//IETF//DTD HTML 2.0 Strict//EN"

        -- Typical usage:

            <!DOCTYPE HTML PUBLIC
        "-//IETF//DTD HTML Strict//EN">

        ...

    --
    >

where the HTML entity declaration contains a comment between two double hyphens --.
However, DTD validators seem to flat out reject these sorts of internal comments and throw an error.
Are the validators wrong, or are the W3C DTDs not well-formed?
Answer:
In looking into it further, it seems that this is due to differences between the SGML and XML specifications.
Essentially, SGML defines comments as beginning and ending with -- anywhere inside a declaration construct <! >, whereas XML requires comments to begin and end with the  delimiters, respectively, as independent constructs.
Because HTML up to version 4.01 was based on SGML, comments within declarations were allowed and were used by the official DTDs.
However, most DTD validators seem to only check for compliance with the simpler XML specification and, therefore, get confused by intra-declaration comments, barfing errors.
Comment: This should be valid, but only in SGML syntax (not XML). Which parser are you using? (just to remind: HTML is an SGML DTD)
Comment: It seems you're right. I was using the [Validome validator](http://www.validome.org/grammar/), which is only for validating XML DTDs. (I didn't know the DTD specifications for XML and SGML were different when I wrote the question). Thanks!
Answer: In looking into it further, it seems that this is due to differences between the SGML and XML specifications.
Essentially, SGML defines comments as beginning and ending with -- anywhere inside a declaration construct , whereas XML requires comments to begin and end with the  delimiters, respectively, as independent constructs.
Because HTML up to version 4.01 was based on SGML, comments within declarations were allowed and were used by the official DTDs.
However, most DTD validators seem to only check for compliance with the simpler XML specification and, therefore, get confused by intra-declaration comments, barfing errors.


Probability that First 'A' before Second 'S' in the word "ASSASSIN"

Question:
Consider all the permutations of the word "ASSASSIN". Find the probability that the First 'A' occurs before Second 'S'.

By considering the sequence of letters in reverse, I deduced that the question is equivalent to probability of Second 'A' occurs after Third 'S'.
(I found this little easier to attempt).
I split this into two further cases:
(I). First 'A' occurs after Third 'S'
(II). First 'A' occurs after before Third 'S' and Second 'A' occurs after Third
For (I). Depending upon where the 4th 'S' goes,
(i.e. SSSSAA/SSSASA/SSSAAS type) there are $7*8=56$ numbers for each case(considering permutation of letters I,N between their gaps). Hence $56*3=168$ numbers this case.
For (II). We have (ASSSA/SASSA/SSASA) initial possibilities. Now the 4th S has 3 ways to go in the first, 2 ways to go in the second(as one possibility is counted in the previous case), but only one ways in the third type(as in one way it is same as the previous case again, and in another one way it would become case (I) again).
The total number of words is $(3+2+1)*(7*8)=336$
Hence the total number of ways is $168+336=504$ ways.
And the required probability is $\frac{504}{(8!/(4!*2!))}=\frac{3}{5}$.
Although this is the correct answer, I am eager to know of any other way to solve this question,preferably with not so many case work and one whose method could be applied to other longer words conveniently as well.
Comment: for practicing such questions,  this tool  careerbless.com/calculators/word/index.php is found very useful
Comment: You can think about it like this, the first 'A' cannot occur after the 4th position in any of the favorable permutations. (If it's in the fourth position, the last four letters have to be S,S,S and A)
Answer: Note that you can ignore the I and the N, as they are irrelevant to the ordering of the A's and S's.
Here are three different ways to proceed.
Solution 1: Direct enumeration--there are only ${6\choose 2}=15$ ways to arrange AASSSS, so this is quite easy to do by hand. Then count how many cases are of interest. Divide this count by $15$.
Solution 2: Find the complementary probability: That is, find the probability that S occurs in both the first and second position:
$P(SS...)=\frac{4}{6}\cdot\frac{3}{5}=\frac{12}{30}=\frac{2}{5}$. So the desired probability is $1-\frac25=\frac35$.
Solution 3: Use inclusion-exclusion.  Let $E_1$ be the event that the first letter among the   A's and S's is A, and let $E_2$ be the event that the second letter among the A's and S's is A.  We want $P(E_1 \cup E_2)=P(E_1)+P(E_2)-P(E_1\cap E_2)=\frac26+\frac26 -\frac{1}{15}=\frac35$.


Angular 2 RC4 to latest - "Uncaught TypeError: Cannot read property 'prototype' of undefined" when extending

Question: I had an older Angular 2 RC4 project I've updated to the latest version (now 2.0.0). I don't get any compilation errors when running ng build using the latest version (1.0.0-beta.14) of angular CLI, but when running ng serve I get the error in the title.
The base service in question looks like:
import { Injectable } from '@angular/core';
import { Response } from "@angular/http";
import { Observable } from "rxjs/Observable";

export class PkServiceBaseService {
  // Implementation
}

While the class extending the base service looks like:
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from "rxjs/Observable";

import { PkServiceBaseService } from "./";
import { JwtAuthorizationService } from "./";
import { Task } from "../shared";

@Injectable()
export class TaskService extends PkServiceBaseService {
  // Implementation
}

Both files are in the same directory, and exported through the index.ts file.
The strange thing is I was getting this same error in some model classes when using inheritance, but now that's disappeared.
Also, the stack trace for the error contains a reference to another service UserService that also extends PkServiceBaseService, but isn't used at all within TaskService.
Please let me know if I can provide any more information. I've omitted the implementation details as the issue seems to only be related to the inheritance, but I can certainly provide more information.
Full stack trace for reference:
__extends              @   task.service.ts:40
(anonymous function)   @   user.service.ts:11
(anonymous function)   @   user.service.ts:105
__webpack_require__    @   bootstrap 32723c5…:52
(anonymous function)   @   main.bundle.js:4803
__webpack_require__    @   bootstrap 32723c5…:52
(anonymous function)   @   prep-kids.component.ts:18
__webpack_require__    @   bootstrap 32723c5…:52
(anonymous function)   @   icon-registry.js:375
__webpack_require__    @   bootstrap 32723c5…:52
(anonymous function)   @   src async:7
__webpack_require__    @   bootstrap 32723c5…:52
(anonymous function)   @   main.bundle.js:81928
__webpack_require__    @   bootstrap 32723c5…:52
webpackJsonpCallback   @   bootstrap 32723c5…:23
(anonymous function)   @   main.bundle.js:1

Edit:
I should add that I've followed the RC4 to RC5 migration steps for Angular 2, as well as the Upgrading from Beta.10 to Beta.14 steps for Angular CLI
Answer: It happened the same to me. In the end there were some circular dependencies in my code that system didn't complain about and webpack threw misleading messages.
In my case I have a shared module and a core module. Instead of importing shared I broke it to shared/menu, shared/icon and so on.
This broke all weird dependencies and started working quite fine
Comment: Thanks, this was my issue too, circular dependency of a component extending something defined in a service it was importing.
Answer: After much digging and a fudging, I was finally able to get my app working again.
This issue in the Angular CLI queue got me on the right track. It seems sometimes using wildcards in your index.ts file can cause issues finding that class after compilation.
For instance, before I was doing something like:
export * from "./user.service";
export * from "./pk-base-service.service";

But changing things in my index.ts to:
export {UserService} from "./user.service";
export {PkBaseService} from "./pk-base-service.service";

got rid of my problems.
There were also a few instances where I would get this same error from my model classes. Previously, when I had to models in the same folder I was able to do:
import { User } from "./";

Changing the import to:
import { User } from "./user.model";

Got rid of the error.
Answer: For me it was the order in the index.ts that was important.
Put my base class first and then the error went away.
Answer: I just removed the -
export * from 'path/base-class-name';

from the index.ts and imported it into my base module.
import { BaseClass } from 'path/base-class-name';

This solved my issue.


Is there any symmetric complex matrix not satisfying this condition

Question: Friedberg linear algebra p.471:
"If $A$ is symmetric with entries in $\mathbb{F}$, then $||A||_{op}$ is the largest absolute value of $A$"
Here, the operator norm is defined as $||A||_{op} \triangleq \sup_{x\neq 0} \frac{||Ax||}{||x||}$.
==========
I can prove this sentence when the field is $\mathbb{R}$, but i'm not sure when $\mathbb{F}=\mathbb{C}$.
Let $A$ be a $n\times n$ symmetric complex matrix and $\lambda$ be an eigenvalue of $A$.
Then, $\overline{\lambda}$ is an eigenvalue of $A^*$, since $A$ is symmetric.
My question is, is $\lambda$ an eigenvalue of $A^* A$?
If not, please give me a counterexample.
Comment: Are you sure you are quoting Friedberg word for word? The phrase "the largest absolute value of $A$" sounds very weird. And what is $\mathbb{F}$? Is it either $\mathbb{R}$ or $\mathbb{C}$?
Answer: I think that for $\mathbb{F} = \mathbb{C}$, the author meant hermitian when (s)he wrote symmetric.
Over $\mathbb{C}$, symmetry in the sense of $A^T = A$ is not very interesting, and it's easy to find counterexamples. Let
$$A = \begin{pmatrix}i & 1\\1 & 0\end{pmatrix}$$
$A$ is obviously symmetric in the $A^T = A$ sense, the operator norm is $\sqrt{\frac52} = \lVert A\cdot\frac{1}{\sqrt{2}}(-i,1)\rVert$, the eigenvalues are $\dfrac{i \pm \sqrt{3}}{2}$, both of absolute value $1$.
$$A^\ast A = \begin{pmatrix}2 & -i\\i & 1\end{pmatrix}$$
has eigenvalues $\dfrac{3 \pm \sqrt{5}}{2}$.
If on the other hand hermitian symmetry was meant, then all eigenvalues are real, eigenvectors to different eigenvalues are orthogonal, and hence the operator norm is the largest absolute value of all eigenvalues.


How do I use PKCS1_PSS_PADDING with Ruby's RSA implementation?

Question: According to the docs for OpenSSL, RSA_PKCS1_PSS_PADDING is supposed to be available for use with OpenSSL's RSA_private_encrypt function, which is what Ruby uses internally for OpenSSL::PKey::RSA#private_encrypt.
Relevant quote from the linked docs for OpenSSL's RSA_private_encrypt:

The padding argument must be one of the RSA_*_PADDING values. If in doubt, RSA_PKCS1_PADDING is the most common but RSA_PKCS1_PSS_PADDING is preferred for new protocols.

Is there anyway I can use PSS padding for the private key encryption? I'd prefer to use PSS over Ruby's default padding (OpenSSL docs say it's preferable), but it seems like PSS is not widely implemented, unless I'm misunderstanding things.
I have Ruby 2.5 and OpenSSL 1.0.2 installed.
require 'openssl'

padding = 6 # OpenSSL's raw constant for RSA_PKCS1_PSS_PADDING since Ruby doesn't define it
priv = OpenSSL::PKey::RSA.new 2048
pub = priv.public_key

data = 'foo-bar-baz'
enc = priv.private_encrypt data, padding
dec = pub.public_decrypt enc, padding

puts dec == data

Running this throws an error: unknown padding type, even though I thought OpenSSL supports the RSA_PKCS1_PSS_PADDING padding type.
Does Ruby 2.5 not support RSA_PKCS1_PSS_PADDING for some reason?
Answer: The documentation that you refer to mentions that

RSA_PKCS1_PSS_PADDING can only be used via the EVP interface.

The Ruby functions that you invoke use the RSA_private_encrypt() function under the hood, which is not the EVP interface. As a result, OpenSSL emits an error. You can see it happen in the OpenSSL source code here.
However, Ruby's OpenSSL::PKey::RSA class exposes two methods specifically for signing and verifying with the RSA-PSS scheme, called sign_pss() and verify_pss(). Their documentation comes with coding examples showing you how to use them.
RSA-PSS can only be used for signature generation (and verification), which is not the same as RSA encryption with a private key (and decryption with a public key).
Comment: The RSA-PSS scheme itself does not have message digest recovery so you will find no implementation of `{RSA|EVP_PKEY}_verify_recover()` that will give it. See also [RSA vs DSA Digital Signature Message Digest Recovery](https://security.stackexchange.com/questions/87235/rsa-vs-dsa-digital-signature-message-digest-recovery)
Comment: Thanks for the clear answer, and for the links to the `_pss` Ruby methods. Does that mean BoringSSL (a fork of OpenSSL by Google and the lib I mistakingly linked to thinking it was OpenSSL) does things a bit different? Because from [their docs](https://commondatastorage.googleapis.com/chromium-boringssl-docs/rsa.h.html#RSA_private_encrypt), RSA-PSS is able to be used for encryption with a private key/decryption with a public key, and not just for `sign`/`verify` (so BoringSSL supports RSA-PSS for `verify_restore`). Is this a missing feature in OpenSSL compared to BoringSSL?
Comment: No, RSA-PSS is a scheme to use for signing and verification purposes only -- by design.The name already says it: PSS stands for Probabilistic *Signature* Scheme. The documentation you refer to seems somewhat misleading, depending how you interpret it.
Comment: This answer might be interesting for you to read: [What is RSA OAEP & RSA PSS in simple terms](https://security.stackexchange.com/questions/183179/what-is-rsa-oaep-rsa-pss-in-simple-terms).
Comment: Thanks for the link. So in that case shouldn't RSA-PSS padding theoretically be available for `EVP_PKEY_verify_recover`, and as such also in `OpenSSL::PKey::RSA#public_decrypt`, or even a new `OpenSSL::PKey::RSA#public_decrypt_pss` method, if it was updated to utilize the `EVP` interface? (Since most implementations of `private_encrypt`/`public_decrypt` use the `RSA_sign`/`RSA_verify_recover` functions under the hood.) If that's incorrect, then why _can't_ RSA-PSS support the `verify_recover` op?
Comment: Thanks so much for the clarification and for the link. I think BoringSSL's docs really confused me, since they make it sound like RSA-PSS does somehow support recovery, but I couldn't find a clear answer anywhere online.