How to prove "square arrangement product" converges?

Question: It is well known that when we multiply two infinite series, say $\sum_{i=1}^{\infty} a_i$ and  $\sum_{i=1}^{\infty} b_i$, then their "product"  $(\sum_{i=1}^{\infty} a_i )\cdot(\sum_{i=1}^{\infty} b_i)$ may depend on how $a_i b_j$s are arranged even when both  $\sum_{i=1}^{\infty} a_i$ and  $\sum_{i=1}^{\infty} b_i$ converge. One famous example is the Cauchy product in which they are arranged diagonally. Cauchy product converges if both $\sum_{i=1}^{\infty} a_i$ and $\sum_{i=1}^{\infty} b_i$ converge absolutely but may diverge if they converge only conditionally.
Another famous arrangement is the "square arrangement" (I'm sorry I don't know how to describe it terminologically. You can take at look at the picture below.). In my textbook it claims that in the "square arrangement" the requirement for the convergence of the product is a bit weaker: both $\sum_{i=1}^{\infty} a_i$ and $\sum_{i=1}^{\infty} a_i$ converge, whether conditionally or absolutely. Unluckily the textbook doesn't give a proof on this, and I have tried googling it but got nothing (it might be because I don't know the accurate terminology). Can you help me about it? Any hint or just telling me the right terminology will be appreciated. Thanks in advance.

A diagram of "square arrangement" here:

The "square arrangement product" is thus
$$\sum_{i=1}^{\infty}d_i$$
Answer: Look at the partial sums:
$$
\sum_{i=1}^Nd_i=\Bigl(\sum_{i=1}^Na_i\Bigr)\Bigl(\sum_{i=1}^Nb_i\Bigr).
$$
Comment: Exactly! That's all it takes for a perfect proof. Thank you so much!
Comment: And may I ask how to describe such a product terminologically (or at least properly) in English? "square arrangement product" sounds quite awkward to me.
Comment: English is not my native language. I find _square product_ quite descriptive.
Comment: Ok, thank you anyway.


Using Entity Framework to connect to SQL Server CE (.SDF file)

Question: I can successfully connect to an .mdf file with Entity Framework. My connection string is as below:
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\FacilitySecurity.mdf;Integrated Security=False;Connect Timeout=30"

On my computer I can connect and use .mdf file. But when I run my application on another computer, there's an error that about SQL Server service. I think I must use .sdf file instead of .mdf file.
But how can I connect to an .sdf file with Entity Framework? And which application or services must be installed in any other computer for run my application?
Comment: First thing to be clear about: should each user have their own database? Or should they connect to a shared database?
Comment: each user have a local database
Answer: SQL Server (probably you mean Express Edition) and SQL Server CE that use .sdf files are completely different products that have nothing in common except "SQL" letters in the name. SQL Server CE is not a server application, it is just a library for embedding.
To use SQL Server CE, for instance with Entity Framework as alternative data provider, you can add appropriate NuGet packages to the project and change connection string (and actually to add a dozens lines in application configuration file). But be careful: functionality of SQL Server CE engine is much more limited.
To use LocalDB on other computer you need to install SQL Server.
Answer: You can try it,follw this description and install the EntityFramework.SqlServerCompact package.
【Install Entity Framework 6 from NuGet】
To get the latest and greatest Entity Framework 6 bits, always install from NuGet. And thanks to the amazing package dependency resolution features of NuGet, just install the single required package, and the remaining packages will be installed as dependencies. In this case, the only thing that is missing from the EntityFramework.SqlServerCompact package (which depends on SQL Server Compact 4 and EF6) is a DbProvider registration in the app.config file, that enables you to run without the SQL Server Compact runtime installed in GAC and machine.config. To fix this ""misssing link", I have created the EntityFramework.SqlServerCompact package, which simply adds the missing config entries and in turn depends on all other required packages.
In other words, simply install the EntityFramework.SqlServerCompact.PrivateConfig package. Right click the References folder in your project, and select Manage NuGet Packages. Search for the package name and install it. And all required packages and references will be installed. (I am working on getting these config entries added to the base EntityFramwork.SqlServerCompact package, in order to make things more streamlined)


Access Devise Configured Messages for Rspec and Capybara Tests

Question: I'm trying to test that a non-logged in user is directed to the devise sign up page when they attempt to access secured content.  I'm using RSpec with Capybara for the tests.
To make sure they reach the login page, I'm making sure the page that they end up on has the content of the devise login page notify hash. (By default, this is: You need to sign in or sign up before continuing.)
Rather than write the test like:
page.should have_content "You need to sign in or sign up before continuing."

Is there a way to access the configured message (in case I change it later)? Something like:
page.should have_content Devise::Messages.Login_required

Answer: Devise messages are stored in config/locales/devise.*.yml, so you can access them like any other translations:
page.should have_content I18n.t("devise.failure.unauthenticated")


how to add parameter of type Class

Question: I have to use a method with this signature
BCR(String id, Class<? extends android.content.BroadcastReceiver>
receiverClass))

I created a class extends a BroadcastReceiver as follows
public class BCRGeoReference extends BroadcastReceiver {

public BCRGeoReference(Context ctx) {

}

@Override
public void onReceive(Context context, Intent intent) {

}
}

but I when i add BCRGeoReference to the method i receive an error saying:
required java.lang.class<? extends android.content.BroadcastReceiver>

please let me know how to add that parameter to the method BCR() posted above
Comment: Are you asking how to call that method with your `BCRGeoReference` class? `BCR("id", BCRGeoReference.class);`.
Comment: how are you calling this method?
Answer: Your signature is wrong. You expect a class object with the generic type of ? extends BroadCastReceiver, but that is not the case. You want to pass an instance of BroadCastReceiver.
Change your signature to this
<T extends BroadcastReceiver> void BCR(String id, T receiverClass)

If you meant to use it as a class object then you have to pass a class. Something like
public class TestJava {
    void BCR(String id, Class<? extends BroadcastReceiver> receiverClass){

    }

    public class AnyReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {

        }
    }

    public static void main(String args[]){
        TestJava test = new TestJava();
        test.BCR("s", AnyReceiver.class);
    }
}

how to add parameter of type Class


Will an iterator cause a memory leak?

Question: Will this cause a memory leak if I don't delete the *itr? I'm just wondering for a project and don't want to have points taken off.
void Directory::removeFile(string fName)
{
// Get files from directory
list<Folder> folders = this->getFolders();
list<File> files = this->getFiles();
for (list<Folder>::iterator itr = folders.begin(); itr != folders.end(); ++itr)
{
    if (fName == (*itr).getFolderName())
    {
        cout << fName << ": Is a directory." << endl;
        return;
    }
}
for (list<File>::iterator itr = files.begin(); itr != files.end(); ++itr)
{
    if (fName == (*itr).getFileName())
    {
        cout << "Found it" << endl;
        itr = files.erase(itr);
        this->setFiles(files);
        return;
    }
}
cout << "This file does not exist." << endl;
}

Edit: The reason why I am asking this is because I did valgrind and got this as a result. Is this a memory leak?
HEAP SUMMARY:
==27219==     in use at exit: 0 bytes in 0 blocks
==27219==   total heap usage: 25 allocs, 25 frees, 82,671 bytes allocated
==27219==
==27219== All heap blocks were freed -- no leaks are possible
==27219==
==27219== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==27219== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Comment: I don't see a `new` or even a pointer, so probably not. But it might if `File` is susceptible of leaking. Why do you suspect it would leak? Understanding that would help us answer your quesiton.
Comment: Iterators, as a concept, are not a memory leak risk. Though there's no telling what problems a sufficiently poor implementation can have.
Comment: @JakeYoung "All heap blocks were freed -- no leaks are possible" is quite clear, isn't it?
Comment: Memory leaks come from allocations that aren't properly reclaimed. What are you allocating in here? Can you step through in a debugger and find out more?
Comment: The only potential source of a memory leak here would be if the `Folder` and `File` types don't free their resources
Comment: I'll take a snippet when I get home. But I did a valgrind and it had like a heap amount of 56k or something like that. I don't really remember what exactly was said. I don't use valgrind too often.
Comment: Off topic: You *copy* your lists of files and folders, modify them and then copy them back (`setFiles`). You can spare all this if your getters return references and you assign to those as well...
Comment: I added a snippet of the result from valgrind. That's what made me ask this question.
Comment: I just wasn't sure why that 82k bytes allocated was so high. I thought that might have been something
Answer: No, you don't have to delete a list<Folder>::iterator itr since it is a variable with automatic storage duration that is not a pointer.
Please remember that you only may feed pointers that you obtained using new to delete and pointers obtained using new[] to delete[].
Answer:
Will this cause a memory leak if I don't delete the *itr?

No, it won't.
std::list::erase will make sure that the destructor of the object contained at the location, in your case a File object, will be called.

Will an iterator cause a memory leak?


Laplace transform restriction and differentiation

Question: every one.I have just started learning Laplace transform.However, there are two main conceptual problems I can't convince myself.

The first problem is about the restriction of this integral, I understand that for a real variable s, it needs to be positive so that the integral converges to a value, e.g. f(t)=1 then L(f(t)) = 1/s . s>0
But,if the s is a complex variable, I don't understand why the book says , e.g. for f(t) = exp(-at) ,then Re(s+a)>0.
Why did they simply ignore the imaginary part of variable s, or are they just considering the real part of the function?(which they didn't mention)?
The second question is when I was asked to verify   L(tsinat) =3 http://tutorial.math.lamar.edu/Classes/DE/Laplace_Table_files/eq0021M.gif  by using
L(cosat) =
the problem is why do we have to differentiate this formula with respect to a? I thought a was a constant value which can't be differentiated in many problems I encountered while solving ODEs before.
Thank you so much for helping! Greatly appreciated.
Answer: Hint for the second part: Use this fact that:
$$\mathcal{L}(t^nf(t))=(-1)^n\frac{d^n F(s)}{ds^n}$$ wherein $\mathcal{L}(f(t))=F(s).$
Comment: - needs a TU! +1
Answer: For the first question: If $s=\sigma + i\omega$ and $t$ is real, then
$$|e^{-st}|=|e^{-\sigma t}e^{-i\omega t}| = e^{-\sigma t}$$
since $|e^{i\omega t}|=1$. In other words it's only the real part of $s$ that determines where the ontegral converges.


Javascript Testing framework similar to dojo DOH

Question: Is there any framework in javascript similar to dojo DOH?
I am looking for testing framework which is browser-based like dojo DOH, it provide support for both browsers and JS runtime environment.
In simple words, I am looking for:

A simple browser-based graphical front end and runner file.

Why I am looking for other Testing unit instead of dojo DOH?
Dojo DOH come with complete package of DOJO, so if I develop an application in dojo then it good to use dojo DOH. Suppose I develop an application in other frameworks like Angular, Backbone etc.
Then only to test application I have to add complete dojo package with my application. (Please correct me if I am wrong, this assumption was made as per my experience on dojo)
Please guide me, if there is a possibility to test application using dojo DOH without adding complete dojo package.
Thanks Help!!
Answer: SitePen replaced DOH with Intern. Intern is well-tailored-for but not-specific-to the Dojo Framework. You can test any JS framework'd app with it. Note, though, I haven't used either.
Aside, an SE Architect I work with came back recently from a conference in love with Jasmine, so you may look at it. They seem to be completely different approaches to testing, so take a gander and decide for yourself where your tastes lie.
Comment: Thanks for reply, I'll try both and share my experience.


Post-hoc test after a GLM with binary data

Question: I have run various logistic regressions (GLM) from the binomial family and they have produced some very interesting results. I would now like to run post-hoc tests to find out which levels of the explanatory variables are significant, but I am finding it very difficult to find a post-hoc test that is compatible with my data.
I am looking at a population of skeletons. I have recorded the presence/absence of infectious lesions at the level of the individual. I have a response variable (Periostitis, which is a type of lesion and which has two levels: present and absent) and I have four explanatory variables (Age.Group, Sex, Cemetery, and Time.Period). These represent the age of the individual (A, B, C, and D), the sex of the individual (Male or Female), the cemetery the individual was recovered from (Cem1, Cem2, and Cem3), and the time period the individual is dated to (TP1 and TP2), respectivly.
I have run logistic regressions because my data is binomial. An example of which can be seen here:
Call:
glm(formula = Periosna$Periostitis ~ Periosna$Cemetery, family = binomial)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.9103   0.5931   0.6841   0.6841   0.9537

Coefficients:
                      Estimate Std. Error z value Pr(>|z|)
(Intercept)             1.3332     0.2087   6.387 1.69e-10 ***
Periosna$CemeteryCem2   0.3155     0.5311   0.594   0.5525
    Periosna$CemeteryCem3  -0.7811     0.3557  -2.196   0.0281 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 244.03  on 221  degrees of freedom
Residual deviance: 238.04  on 219  degrees of freedom
AIC: 244.04

Number of Fisher Scoring iterations: 4

I now want to run a post-hoc test to see which levels (Cem1, Cem2, or Cem3) are significant. I have read everything on this site and on others and have tried to run the glht function from the multcomp package. I see that there are different types of tests (matrix, character, expression, mcp, and mlf), but I do not know which to use. There is a lot of literature online about mcp, but I do not think that I can use this as my data is binomial. When I try to use it, I get an error code:
> library(multcomp)
>
> results<-glht(modelA,linfct=mcp(Cemetery="Tukey"))
Error in mcp2matrix(model, linfct = linfct) :
  Variable(s) 'Cemetery' have been specified in 'linfct' but cannot be     found in 'model'!

What would you suggest I use to analyze the levels of my explanatory variables?
Thank you very much for your help. I am stumped!
Comment: "I now want to run a post-hoc test to see which levels (Cem1, Cem2, or Cem3) are significant" *significant* in **what** sense? Do you want to test pairwise equality of group means?
Comment: I want to test to see which levels contribute the most to the outcome of the response variable. I do not know how to put that statistically.
Answer: The problem you haveg is that are abusing (misusing) the formula notation. You never use a formula like this:
Periosna$Periostitis ~ Periosna$Cemetery

because, as you've found out it, it totally breaks the logic that you want to then use for subsequent operations.
You asked mcp() to set up Tukey contrasts for the covariate Cemetery, yet you fitted a model with covariate name Periosna$Cemetery, hence it quite rightly told you that a variable of the stated name was not involved in the model fit.
Instead, the call should have been
glm(Periostitis ~ Cemetery, data = Periosna, family = binomial)

noting that we use the variable names directly, as they exist in Periosna, and we tell R where to locate the variables in the formula via the data argument.
Now when you call glht() it should be able to find the Cemetery variable.
Comment: Thank you very much, Gavin. I did not realize that the Periosna$ argument was so critical, but it makes complete sense when I read your answer. I ran the test again, and it worked. Thanks again.


Chamar mais de um script bat

Question: Estou com uma situação bem chatinha e não consegui achar solução, eu tenho 2 scripts e os mesmos são chamados através de um outro, meu problema é que ele chama um e não o outro, um inicia um tomcat e o outro inicia um banco hsql. Alguém pode me ajudar ? Está assim:
@echo off

call start-tomcat.bat tgg
call start-hsql.bat tgg

@pause

Answer: Se chamar os dois assim, iniciarão em janelas separadas:
@echo off

start start-tomcat.bat tgg
start start-hsql.bat tgg

@pause

Se chamar assim inciarão na mesma janela:
@echo off

start /b start-tomcat.bat tgg
start /b start-hsql.bat tgg

@pause

Comment: Show, muito obrigado.

Chamar mais de um script bat


Retrieving Data from Database which was entered from a drop down menu: data is showing as numeric

Question: I'm trying to retrieve data using SQL that was entered into a database using a drop down menu box.
The values from the box are things link "cap", "coupon", "liner" etc.
But when I try to retrieve the data from its location in the database (MaterialPackaging.Packaging) the value comes out as numeric.
ex: where it should be 'cap', it gives 12, 'tray' is 7, etc...
Why does this happen, and how can I fix it (preferrably without using some switch statement as a key of sorts) is there some sort of conversion that is going on here that I can change? Is this something partial to drop down menus?
Comment: perhaps your database has a lookup table for the various values, that you could join into your query?
Comment: I don't see a lookup table for this, but thank you for your help
Answer: Okay, your question is very vague.
What language and/or platform are you using?
Is it a ASPX form or a C# windows form?
Both allow drop downs to have values (1, 2, ..) associated with them.
Go to the source my friend!
Use SSMS, query the data table and see what the values are.  Maybe you are storing numeric instead of text strings.
If you really need text, please join to a decode table and return the text value that you want.
That way, you do not need to code a case statement on the front end!
Comment: I'm using an rdl report to return the values-- the data itself is entered through a management website that I am not trained in. SQL Server Management also shows numeric values.
Comment: Edit** Thank you-- I'm unfamiliar with decode tables; is there anything I should know?
Comment: A decode or look-up table are one in the same.  For each numeric code, have a text value in the table.  Join the original data to the decode table on the numeric code.  Just return the text value.  This avoids case statements when showing the detail content on the report.  For filtering, you will have to return back the numeric to SQL Server.  Good luck with your SSRS report ...


Why the twin prime conjecture isn't proved already by Euclid's theorem?

Question: I was wondering how Euclid showed that there are infinitely many primes by generating a prime number from finitely many primes, and if it could be used to answer if there are infinitely many pairs of primes whose difference is 2. I show my approach in my - short - article here (I know I should copy here the relevant bits, but the article is really short).
My question: why is it not proved like this already? Am I missing something?

Update:
It seems I was too lazy to check for counterexamples. I removed my article. Thank you for the lot of feedbacks.
Comment: This site is not an place to come to have articles reviewed and assessed.
Comment: Please read this answer https://mathoverflow.net/a/23521 under "Examples of common false beliefs in mathematics"
Comment: Yes, you're missing something.
Comment: $2 \cdot 3 \cdot 5 \cdot 7 -1 = 209$ is not prime.
Comment: You are missing a *lot*.  Your "article" proves nothing, but I suspect it would take too much time to explain it all.
Comment: Euclid never said that the product of the first $n$ prime numbers plus $1$ is prime.
Comment: Another one: https://math.stackexchange.com/q/1055365/42969
Comment: @WhatsUp Even this would not prove the twin prime conjecture. Only if $p$#$\pm1$ would be a pair of primes, we would get a prime-twin this way.
Comment: If the article is short, then there is no reason to not formulate it out here. But even then, amWhy's comment applies.
Comment: The primorials have been checked for primality upto very high limits. The only known twin prime pairs $p$#$\pm1$ occur for $p=3,5,11$. An interesting quesion would be whether there are infinite many such pairs, probably not.
Comment: Fermat was also too lazy when he conjectured that $2^{2^n}+1$ is always prime. Ironically, chances are very high that he already knew all primes of this form and that there are no more. Euler was the first to disrove this conjecture by finding $641\mid 2^{32}+1$
Answer: Euclid proof states that $\psi_n +1$ is itself prime or it contains new primes in its factorization, for example
$$2\cdot 3 \cdot 5\cdot 7 \cdot 11\cdot 13+1=30031=59 \cdot 509$$
Comment: See the comment above. Even if $p$#$+1$ would always be prime , the twin prime conjecture would still not be proven.
Comment: @Peter My answer is related to the proof given by the asker. Thanks anyway for your additional comment.


apache config dynamic documentroot

Question: we are programming a website in a test environment.
This website will have 2 languages
with urls like domain-language.com
eventually we need to switch over to a situation like domain/language.com
can we set up apache so that it can listen to domain/language.com
and depending on the approach the documentroot changes towards the subfolder of the aproached language? because we have a lot of hardcoded links on our website which might all have to be changed if the documentroot is a level higher .
the folder structure how i think it will look like is
/-
  language1
  language2
if i browse towards domain/language1.com i should get the subfolder language 1 as documentroot , making it the /
Answer: First of all, you can't use "/" within a domain name I guess. "/" is always using in Apache and browser as a delimiter between domain name and file/sub-folder. Hence try to use other symbols  like "-", "_" etc to replace the "/". In fact, it's definitely possible to set different Docroot for different domains.. any change in domain name (in your case it's language1 and language2) is considered as a different domain which can be mapped to separate DocRoot folder.

apache config dynamic documentroot


How do I print individuals fields in block.html.twig when is a node in a block?

Question: How do I print individuals fields in block.html.twig when is a node in a block?
The template is working fine. I can hard code some random text and it is displayed. I just can't display the field values.
I have already tried
{{content.my_field.0}}
{{content.my_field[0]}}
{{node.my_field.0.value}}
{{ content.my_field }}

But, after clear the cache doesnt work
Comment: Have you tried `{{ content.my_field }}`?
Comment: Did you clear the cache?
Comment: Yes, I have already tried {{ content.my_field }} and also I always clear the cache @NoSssweat
Comment: What do you mean by `when is a node in a block`?
Comment: `doesnt work` Are you getting an error?
Comment: @leymannx is a custom block, a node in a Block
Comment: @NoSssweat not, is not display the field values
Comment: Does it show up when you just do `{{ content }}` ?
Comment: @NoSssweat yes, works perfectly when I use {{content}} but not when I try to display individuals fields
Comment: And you know Devel's submodule Kint that lets you put `{{ kint() }}` in the template to inspect onpage what variables/objects are available? And have tried that already? I still don't get though where the node actually comes from.
Answer: You have to set "node" in the twig-variables of your block. I.e. you can do this in a template_preprocess hook like so:
function mytheme_preprocess_myBlock(&$variables) {
  $variables['node'] = Node:load(50);
}

Then you can access the "node" in your template like {{node.my_field.value}}.
The hard part is to find which node to load in the preprocess function :-)
Comment: Better way would be to have a block plugin with a specialized template. Then set the "node" in the build() function of your block plugin.
Comment: Better a custom block and then get the current node from context. https://gist.github.com/dsnopek/b4e0bc096b216d63a96d17559484dc51


Bound on count implies bound on numbers being counted. How?

Question: Let $C$ and $T$ be large real numbers.
Consider the inequality $$\sum_{\gamma \in \Gamma : |\gamma-T| \leq 1} 1 \leq C\log(3T)-1,$$ where $\Gamma$ is a finite set of real numbers.
Does this inequality imply that there exists a real number $T'$ such that
\begin{gather}
|T-T'| \leq 1, \\
|\gamma - T'| \geq \frac{1}{C\log(3T)} \quad \text{for all} \quad \gamma \in \Gamma.
\end{gather}
I'm reading a paper where an assertion of this type is made, but I can't see why it is true.
edit: Changed 2 to 3. But I don't think it should make a difference...
Comment: I think the idea goes something like this.  Let's say there are $N$ reals $\gamma$ within $1$ of $T$.  Then they lie on the interval from $T-1$ to $T+1$.  Then, worst case, they are evenly spread across this interval, with a space of $2/N$ between them.  Putting $T''$ in the middle gives a distance of $1/N$ to the nearest gammas, and all other gamma are farther away.  Where that "-1" goes, I'm not sure...but I think this is the idea..
Comment: Wait, the worst case spacing should be $2/(N-1)$, and then we can just throw away the difference since $1/(N-1) > 1/N$.
Comment: @MatthewConroy:  you also have intervals at the ends of the interval that can be half the length of the others.  That is why $N-1$ becomes $N$.  You have the idea.  Would you like to write up the answer?  Otherwise, I will.
Comment: Can you give an example of a $\Gamma, C, T$ where this is true, or where it is not true?
Comment: $\Gamma$ is the set of imaginary parts of the zeroes of a Dirichlet L function associated to a character $\chi$. See (for example) Proof of Theorem 8 on page 289 of the paper: Liu, Ming-Chit(PRC-HK); Wang, Tianze(PRC-HEN)Distribution of zeros of Dirichlet L-functions and an explicit formula for ψ(t,χ). Acta Arith. 102 (2002), no. 3, 261–293.  It is free to download here: https://www.impan.pl/en/publishing-house/journals-and-series/acta-arithmetica/all/102/3
Comment: Not that it that it makes any difference as far as I can tell, but the paper has $q\ge 3$ and you appear to be using $q=2$.  Any reason for that?
Comment: Mistake on my part. But like you say, I don't think it should make a difference. I'll edit
Comment: You go ahead.  Cheers!
Answer: Let $N=C\log(3T)$.  Your first says there are at most $N-1$ elements of $\Gamma$ that are in the interval $[T-1,T+1]$, which has length $2$.  You are asking to find $T'\in[T-1,T+1]$ that is far from all the elements of $\Gamma$.  If you think of spreading out the points to minimize the distances where $T'$ can go, they would be at $T-1+\frac 1N,T-1+\frac 3N,T-1+\frac 5N \ldots T-1+\frac {2N-1}N=T+1-\frac 1N$  All the gaps are of size $\frac 2N$ and the spaces at the ends are $\frac 1N$.  The points $T-1, T+1,$ and the midpoints of the intervals would all be candidates for $T'$.  If you move any points closer together to prevent putting $T'$ in an interval, you open up some other interval.
There is one nit that makes this not work.  You could squeeze the points together by a tiny bit to prevent putting $T'$ anywhere between the first and last points.  Then there could be points in $\Gamma$ at $T-1-\epsilon$ and $T+1+\epsilon$ that don't count in the initial count because they are outside the interval but prevent us from putting $T'$ in the ends of the interval.  We can fix that by either saying at the end for all $\gamma \in \Gamma \cap [T-1,T+1]$ or by making the denominator in the distance between $\gamma$ and $T'$ into $N+1$ instead of $N$ so the end intervals are of length $\frac 2{N+1}$ instead of $\frac 1N$


Why is $|x-8| \le 1$ equivalent to $-1 \le x-8 \le 1$?

Question: My book presents the following: $$7 \le x \le 9 $$ so $$ -1 \le x - 8 \le 1 $$ and $$ |x-8| \le 1$$
I usually get confused with the way that taking the absolute value of an expression works. Could anybody explain why the inequalities above are equivalent? I understand how the first and the second one are equivalent but not how the third one is equivalent to the second one.
Comment: The absolute value of $x-a$ is the *distance* between $x$ and $a$. Think geometrically, with a "number line." I Don't like the first transition, from $7\le x\le 9$ to the next line. Oh, it is absolutely correct. But the real point is that $8$ is **halfway** between $7$ and $9$. So if you sit at $8$, everybody is at distance $\le 1$ from you.
Answer: On a number line, $|x-a|$ represents the (non-negative) distance between $x$ and $a$.  So $|x-8| \leq 1$ can be interpreted as: The distance between $x$ and $8$ is no more than $1$ unit.  This immediately gives you $7 \leq x \leq 9$.
To analyze this the other direction, if $a \leq x \leq b$, then think of the midpoint:  $\frac{a+b}{2}$, and half the distance from $a$ to $b$: $\frac{b-a}{2}$.  You obtain:
$$ \left| x - \frac{a+b}{2} \right| \leq \frac{b-a}{2}.$$
Comment: I think your approach here is very good: what's happenin' comes first, then, maybe, manipulation.
Answer: Suppose you had $|x| < a$ (note: the idea below holds the same for $\leq$ as well). Let's break this into two cases: $x \ge 0$ and $x < 0$.
If $x \ge 0$, then $|x| = x$ since $x$ is already nonnegative so what the inequality $|x| < a$ says in that case is that $x < a$.
If $x < 0$, then $|x| = -x$ since $x$ is negative. What the inequality then says is that $-x < a$, or equivalently that $x > -a$.
Putting these two pieces together we get that $-a < x < a$. In your case we have that $-1 \leq x - 8 \leq 1$. Well using the above expression, we have that this is equivalent to $|x-8| \leq 1$.
Answer: First of all, inequality relation is unaffected by
$(i)$ the addition (hence, subtraction) of finite real numbers
$(ii)$ the multiplication (hence, division) by finite positive real numbers
Again if $y$ is real and $|y|\le b$ Clearly, $b\ge0$
$\implies y^2\le b^2\implies (y-b)\{(y-(-b)\}\le0$
$\implies$ either $y\ge b$ and  $y\le -b$ which is impossible as $b\ge0$
or $y\le b$ and $y\ge -b\implies -b\le y\le b$


Delta files not deleted

Question: I found out that my VM is running with a snapshot which is not visible in the snapshot manager.
I found out also that the machine is running on a delta file (probably an old snaphot)
I see there are procedures to consolidate snapshots but what I want to understand now is :
Having a VMDK-flat disk of 50gb =>which is actually the vdisk created at the beginning
Now I have a DELTA file of 38 gb...and this file it is growing on daily basis.
My question is : why the delta file is growing ? is that normal ?
Answer: I'm sure some more VM-savvy people will chime in here, but it sounds as though the delta file is doing what it is supposed to.
As far as I know, snapshots work via copy-on-write, where you start out with the original image (that's your vdisk) and an empty file (that's the delta file). Every time anything is changed at all, that change is made on the delta disk. The original disk isn't touched, that way if you ever need to revert to a snapshot, the delta file  is thrown away and everything is read from the original vdisk.
Over time, this leads to the side effect of the delta file growing massively as things are changed, added, and removed. As I understand it, if you add a 10MB file, the delta file grows by 10MB. Remove that file, and it grows by another 10MB, because there is a 10MB difference. I could be wrong, and it might actually shrink by 10MB, but I don't think so. (Please someone correct me).
If you consolidate your changes into your snapshot, you'll be back to the original 50GB disk image by itself.
Of course, I could be horribly wrong and mistaken, in which case I'll be voted down, and you should listen to whoever comes in and knows more.
Comment: You are correct VMware uses their sparse disk format for disk snapshot delta files which is a COW mechanism. Snapshots can definitely grow as big as the source volume if left runnning for extended periods of time and they never shrink no matter what changes you make until you delete the snapshot.
Answer: It's normal for the delta file to grow. What Matt says is correct about how snapshots work. What's not normal is the snapshot not showing up in the snapshot manager. I suspect that you can't take any new snapshots of that VM either. It sounds like an orphaned snapshot.
You need to backup and then shut that VM down, if you can.
This KB might help if the snapshot can be detected. Otherwise the only way I solved this in the past was to manually delete the snapshot files, rewrite the .vmx file and bring the VM up in a crashed state, losing all changes in the snapshot.
If the VM won't shut down you need to find the correct process on the host and kill -9 it from the service console.
Then you need to rename or delete all the [guestname]-######-delta.vmdk, [guestname]-######.vmdk, [guestname]-Snapshot###.vmem.WRITELOCK files.
Then edit the vmx file. Look for the line scsi0:0.fileName. It should list one of the snapshot files as the hard disk. Change it to the original vmdk file. When you start the VM it will tell you that it had crashed. You lose the contents of the snapshot but at least you'll have the server back.
It's a harsh solution but there's not a whole lot you can do if ESX says there's no snapshot there and the VM refuses to shut down.
Comment: Would another solution be to run the vmware converter on it, and turn it into another VM, which you can then use to replace the "broken" one?
Answer: This sort of thing can get very messy. Phosdex and Matt have pretty much covered the worst case scenarios.
I'd recommend following the instructions in this VMware KB1002310 troubleshooting document, it covers the same approach as the one Phosdex linked to but it provides some more tips on how to establish if the snapshots you are looking at are actually associated with the VM you think they are. Sometimes they aren't, I've seen it happen when people move VM's around   in an effort to "tidy" things up using the Datastore Browser.
If that still fails you can take a slightly out of the box approach and use VMware Converter to carry out a P2V migration on the VM. Even though it's a virtual machine if you treat it as a physical target Converter will pull the current state from within the context of the Guest OS and wont care if there are dodgy snapshots in some unmanageable state. It will then copy the current state of the VM to a nice fresh clean target leaving the snapshot mess behind. Once you have the converted copy running (isolated from the production network though) you can safely kill the original any way you like and connect the copy to production. Once you are certain the copy is OK you can delete the old VM entirely.

Delta files not deleted


Passar parâmetro para componente da Tab.Screen

Question: Como passar parâmetros para o componente da Tab Screen?
Ficha/index.js:
import Historico from './Historico';

export default function Ficha({ route, navigation }) {

  const { periodo } = route.params; // quero passar o periodo para o Historico

  return (
    <Tab.Navigator
        screenOptions={({ route }) => ({})}
        tabBarOptions={...}
    >

    <Tab.Screen
      name="Historico"
      component={Historico}
      options={{
        title: 'Histórico',
        tabBarOptions: {
          tabStyle: {
            width: 'auto',
          },
        },
      }}
    />

    ...

   </Tab.Navigator>

 );

Historico/index.js:
export default function Historico({ navigation }) {
  // acessar aqui, de alguma forma, o "periodo" passado na Tab Screen.
  ...
}

Answer: Izi pizi
export default function Historico({ navigation, route }) {
  ...
  console.log(route.params); //provavelmente o valor ja vai estar
                            // aqui, se nao estiver voce segue o exemplo abaixo tambem
}

  <Tab.Screen
      name="Historico"
      component={Historico}
      initialParams={{ periodo }} <----
      options={{
        title: 'Histórico',
        tabBarOptions: {
          tabStyle: {
            width: 'auto',
          },
        },
      }}
    />


Laravel Models properties declaration

Question: I have the following model:
class User extends Authenticatable
{
 private string $first_name;

 public function name()
 {
  return $this->first_name;
 }
}

when I call that method from a controller, I'm getting

User::$first_name must not be accessed before initialization

Also, if I'm commenting/removing the declaration of property, the method runs well with no errors.
Comment: Hi @cristisst, What is returned if you remove the property declaration? I assume it is `null` but I just want to make sure.
Comment: the value of first_name not `null`
Comment: So. "What is returned if you remove the property declaration?"
Comment: Also note that the property `$first_name` will not map to the element in the database. If you have a field in the database called `first_name` then the class property will overshadow the database field and hence the uninitialised error.
Comment: you can solve the problem Defining An Accessor, see document https://laravel.com/docs/8.x/eloquent-mutators
Comment: if I remove the declaration of the property, then I'm getting the value from the database of `first_name`. it's really weird.
Comment: I don't understand why you're declaring a property on an Eloquent model. You don't do this in Eloquent for database fields - Eloquent doesn't work that way. The only time you should declare a property on an Eloquent model is when it's something used by Eloquent, such as the `$table` property. If you want to provide more info for an IDE or static analysis you need to use the @propery annotation on the class instead
Answer: You can use an accessor to achieve this:
class User extends Authenticatable
{
 public function getNameAttribute()
 {
  return $this->first_name;
 }
}

Instead of calling the method, you only access a property with get prefix and Attribute suffic removed like so: $user->name
Answer: PHP 7.4 introduced typed properties.
Typed properties need to be initialised before accessing it. You can read more about that error in this article

That's why typed properties without a default value now have an
uninitialized state. When calling a method that accesses such an
uninitialized state, you'll get the "Typed property User::$username
must not be accessed before initialization" error.
Note that nullable typed properties also have this uninitialized state
instead of having null as default value.

So simply initialising it will fix the error: private string $first_name = "init value";
But since you reference Models in the question title I assume you are using Eloquent models.
class User extends Authenticatable {
    ...
}

And then you also don't need to put the model properties on the class. Eloquent will automatically map the database fields as properties on the object.
Comment: You don't need to extend `Model` on the `User` class as the `Authenticatable` class extends it.
Comment: The `Authenticatable` I imported is an `interface` so you do need to extend `Model`. If you import `Illuminate\Foundation\Auth\User as Authenticatable` (as I've seen in many examples) then, yes, you only need to extend `Authenticatable`.
Comment: My point was; replacing the default `User extends Authenticatable` with `User extends Model implements Authenticatable` is pointless.
Comment: But not incorrect. It wasn't always the default so thats where the mixup happened. Thanks. Ill edit the answer.

Laravel Models properties declaration


Integral Notation , integrating over integers.

Question: What would it mean to integrate over a set of numbers like the integers? For example
if given an integral whose bounds are negative to positive infinity, one can express this as:
What I was thinking is that this would not come to much use since this would be like integrating a point. Which would yield zero for every integer over which you integrate. I suppose if you were integrating a delta function this would be the only exception.
\begin{equation}\int_\mathbb{R} f(x)dx \ \text{vs.} \int_\mathbb{Z} f(x)dx  \end{equation}
Comment: If you are talking about Riemann integration or Lebesgue integration with respect to the Lebesgue measure then the result will be zero. If you use the counting measure on $\mathbb{Z}$ then you have $\int_\mathbb{Z} f(n) d |\cdot|(n) = \sum_{k \in \mathbb{Z}} f(k)$.
Comment: Not of much use. With a function, yields zero, and with delta distributions yields a discrete summation.
Comment: Hello and welcome to Mathematics StackExchange! Are you familiar with the notion of a Lebesgue integral, that would give you the right definition. Also try to use MathJaxx instead of a picture if you can. Greetings,
Comment: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference I recommend you look here for posting posts its very helpful.\
Comment: Great Question. +1
Comment: What does the FTC say about an integral on an interval whose starting and ending endpoints are the same? What if I have several of them?
Answer: In Lebesgue's theory of integration, one can integrate over any "measurable" set of real numbers, and non-measurable sets are exotic things not encountered in practice. (In the context of probability theory, however, sets failing to be measurable with respect to certain sigma-algebras that must be considered. But you should consider this parenthetical comment optional until you learn some of the relevant things in probability theory.)

By the usual way of assigning a measure to a set of real numbers, the measure of the set of all integers is $0,$ and consequently if one integrates any function over that set one gets $0.$
But one can assign other measures to the set of all integers, in which a positive number is assigned to some or all sets containing just one integer. The most usual way to do this is that the measure of each set $\{n\}$ is $1.$ In that case, the integral over the set of all integers is just the sum of an infinite series.


How to launch a URL in IE instead of Edge from a Windows 8/10 WInJS application

Question: I want to open one URL on IE browser not on default edge browser from a windows 8.1/10 universal application using phonegap,WinJS etc..
I got same question
How to launch a URL in IE10 from within a Windows 8 WInJS application?  but the solution from this question is not working as its opening on default edge browser.
I am using cordova ,WinJs to develop this application.
i have tried inAppBrowser and its also opening on default edge even if we specify metatag specifically to any of the IE version like this.
<code>  <meta http-equiv="X-UA-Compatible" content="IE=9" />
</code>
and also tried from C# using runtime component but every time its opening on EDGE browser but i need specific IE (IE9 or IE10 etc... )
Answer:
Windows Store apps cannot launch specific apps. The can launch documents or URIs only into the default handler for the type

From MSDN thread:https://social.msdn.microsoft.com/Forums/windowsapps/en-US/1c93b5a8-ead8-4e51-83f3-763b1db53324/how-to-open-nondefault-browser-on-clicking-hyperlink-having-target-blank-in-webview-?forum=winappswithcsharp


Identify $\mathbb{R}/\mathbb{N}$

Question: I need help with this problem:
Define a equivalent relation in $\mathbb{R}$:
1-identifying $x$ with itself if $x \notin \mathbb{N}$
2-$1,2,3,...$ belongs to the same equivalent class (I am asuming that $\mathbb{N} =\{1,2,...\}$).
Let's call $\mathbb{R}/\mathbb{N}$ the set of equivalent classes under the relation defined above.  Also I can give the quotient topology to $\mathbb{R}/\mathbb{N}$. There is a geometric way to picture this topology set?
Thank you
Comment: You can imagine $\mathbb{R}$ as being the $x$-axis in $\mathbb{R}^2$.  Then take the point $(0,1)$ and draw a line from it to each point of $\mathbb{N}$.  Your $\mathbb{R}/\mathbb{N}$ is topologically equivalent to that.  By shrinking the added lines, it becomes a wedge of circles.
Comment: beautiful!  thank you very much
Answer: Starting from $X_2=\mathbb{R}/ \{1,2\}$: it can be imagined as two step construction:

$((-\infty,1]\cup [2,\infty))/\{1,2\}$ - it is homeomorphic to $\mathbb{R}$.
$[1,2]/\{1,2\}$ is homeomorphic to circle $\mathbb{S}_1$.

Gluing those two up gives real line tangent to circle. This is $X_2$.
Going up in $k=3,4,...$ will add to $X_k$ another circle that meets all other and the line in one point. This means that $X_{\omega}=\mathbb{R}/\mathbb{N}$ is ray $(-\infty,1]$ glued up with countably many circles at one point.
Comment: This is a good picture. But a word of caution: We can construct this in $\mathbb R^2$ but the quotient  topology is NOT the subspace topology as a subspace of  $\mathbb R^2$ (with the usual topology on $\mathbb R^2$).  In $\mathbb R/\mathbb N ,$  the  point (the equivalence class) $\mathbb N$ is a point with uncountable character.

Identify $\mathbb{R}/\mathbb{N}$


Read data from csv file with foreach function

Question: I have been reading data from csv, if there is a large csv file, for avoid this time-out(rack 12 sec timeout) i have read only 25 rows from csv after 25 rows it return and again make a request so this will continue until read all the rows.
def read_csv(offset)
  r_count = 1
  CSV.foreach(file.tempfile, options) do |row|
  if r_count > offset.to_i
    #process
  end
  r_count += 1
end

But here it is creating a new issue, let say first read 25 rows then when the next request comes offset is 25 that time it will read upto first 25 rows then it will start read from 26 and do process, so how can i skip this rows which already read?, i tried this if next to skip iteration but that fails, or is there any other efficient way to do this?
Comment: As i have this upload feature for my application
Comment: Did you consider processing the CVS in a background job?
Comment: No because i have to show the final count of how many items are uploaded  to user, also if there any issue with that csv that one also i have to tell to user
Comment: @django were you able to find a solution for this? Could you share for those searching for an answer in the future or mark this complete based on one of the answers provided?
Answer: Code
def read_csv(fileName)
  lines = (`wc -l #{fileName}`).to_i + 1
  lines_processed = 0
  open(fileName) do |csv|
    csv.each_line do |line|
      #process
      lines_processed += 1
    end
  end
end

Pure Ruby - SLOWER
def read_csv(fileName)
  lines = open("sample.csv").count
  lines_processed = 0
  open(fileName) do |csv|
    csv.each_line do |line|
      #process
      lines_processed += 1
    end
  end
end

Benchmarks
I ran a new benchmark comparing your original method provided and my own. I also included the test file information.
"File Information"
Lines: 1172319
Size: 126M

"django's original method"
Time: 18.58 secs
Memory: 0.45 MB

"OneNeptune's method"
Time: 0.58 secs
Memory: 2.18 MB

"Pure Ruby method"
Time: 0.96
Memory: 2.06 MB

Explanation
NOTE: I added a pure ruby method, since using wc is sort of cheating, and not portable. In most cases it's important to use pure language solutions.
You can use this method to process a very large CSV file.
~2MB memory I feel is pretty optimal considering the file size, it's a bit of an increase of memory usage, but the time savings seems to be a fair trade, and this will prevent timeouts.
I did modify the method to take a fileName, but this was just because I was testing many different CSV files to make sure they all worked correctly. You can remove this if you'd like, but it'll likely be helpful.
I also removed the concept of an offset, since you stated you originally included it to try to optimize the parsing yourself, but this is no longer necessary.
Also, I keep track of how many lines are in the file, and how many were processed since you needed to use that information. Note, that lines only works on unix based systems, and it's a trick to avoid loading the entire file into memory, it counts the new lines, and I add 1 to account for the last line. If you're not going to count headers as line though, you could remove the +1 and change lines to "rows" to be more accurate.
Another logistical problem you may run into is the need to figure how to handle if the CSV file has headers.
Answer: You could use lazy reading to speed this up, the whole of the file wouldn't be read, just from the beginning of the file until the chunk you use.
See http://engineering.continuity.net/csv-tricks/ and https://reinteractive.com/posts/154-improving-csv-processing-code-with-laziness for examples.
You could also use SmarterCSV to work in chunks like this.
SmarterCSV.process(file_path, {:chunk_size => 1000}) do |chunk|
  chunk.each do |row|
    # Do your processing
  end
  do_something_else
end
enter code here

The way I did this was by streaming the result to the user, if you see what is happening it doesn't bother that much you have to wait. The timeout you mention won't happen here.
I'm not a Rails user so I give an example from Sinatra, this can be done with Rails also. See eg http://api.rubyonrails.org/classes/ActionController/Streaming.html
require 'sinatra'

get '/' do
  line = 0
  stream :keep_open do |out|
    1.upto(100) do |line| # this would be your CSV file opened
      out << "processing line #{line}
"
      # process line
      sleep 1 # for simulating the delay
    end
  end
end

A still better but somewhat complicated solution would be to use websockets, the browser would receive the results from the server once the processing is finished. You will need some javascript in the client also to handle this. See https://github.com/websocket-rails/websocket-rails


How do I create this table using HTML table tags?

Question: How do I create this table using HTML table tags?
Comment: That doesn't look like something where a table is an appropriate data structure to use.
Answer: Something similar to this could be used:

	<td width="25%"

Answer: This is a sketch: when possible I would remove all of those constraints to widths and height.

table{border-collapse:collapse;width:100%}
table,td{border:1px solid #000}
td{height:5em;width:25%}


For linux, getting the total CPU time of a process and all it's sub processes that ever existsed

Question: So basically I have multiple users on my system and I want to determine how much CPU time they spend while being logged in into their shell and running different commands. I have a script which knows the PID of the shell they are logged in with. I must be able to probe the value regularly so I can't simply run the shell in time(1) or something like that.
I have glanced at /proc/$pid - anyone knows of a good value (or combination of values) there I could use? Maybe there's some kernel module for this?
An acceptable solution to my problem would allow querying init (the process with pid = 1) and find the total CPU time the entire system has used so far.
Comment: You just want to know how much CPU time they use or you want to limit it? Because resource quotas would help with the latter...
Comment: Do you want total CPU usage per user or for the whole system?
Answer: Look at using cgroups to throttle and control activity on a per-user basis to a per-cpu basis. Once that is done you can use the cgroups statistics patch to generate the information you are looking for.


Make Reference to Variable in a View in SQL Server

Question: I am to make modifications to a view in SQL Server. Below is the view code:
ALTER View [dbo].[SupplierPOImport_Errors]
AS
SELECT
SupplierName,
Case SupplierID WHEN 0 THEN 'NO' ELSE 'YES' END AS 'SupplierFound',
PONumber,
InvoiceNumber,
InvoiceDate,
ItemNumber,
ItemBarcode,
Description,
Quantity,
Cost,
Tax,
Case ItemID WHEN 0 THEN 'NO' ELSE 'YES' END AS 'ItemFound',
Case PurchaseOrderID WHEN 0 THEN 'NO' ELSE 'YES' END AS 'POFound',
--Case Quantity WHEN 0 THEN 'NO' ELSE 'YES' END AS 'UnderSupplied',
(SELECT SUM(quantity * Cost) FROM SupplierPOImport) AS TotalExGST,
(SELECT SUM(quantity * Cost * (100 + Tax)/100) FROM SupplierPOImport) AS TotalIncGST,

  -- REQ 5
  Case WHEN ItemNumber = (SELECT OrderNumber
  FROM [RMS_SO_SM_PO].[dbo].[PurchaseOrderEntry]
  INNER JOIN
  [RMS_SO_SM_PO].[dbo].[PurchaseOrder]
  ON PurchaseOrder.ID = PurchaseOrderEntry.PurchaseOrderID
  WHERE
  PurchaseOrder.PONumber = SupplierPOImport.PONumber AND
  PurchaseOrderEntry.OrderNumber = SupplierPOImport.ItemNumber) THEN 'NO' ELSE 'YES' END as 'POAdded',

-- REQ 6 A

  CASE WHEN EXISTS(SELECT ItemNumber FROM SupplierPOImport t1
   INNER JOIN SupplierList t2 ON t1.ItemNumber = t2.ReorderNumber
   INNER JOIN ITEM t3 ON t2.ItemID = t3.ID
   INNER JOIN SupplierPOImport_Errors t ON t.ItemNumber = t1.ItemNumber
   WHERE
    t3.SupplierID = t1.SupplierID AND
    t1.ItemNumber = t2.ReorderNumber AND
    t1.ItemNumber = t.ItemNumber)
    THEN 'YES' ELSE 'NO' END AS 'PRIMARY'
FROM SupplierPOImport

GO

REQ 6 returns more than one record, because the ItemNumber for ItemNumber = SupplierList.ReorderNumber refers to the table SupplierPOImport. I need it to refer to the ItemNumber in the view, as this is talking to a VB.NET application, that imports the data into the table SupplierPOImport. With the View, I am able to write logic for every row in the datagrid in the application.
So, what I would like is a way to compare my Query, against the ItemNumber Value in my View. The way REQ 5 works is that for every row that is imported, it sends back a YES or NO to the VB.NET Application. It checks whether the current ItemNumber is equal to what the query returns. The query has a PONumber WHERE clause(it gets it from the View). However for REQ 6, I want a way to refer to the ItemNumber.
Essentially, I want it to return YES whenever my ItemNumber exists in the query. I have tried to use TempItemNum = SupplierList.ReorderNumber but SQL does not recognize TempItemNumb in the query.
I get this error below when I try to execute this:
View or function 'SupplierPOImport_Errors' contains a self-reference. Views or functions cannot reference themselves directly or indirectly.
Could not use view or function 'SupplierPOImport_Errors' because of binding errors.
Comment: This isn't very clear. We don't have the full view, and some sample data and desired results would be very helpful.
Comment: Please post the entire view.  If it's too big to fit in a single question, then _you_ need to find a minimal version to show us.
Comment: Thanks. I have added the entire view that I am using. Is this helpful now?
Comment: I'm still scratching my head at _ItemNumber in the view_. What does this mean? What bearing does it have on the application?
Comment: It holds the different ItemNumbers for each row of the table, so it does its calculations and passes it to the application for each row.
Answer: Your original question returns a YES or NO in a column but the function you posed as an answer returns an ItemNumber. So here's a guess of what you want.
The SQL you posted was actually really close to what was required. Please try this and if it isn't what you want, please explain why it is different.
I have only done one column here. If this is progress we can work on the next column.
ALTER View [dbo].[SupplierPOImport_Errors]
AS
SELECT
SupplierName,
Case SupplierID WHEN 0 THEN 'NO' ELSE 'YES' END AS 'SupplierFound',
PONumber,
InvoiceNumber,
InvoiceDate,
ItemNumber,
ItemBarcode,
Description,
Quantity,
Cost,
Tax,
Case ItemID WHEN 0 THEN 'NO' ELSE 'YES' END AS 'ItemFound',
Case PurchaseOrderID WHEN 0 THEN 'NO' ELSE 'YES' END AS 'POFound',
--Case Quantity WHEN 0 THEN 'NO' ELSE 'YES' END AS 'UnderSupplied',
(SELECT SUM(quantity * Cost) FROM SupplierPOImport) AS TotalExGST,
(SELECT SUM(quantity * Cost * (100 + Tax)/100) FROM SupplierPOImport) AS TotalIncGST,

  CASE WHEN EXISTS (
  SELECT *
  FROM [dbo].[PurchaseOrderEntry]
  INNER JOIN [dbo].[PurchaseOrder]
  ON PurchaseOrder.ID = PurchaseOrderEntry.PurchaseOrderID
  WHERE
  PurchaseOrder.PONumber = I.PONumber AND
  PurchaseOrderEntry.OrderNumber = I.ItemNumber
  ) THEN 'NO' ELSE 'YES' END as 'POAdded'

FROM SupplierPOImport I

Comment: Sorry, I was not very clear at all. I should be more articulate in my questions. What I have done is this in the View:

  -- REQ 6
  CASE WHEN ItemNumber = (SELECT dbo.MCS_CheckPrimarySupplier(ItemNumber)) THEN 'YES' ELSE 'NO' END AS 'PRIMARY',

So, This function only returns a value that should be equal to the current ItemNumber in the view... does this make sense? I am not an SQL guy, Mostly I develop for NAV, so SQL is new territory
Comment: notice how when I call a function and pass in the ItemNumber, I can use that in my query(refer to the function I showed), but when I write the same query in the view, I cannot refer to that ItemNumber that I am passing now instead... Does this make things clear?...
Comment: Did the view return the correct result or not? If not, why?
Comment: In my answer, it does exactly the same thing, except that you are not using an expensive function.
Comment: "The current item in the view" is just "SupplierPOImport.ItemNumber"
Comment: I see. I will accept this as the answer, as this works great. Cant believe how simple it was. Thanks.
Comment: Great. The learning to take from this is, in SQL, try to think _set based_, not _procedural_
Answer: In Req 6 you do an INNER JOIN against
SupplierPOImport_Errors

which is the same name you try to use for the view you try to create. That's the problem. I guess you already have a table with the same name. If that's the case, just use a different name for the view you are creating. Prefixing tables with T_ and views with V_ is a useful naming convention to avoid that
Comment: Table is named SupplierPOImport, View is named SupplierPOImport_Errors, The way I wrote Req 5, I am able to do what I want, but thats not working for Req 6.
Comment: Please take another look at line 4 of Req 6


try except syntax error

Question: I have a problem with the next code.
try: 1+1
except Exception as exception: pass
1+1
try: 2+2
except Exception as exception: pass

The result I get in the prompt is
... ...   File "<stdin>", line 3
    1+1
    ^
SyntaxError: invalid syntax
>>> ... ... ... 4

However the next code executes with no error.
try: 1+1
except Exception as exception: pass

try: 2+2
except Exception as exception: pass

My sys.version_info is:
sys.version_info(major=2, minor=7, micro=3, releaselevel='final', serial=0)

Why do I get the syntax error?
Answer: When using the interactive prompt, there needs to be a blank line between a block (such as a try/except block) and the next independent command. This is only in the REPL, when running a .py file it's not necessary.
Comment: @Usobi basically, when you're in the REPL and the prompt is `...` instead of `>>>`, you're still inside a block.

try except syntax error


How do I download a specific version of a module?

Question: The official documentation for Drupal Console says that the arguments for drupal module:download are the following.
drupal module:download [arguments] [options]

is there an argument or option to specify the dev/beta version of the module?
Answer: We can use following code to download latest stable release :
drupal mod modulename --latest

if we want to select a specific release other than latest then we can go for
drupal mod modulename --unstable

hope this will help.
https://docs.drupalconsole.com/en/commands/module-download.html


Correct statistical analysis for comparison of two groups with 5 subgroups (in R)

Question: I need to find the correct way to compare the following:
I have 500 patients split into two groups (Seazure and No-Seazure)
The groups characteristics match (age, gender etc. is non significant)
The comparison variable is WFNS-grading:
grade 1: GCS 15, no motor deficit. grade 2: GCS 13-14 without deficit grade 3: GCS 13-14 with focal neurological deficit grade 4: GCS 7-12, with or without deficit. grade 5: GCS <7 , with or without deficit.
I just can't able to find the median or the Mean because the grades Are more like A-E.
So what statistical analysis do I need to use to calculate if the severity (grading) is significant different between Seazure and No-Seazure.
I am using R, to make My calculations
Comment: What are you actually trying to do? I.e. do you have a clear question you wish to address? Whether differences in the characteristics of groups are significant or not is not usually considered an useful, reliable or acceptable criterion for determining what should play a role in the analysis.
Comment: My question is: i there a significant difference in the two groups severity of SAH (WFNS)?
Answer: Seizure grade appears to be an ordinal variable. There are a few options for these. One is to use a test such as Jonckheere-Terpstra. In R, one way to do this is jonckheere.test.  Another method is to treat this as a regression problem with ordinal logistic regression. Then "grade" would be the dependent variable and "group" would be the independent variable. One nice thing about ordinal regression (vs. JT) is that you can include covariates. However, ordinal logistic regression makes more assumptions that JT.
Comment: Logistic Regression. Of course.. I think i overthought it... Thx
Comment: Would you use something like polr(DCI~Age+Gender+WFNS...?
Comment: That looks about right.


XSS vulrenability in

Question: Summary: The
 attribute does not escape HTML, hereby opening a potential XSS attack hole. How can I solve it?
Original question below (original title was: XSS Attacks : How to prevent Script injection in Response of application):

I am working JSF Application currently i am facing issue with xss attacks i have done several research on it. but not able to find the solution. i am using OWASP tool for testing. i am able to prevent xss attacks in request but not for response.  For request i used filter which filters the request and giving the correct output but the response is not handled by same solution. once the response comes from application control goes to OWSAP then I am injecting Script inside it and its get displayed on the browser :(
Xhtml Code:

                    <f:facet name="header">ID</f:facet>
                    <h:outputText value="#{region.id}" />

                    <f:facet name="header">Region</f:facet>
                    <h:outputText value="#{region.regionDescription}" />

                    <f:facet name="header">Action</f:facet>

                        <f:setPropertyActionListener value="#{region}" target="#{regionsBean.forDelete}" />

response in OWSAP:

If You see the above code here i am inserting alert <.script>confirm(1);<./script>. tag.
The solution which i tried :
1) Filter which is working for request not for response.
2) used escape attribute
3) Content Security Policy inside  tag (i am using mozila firefox)
 <meta http-equiv="Content-Security-Policy" content="script-src  'self' https://apis.google.com;" />

Thanks For your help in advance.
Answer: After reading three times, your fairly convoluted question boils down to:

The
 attribute does not escape HTML, hereby opening a potential XSS attack hole. How can I solve it?

This is a known issue which was already fixed since PrimeFaces 3.5. Further the
 has also a XSS vulrenability which is only fixed since PrimeFaces 5.2 RC1. PrimeFaces is currently already available as 5.3. So, just upgrade to latest and this problem should disappear.
If you really can't upgrade, below are your options:

Make sure that user-controlled input never ends up in
. It's only vulrenable when enduser has full control over its value.
Or, rebuild the older versioned JAR to include the fix.
Or, escape it yourself beforehand using JSTL #{fn:escapeXml()} function.

Don't forget to remove after a upgrade to at least PrimeFaces 5.2, otherwise it will be double-escaped.

To be clear, JSF is designed to have builtin XSS prevention over all place. When you discover a XSS hole while already using the most recent version of the JSF implementation or JSF library, then it's just a bug which you should by all means report to the JSF impl/library guys. See also CSRF, XSS and SQL Injection attack prevention in JSF.
Comment: Thanks for response. I am using primefaces 3.4.2 is there any wayout for this problem. as i am seeing there is change in src/main/java/org/primefaces/component/confirmdialog/ConfirmDialogRenderer.java as fix in 5.2 so i need to modify the jar of 3.4.2 and need to test
Comment: and for escape i tried this alternative

 for the message of p:confirmDialog
Comment: Thanks for answers update @balusC  you always hope for us :) let me check with the fixes
Comment: Am I right to believe that `of:escapeJS` would be better than `fn:escapeXml`?
Comment: @ForguesR: Use of:escapeJS() if you need to print the value as part of actual JavaScript code. Use fn:escapeXml() if you need to print the value as part of actual X(HT)ML value.
Answer:
Content-Security-Policy (CSP) is usefull and you should continue using it. But it should be in an http header, not in a html meta. And, it's only a protection against bug (like the one you have).
You have an inline script. Your CSP do NOT allow inline script (and it's GOOD because inline script are bad for security. Do not use them. Put javascript in javascript file. (if you read more about csp, keywords containing the word 'unsafe' contain if for a good reason)
The code generating :"You are about to delete the Region [confirm(1);]. Proceed?"

message="You are about to delete the Region [#{regionsBean.forDelete.regionDescription}]. Proceed?"

SHOULD have encode regionsBean.forDelete.regionDescription . Are you able to produce yourself the injection ? (without the OWASP tools?)
Comment: thanks for your response. I am Using OWASP tool for testing, ON my xhtml i am using  when i am clicking on delete button its showing this confirm dialouge box but before showing that in OWASP response i am inject inline JS alert. and the response is in Javascript
Comment: @vinod sorry, but "what is the code generating that HTML" I mean, what is the code in YOUR application that generate "You are about to delete the Region [name_of_the_region]. Proceed?"
Comment: Thanks. Can you edit your question to show the code genetating the content inside  ? How do you insert the name of the region in the sentence  "You are about to delete the Region [name_of_the_region]. Proceed?" ?
Comment: i have added all code hope this will be easier to understand. Thanks
Comment: I've edit my answer, but I can't help you further. With your question now improved, I hope some JSP folks can help you

XSS vulrenability in


Capistrano: How can I trigger a task on ALL hosts if ANY of them is failing a check?

Question: I am using capistrano to deploy a rails application.
I have a challenge of running a check across ALL hosts and then determining if a task should be triggered on ALL hosts, if ANY of them fails the check. The check could e.g. be looking for a file:
desc "Make sure file is on all servers"
  task :do_something do
    on roles(:app) do
      unless test("[ -f /some_dir/the_file.txt ]")
        # Run something on ALL servers if missing on just one of them...
      end
    end
  end
end

I have also considered if it could somehow be done by first running one task on all servers and combining up the result of those and then in a second task run it if the output of the first had the file missing on any of the servers.
Answer: I figured it:
task :check_something do
  has_file = []
  on roles(:app) do
    has_file << test("[ -f /some_dir/the_file.txt ]")
  end
  set(:should_run_something, has_file.any?{|file| file == false})
end

task :run_something do
  on roles(:app) do
    if fetch(:should_run_something)
      # Run my command
    end
  end
end
after :check_something, :run_something


Visual Studio 2015 não mostra conteúdo de QString durante debug/depuração

Question: Estou utilizando o Visual Studio 2015 para desenvolver uma aplicação em Qt 5. Tudo funciona corretamente, mas quando tento depurar o código e inspecionar uma variável do tipo QString, o debug não mostra o conteúdo (texto) da variável, mas sim informações internas da alocação do objeto (tanto no tooltip quando eu passo o mouse sobre a variável, como na janela de Watch):

Há alguma forma de fazer o VS exibir o conteúdo textual da variável, tal como ele faz com strings ANSI e STL?
Comment: Programo em Lazarus, e nele temos um debug não muito eficiente, mas quando uma variável mostra um endereço, como no seu caso, usamos o operados ^ para mostrar o conteúdo do endereço. No seu caso, parece que o VS tem formas de tratar isso: http://stackoverflow.com/questions/22324166/visual-studio-2012-and-qt4-8-5-how-to-see-qstring-contents-in-debug-mode
Comment: Sim, verdade. De fato eu estava respondendo à minha própria pergunta. Só demorei porque o sistema não deixou eu postar o conteúdo que eu havia originalmente preparado (tava reclamando que era muito grande... droga... rs). Mas mesmo assim, obrigado pela ajuda. :)
Comment: Que khda heim? Eu gastei um tempão respondendo, e é duplicada (eu mesmo já havia colocado esse conteúdo aqui. rs). Sorry galera. Optei por não remover porque aqui há informação sobre a atualização para a versão 5.7 do Qt.
Answer: O Visual Studio tem um recurso chamado Visualização Customizada de Objetos Nativos (uma tradução livre do original em inglês Custom Views of Native Objects). No blog da Microsoft tem um exemplo bem bacana.

O arquivo natvis deve ser adicionado ao projeto, para uso particular,
  ou à pasta C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Packages\Debugger\Visualizers para uso geral.

Até algum tempo existia o Qt Visual Studio Add-in, que ao ser instalado fornecia uma série de facilidades para a utilização do Qt no VS, incluindo um arquivo natvis. Esse add-in está agora obsoleta (deprecated) mas você pode utilizar seu arquivo qt5.natvis (encontrado em alguns repositórios na Internet, tal como esse). Parte do arquivo é reproduzido abaixo, mas baixe-o da fonte original (ele é muito grande para caber todo aqui):
<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
    <Type Name="QPoint">
        <AlternativeType Name="QPointF"/>
        <DisplayString>{{ x = {xp}, y = {yp} }}</DisplayString>
        <Expand>
            <Item Name="[x]">xp</Item>
            <Item Name="[y]">yp</Item>
        </Expand>
    </Type>
    <Type Name="QRect">
        <DisplayString>{{ x = {x1}, y = {y1}, width = {x2 - x1 + 1}, height = {y2 - y1 + 1} }}</DisplayString>
        <Expand>
            <Item Name="[x]">x1</Item>
            <Item Name="[y]">y1</Item>
            <Item Name="[width]">x2 - x1 + 1</Item>
            <Item Name="[height]">y2 - y1 + 1</Item>
        </Expand>
    </Type>
    <Type Name="QRectF">
        <DisplayString>{{ x = {xp}, y = {yp}, width = {w}, height = {h} }}</DisplayString>
        <Expand>
            <Item Name="[x]">xp</Item>
            <Item Name="[y]">yp</Item>
            <Item Name="[width]">w</Item>
            <Item Name="[height]">h</Item>
        </Expand>
    </Type>
    <Type Name="QSize">
        <AlternativeType Name="QSizeF"/>
        <DisplayString>{{ width = {wd}, height = {ht} }}</DisplayString>
        <Expand>
            <Item Name="[width]">wd</Item>
            <Item Name="[height]">ht</Item>
        </Expand>
    </Type>
    <Type Name="QLine">
        <AlternativeType Name="QLineF"/>
        <DisplayString>{{ start point = {pt1}, end point = {pt2} }}</DisplayString>
        <Expand>
            <Synthetic Name="[start point]">
                <DisplayString>{pt1}</DisplayString>
                <Expand>
                    <ExpandedItem>pt1</ExpandedItem>
                </Expand>
            </Synthetic>
            <Synthetic Name="[end point]">
                <DisplayString>{pt2}</DisplayString>
                <Expand>
                    <ExpandedItem>pt2</ExpandedItem>
                </Expand>
            </Synthetic>
        </Expand>
    </Type>

    . . .

    <Type Name="QChar">
        <DisplayString>{ucs,c}</DisplayString>
        <StringView>ucs,c</StringView>
        <Expand>
            <Item Name="[latin 1]">ucs > 0xff ? '\0' : char(ucs),c</Item>
            <Item Name="[unicode]">ucs,c</Item>
        </Expand>
    </Type>
    <Type Name="QString">
        <DisplayString>{d->data,sub}</DisplayString>
        <StringView>d->data,sub</StringView>
        <Expand>
            <Item Name="[size]">d->size</Item>
            <Item Name="[referenced]">d->ref._q_value</Item>
            <ArrayItems>
                <Size>d->size</Size>
                <ValuePointer>(d->data),c</ValuePointer>
            </ArrayItems>
        </Expand>
    </Type>
    <Type Name="QT::QString">
        <DisplayString>{d->data,sub}</DisplayString>
        <StringView>d->data,sub</StringView>
        <Expand>
            <Item Name="[size]">d->size</Item>
            <Item Name="[referenced]">d->ref._q_value</Item>
            <ArrayItems>
                <Size>d->size</Size>
                <ValuePointer>(d->data),c</ValuePointer>
            </ArrayItems>
        </Expand>
    </Type>

    . . .

</AutoVisualizer>

A visualização de QString desse arquivo não funciona na versão 5.7 do Qt, mas há uma atualização que pode ser substituída (a fonte é do SO):
<Type Name="QString">
    <DisplayString IncludeView="nq">{((reinterpret_cast<unsigned short*>(d)) + d->offset / 2),sub}</DisplayString>
    <DisplayString ExcludeView="nq">"{((reinterpret_cast<unsigned short*>(d)) + d->offset / 2),sub}"</DisplayString>
    <StringView>((reinterpret_cast<unsigned short*>(d)) + d->offset / 2),sub</StringView>
    <Expand HideRawView="true">
        <Item ExcludeView="simple" Name="[size]">d->size</Item>
        <Item ExcludeView="simple" Name="[referenced]">d->ref.atomic._q_value</Item>
        <ArrayItems ExcludeView="simple">
            <Size>d->size</Size>
            <ValuePointer>((reinterpret_cast<unsigned short*>(d)) + d->offset / 2),c</ValuePointer>
        </ArrayItems>
    </Expand>
</Type>

Após salvar o arquivo natvis no diretório de visualizadores e reiniciar o VS, tem-se uma visualização apropriada de QString:


Extrair texto de uma string em python

Question: Estou com a seguinte dificuldade.
Tenho um df com varias colunas e uma delas é a Descrição. No meio desta descrição tenho o código do produto e gostaria de extrair essa informação para uma nova coluna. Por exemplo
Descrição.: "Esta é a descrição AA-123.456 do produto...."
Nova coluna "AA-123.456"
Alguém sabe como faço isso no python?
Comment: Expressão regular?
Comment: @mercadante tenta especificar melhor a sua pergunta, do jeito que está ninguém vai conseguir ter ajudar. Se puder coloque o código para vermos o que está acontecendo ou o que você precisa. Nessa descrição do seu problema dá a entender que usar expressões regulares ( regex ) vai te ajudar.
Answer: Caso os códigos tenham um padrão de formação conforme seu exemplo LL-NNN.NNN, onde L corresponde à uma letra uppercase e N corresponde à um número. Além disso, tanto o hífen quanto o ponto aparecem naquela posição específica. Você pode usar o método str.extract com a expressão regular ([A-Z]{2}-\d{3}\.\d{3})
Nota Em se tratando de expressões regulares, sempre existe uma mais abrangente.
Veja o exemplo abaixo:
Importando biblioteca
import pandas as pd

Criando dataframe de teste
df = pd.DataFrame({"cod": [1, 2, 3, 4], "descricao": ["Um texto qualquer AA-123.456 e segue com mais coisa", "Outro texto com o codigo BB-232.444 e vamos lá", "Por fim um produto CC-666.888 e fim", "um errado AA-12.3.456"]})

print(df)

   cod                                          descricao
0    1  Um texto qualquer AA-123.456 e segue com mais ...
1    2     Outro texto com o codigo BB-232.444 e vamos lá
2    3                Por fim um produto CC-666.888 e fim
3    4                              um errado AA-12.3.456

Criando nova coluna
df["novaColuna"] = df["descricao"].str.extract(r'([A-Z]{2}-\d{3}\.\d{3})')

print(df)

   cod                                          descricao  novaColuna
0    1  Um texto qualquer AA-123.456 e segue com mais ...  AA-123.456
1    2     Outro texto com o codigo BB-232.444 e vamos lá  BB-232.444
2    3                Por fim um produto CC-666.888 e fim  CC-666.888
3    4                              um errado AA-12.3.456         NaN

Repare que para o último item, não foi extraído o código, pois o mesmo não está no padrão citado.
Comment: Paulo, bom dia! Apliquei sua solução em meu DF e extraiu, porem tenho alguns código que são com 10 digitos outros são 11. Exemplo: SE-XXX-.XXX ou SE-XXX-XXXX  Para os que possuem 11 digitos ele não apresenta o ultimo. Se eu alterar de extract(r'([A-Z]{2}-\d{3}\.\d{3})') para extract(r'([A-Z]{2}-\d{3}\.\d{4})') ai todos os que possuem 10 digitos são apresentados como NaN.
Comment: Paulo, fiz somente este ajuste .str.extract(r'([A-Z]{2}-\d{3}\.\w+)') e funcionou. Muito Obrigado pela ajuda.
Comment: Neste caso, o ponto `.` irá pegar **qualquer** caracter ou seja `LL-NNN.NNN `. pegará o espaço no final; ou `LL-NNN.NNNX` pegará o `X`. Use `(r'([A-Z]{2}-\d{3}\.\d{3,4})')`. Assim, pegará 3 ou 4 dígitos no final...

Extrair texto de uma string em python


Find $\lim\limits_{x\to\pi/4} \frac{1-\tan(x)^2}{\sqrt{2}*\cos(x)-1}$ without using L'Hôpital's rule.

Question: Find $$\lim_{x\to\pi/4} \frac{1-\tan(x)^2}{\sqrt{2}\times \cos(x)-1}$$ without using L'Hôpital's rule.
I can solve it using L'Hôpital's rule, but is it possible to solve it without using L'Hôpital's rule?
Comment: You want to use the (limit) definition of derivative for $\tan$ and $\cos$ at $\frac{\pi}{4}$.
Comment: OP asked for "without l'Hospital's rule".
Comment: Shouldn't that be written $\tan^2 x?$
Comment: @OscarLanzi The definition of the derivative is not L'Hopital.
Answer: You can try the following:
\begin{align}
\frac{1-\tan^2({x})}{\sqrt{2} \cos{x}-1}\frac{\sqrt{2} \cos{x}+1}{ \sqrt{2} \cos{x}+1 }&=\frac{1-\frac{\sin^2{x}}{\cos^2{x}}}{2 \cos^2{x}-1} (\sqrt{2} \cos{x}+1)\\ &=\frac{\cos^2{x}-\sin^2{x}}{\cos^2{x} (2\cos^2{x}-\sin^2{x}-\cos^2{x}) }(\sqrt{2} \cos{x}+1)\\
&=\frac{\sqrt{2} \cos{x}+1}{\cos^2x}.
\end{align}
Now take the limit as usual.
Answer: Let $f(x) = \tan^2 x, g(x) = \sqrt 2 \cos x.$ The expression equals
$$-\frac{f(x) - f(\pi/4)}{g(x) - g(\pi/4)} = -\frac{(f(x) - f(\pi/4))/(x-\pi/4)}{(g(x) - g(\pi/4))/(x-\pi/4)} .$$
As $x\to \pi/4,$ the last expression $\to -f'(\pi/4)/g'(\pi/4)$ by definition of the derivative, which is a simple computation. (No L'Hopital was used here.)
Answer: Change the variable to $y=x-\frac{\pi}{2}$. then the limit is
$$\frac{-4\sin y \cos y}{(\cos y-\sin y)^2 (\cos y-\sin y -1)}$$
Now both $\cos y$ and $(\cos y-\sin y)^2$ have a limit of $1$ so we are reduced to
$$\frac{-4\sin y}{\cos y-\sin y -1}$$
Now $\frac{\sin y}{y}\to 1$ so we need to find the limit of
$$\frac{-4 y}{\cos y-\sin y -1}$$
Now $$\frac{\cos y-\sin y -1}{y}=y\frac{\cos y-1}{y^2}-\frac{\sin y}{y}\rightarrow -1$$
Thus the limit (assuming I have made no error) is $4$.
Answer: Writing $1=\tan\dfrac\pi4,\sqrt2=\sec\dfrac\pi4$
replacing $\dfrac\pi4=2A,x=2y$
$$\lim_{y\to A}\dfrac{\tan^22A-\tan^22y}{\sec2A\cos2y-1}=\cos2A\cdot\lim_{y\to A}(\tan2A+\tan2y)\cdot\lim_{y\to A}\dfrac{\tan2A-\tan2y}{\cos2y-\cos2A}$$
Now $\lim_{y\to A}\dfrac{\tan2A-\tan2y}{\cos2y-\cos2A}$
$=\lim_{y\to A}\dfrac{\sin(2A-2y)}{2\cos2A\cos2y\sin(A+y)\sin(A-y)}$
$=\lim_{y\to A}\dfrac{2\sin(A-y)\cos(A-y)}{2\cos2A\cos2y\sin(A+y)\sin(A-y)}=?$
Answer: Just another way to do it.
Let $x=y+\frac \pi 4$, expand and simplify. You should get $$\lim_{x\to\pi/4} \frac{1-\tan^2(x)}{\sqrt{2}\times \cos(x)-1}=\lim_{y\to 0}\frac{2 (\cos(y)-\sin (y)+1)}{(\cos (y)-\sin (y))^2}$$ which looks very simple.


Proving at least 99 pairwise sums of the reals are non-negative

Question: Suppose, one hundred real numbers are given and their sum is 0.Then how can I prove that at least 99 of the pairwise sums of these hundred numbers are non-negative?
I tried this:
Let the real numbers be $a_i$,$1\leq i\leq100$.
By the given condition, $a_1+a_2+\dots +a_{100}=0$.Suppose for the sake of contradiction, that at most 98 of the pairwise sums of these given reals are non-negative.I just tried to examine the case when exactly 98 of them are non-negative.
I labelled the sums $S_1$,$S_2,\dots S_{4950}$,WLOG assume that sums $S_1,S_2,\dots S_{4852}$ are negative, the rest are non-negative.
$$S_1+S_2+\dots +S_{4950}=99(\sum_{i=1}^na_i)=0$$
Case I: $S_{4853}+a_{4854}+\dots +a_{4950}=0$.That simply means that $S_1+S_2+\dots +S_{4852}=0$.But, by the given condition, $S_1+S_2+\dots +S_{4852}<0$,a contradiction.After that, I am not able to make any progress.
Can anyone please suggest a more efficient method to solve this problem.I feel this approach will involve enormous case work.
Comment: More of a sketch than a proof, but consider the largest element. The pairwise sum of this with the others will yield 99 positive sums,  unless there is an element even more negative than the maximum is positive. But if this is the case, then the average of the other 98 will be positive,  so there will be more positive sums there.
Answer: Without loss of generality, $a_1\ge a_2\ge \ldots\ge a_{100}$.
From $$0=(a_1+\ldots+a_{50})+(a_{51}+\ldots+a_{100})\le 50a_1+50a_{51},$$ we conclude $a_1+a_{51}\ge0$, hence we have $50$ nonnegative sums $$\tag1 a_1+a_k,\ 2\le k\le 51$$ involving $a_1$.
We may assume that $a_1+a_{100}<0$ as otherwise $(1)$ can be extended to $2\le k\le 100$ and we are done. Therefore $a_2+\ldots+a_{99}=-(a_1+a_{100})>0$ and from
$$0< (a_2+\ldots+a_{50})+(a_{51}+\ldots a_{99})\le 49a_2+49a_{51},$$
we conclude $a_2+a_{51}> 0$, hence we have another $49$ nonnegative (in fact positive) sums
$$\tag2a_2+a_k,\ 3\le k\le 51$$
and together with $(1)$ this produces the required $99$ nonnegative sums.

Warning: Contrary to what it may look like, this method will not guarantee us $50+49+48+\ldots$ nonnegative sums as the first step from $(1)$ to $(2)$ comes into play only if $a_1+a_{100}<0$. In fact, $a_1=99, a_2=\ldots=a_{100}=-1$ shows that $99$ cannot be improved.


Why is is_dir() called over 4000 times per request?

Question: I installed XHPROF to check how I could improve my code. I noticed that Drupal calls is_dir() over 4000 times on nearly every request, and this takes about 800ms.

Why does this happen? Is there any way to speed that up?
I have already disabled the automatic register rebuilt, but it didn't decrease the number of times is_dir() is called.
Comment: And this is how Drupal recognizes new modules, themes and libraries in different directories!
Comment: What page are you looking at? Seems like it's caused by the file_scan_directory. Bet it's during cron or some administration page.
Answer: When you uninstall a module, you need to first disable it from admin/modules and then uninstall it from admin/modules/uninstall. The same goes for themes, which should be first disabled from admin/appearance.
If you, for example, delete the module without disabling the module, Drupal will continue to search for the module in the file system, which can result, among other errors, in the issue you are experiencing.
See also Avoid re-scanning module directory when multiple modules are missing.
To understand which module has been deleted without first uninstalling it, you will need to run the SELECT name, filename FROM system WHERE status = 1; query and compare that list of module with the modules present on the site directory. All the enabled modules and themes should be present.
There's also a hook implementation Martin_Dresden posted on Drupal 7 abysmally slow: file_scan_directory called > 1000 times per page load that may help with debugging. I provide here a slightly modified version.
function MYMODULE_init() {
  $startingtime = microtime(true);
  $o = '
Checking for dead modules ...
';
  $result = db_select('system')
    ->fields('system', array('filename'))
    ->condition('status', '1', '=')
    ->execute();
  $n = 1;
  $m = 0;

  foreach ($result as $row) {
    $path = DRUPAL_ROOT . '/' . $row->filename;

    if (!file_exists($path)) {
      $o .= "#$n $path
";
      $m++;
    }

    $n++;
  }

  $timedif =  round(microtime(true) - $startingtime,3);
  $o .= "Total of $n active modules registered in database. $m dead entries found.
";
  $o .= 'Query Time: ' . $timedif . ' seconds';

  drupal_set_message($o);
}

Comment: Is there a way to determine which row in `{system}` is the problem?
Comment: @MPD answer updated with possible solution there.
Comment: If I disable a module but don't uninstall it, are there any disadvantages in this case compared to also uninstalling it?
Comment: The module will have a row in system table! Un installation wipes everything related to the module in db and in file system if 'un install' routine is properly written!


Add html to wrap views programaticly

Question: I need to wrap field in views. I use views with module Responsive grid and have this html.

Responsive html

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ultrices sit amet diam eu accumsan.

I want to have this html

Responsive html

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin ultrices sit amet diam eu accumsan.

I know that i should use this function hook_preprocess_views_view, hook_preprocess_views_view_fields or hook_preprocess_views_view_field but i don't know how to do it correctly.
So how can i have this html without creating *tpl.php file
Answer: It can be done in the views admin interface in the next way:

Exclude existing fields from display
Add new field Global: Custom text
Display new fields in Custom text filed using tokens

See example

Add html to wrap views programaticly


There is data for the field - On uninstalling module

Question: Given I have a module that defines a new field on an entity. How can I delete that data on uninstalling? There is a requirement:

There is data for the field X on entity type Y

which means I cannot delete the data on the hook_uninstall since it cannot be called.
Comment: Your module (when installing) adding a base field or a bundle field?
Answer: This is a known limitation to Drupals Core and this finally gets resolved for Drupal 8.5.x, see this issue:
https://www.drupal.org/project/drupal/issues/2282119
But for versions earlier there is an option to workaround this, by creating a form that handles the cleaning of added data to make the uninstall validation pass. This is a UI solution but you still need to add a not somewhere that users know how to find the form. See how the Flag module handled it:
https://www.drupal.org/node/2409673
There are other options like creating a drush command, but what you basically need to do is to clean the added data from the database to make the validation for uninstall pass and allow users to uninstall the module.


Scala: Overriding methods from java interface

Question: I'm trying to implement a generic java interface in scala. I have looked at:
How do I extend Java interface containing generic methods in Scala?
And Scala: Overriding Generic Java Methods II
But still I could not find an answer. Here's the method signature from Spring web:
T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException;

I tried the following in scala:
 @throws(classOf[IOException])
  @throws(classOf[HttpMessageNotReadableException])
  override def read[T](clazz : Class[_ <: T], inputMessage : HttpInputMessage) : T ={
  }

But I get an error saying that this method overrides nothing. If I erase the type by doing:
override def read(clazz : Class[_], inputMessage : HttpInputMessage) : AnyRef ={

It marks the method as being overwritten. My question is how can I keep type safety here and force it to override the interface method?
Regards
EDIT
The spring interface:
public interface HttpMessageConverter<T> {

T read(Class<? extends T> clazz,
       HttpInputMessage inputMessage)
       throws IOException,
              HttpMessageNotReadableException
}

Comment: Could you provide a link for the source code of the Spring Web where the method you are trying to override/implement resides?
Answer: I think the problem is likely to be that you have added a type parameter to the read method, rather than using the type parameter from your class declaration:
class MyImpl[T] extends JavaInterface[T] {

  override def read(clazz: Class[_ <: T], ... )

}

If we rename your T to U it becomes clearer what you have done:
class MyImpl[T] extends JavaInterface[T] {

  /** U is not T */
  override def read[U](clazz: Class[_ <: U], ... )

}

You might also try and sing "U is not T" to the tune of REM's Losing My Religion to hammer the point home.
Answer: In java you have parameterilized interface, but in scala you try to parameterize method.


Dynamic Typescript object properties

Question: I would like to dynamically extend a type so that I can do the following:
interface SurveyQuestion {
  propertyName: string,
  propertyType: Object,
}

const questions: SurveyQuestion[] = [
  { propertyName: "isNewUser", propertyType: typeof Boolean },
  { propertyName: "satisfactionScore", propertyType: typeof Number },
  { propertyName: "comments", propertyType: typeof String },
];

type SurveyWithQuestions = {
  date: Date;
  username: string;
}

let survey1: SurveyWithQuestions = {
  date: new Date("1/1/2023"),
  username: "johndoe",
  isNewUser: true,
  satisfactionScore: 5,
  comments: "happy user"
};

...so that new questions added will not error and will allow code completion for them.
This gets close using generics and object keys.  But I couldn't modify it properly to iterate questions.
Comment: `typeof Boolean` and `typeof Number` and `typeof String` are almost certainly not what you want; those are just the string `"function"`.  And `Object` is also almost certainly not what you want, since that matches any non-nullish value, including the string `"function"`, which is why that's not an error.  Could you please [edit] the code to be a [mre] that actually demonstrates what you're trying to do, at least the runtime code? Then we can help you give it typings.
Comment: Why is this tagged "typescript-eslint"? Do you have some linter config that's relevant here?  If so, what is it?  If not, maybe untag?
Comment: *Perhaps* [this approach](https://tsplay.dev/NBJlbN) is what you want, but I had to make a lot of guesses and I'm not sure how you expect to use it (where and when are you going to "add" new questions?  How are you really going to encode what types the property types are? etc).  If that works for you I could write up an answer explaining; otherwise, what am I missing?
Comment: @jcalz Yes, that is exactly how I expect to use it; adding new SurveyQuestions to the array automatically adds those strongly-typed properties to the SurveyWithQuestions object.  That way I can use code completion and not have to keep property names in multiple places.  Thanks for your TS wizardry!
Answer: I'm going to presume that the propertyType property will be a string that describes the type, like "boolean" or "date".  If so, then for this to work you'll need to keep a type that maps from these strings to the TypeScript types they represent:
interface TypeMap {
    boolean: boolean;
    number: number;
    string: string;
    date: Date;
    // add any name-to-type mappings you need here
}

and then we can say that your SurveyQuestion type needs to use on of the keys of TypeMap as propertyType:
interface SurveyQuestion {
    propertyName: string,
    propertyType: keyof TypeMap,
}

When you define question, you don't want to annotate it as SurveyQuestion[]. You need the compiler to keep track of the particular propertyName and propertyType values inside the initializing array literal, but if you annotate the variable property as SurveyQuestion[] the compiler will forget all those details.   So you want to write const questions = ... and not const questions: SurveyQuestion[] = ....
And even that's not quite enough; the compiler won't realize you care about the literal types of those property values unless you tell it so.  Normally a value like [{a: "abc", x: "xyz"}, {a: "def", x: "uvw"}] will be inferred as type Array<{a: string, x: string}>, even without an annotation.  It's more common for people to want a type like that then something very specific about "abc" and "xyz".  But you want the most specific type possible, so you can do so with a const assertion:
const questions = [
    { propertyName: "isNewUser", propertyType: "boolean" },
    { propertyName: "satisfactionScore", propertyType: "number" },
    { propretyName: "comments", propertyType: "string" },
] as const;

And IntelliSense shows you that the type of questions is:
/* const questions: readonly [{
    readonly propertyName: "isNewUser";
    readonly propertyType: "boolean";
}, {
    readonly propertyName: "satisfactionScore";
    readonly propertyType: "number";
}, {
    readonly propretyName: "comments";
    readonly propertyType: "string";
}] */

So that's enough information to work with now, hooray!

But note that we haven't used SurveyQuestion at all.  The compiler didn't realize that we wanted SurveyQuestions and so it didn't catch that I wrote propretyName instead of propertyName in there.  Oops!
To fix that, you can use the new satisfies operator to have the compiler check that your initializer is an array of SurveyQuestions without widening the variable to that type:
const questions = [
    { propertyName: "isNewUser", propertyType: "boolean" },
    { propertyName: "satisfactionScore", propertyType: "number" },
    { propretyName: "comments", propertyType: "string" }, // error!
//    ~~~~~~~~~~~~~~~~~~~~~~~ <-- Did you mean to write 'propertyName'?
] as const satisfies ReadonlyArray<SurveyQuestion>;

Now the compiler has caught the error and we can fix it:
const questions = [
    { propertyName: "isNewUser", propertyType: "boolean" },
    { propertyName: "satisfactionScore", propertyType: "number" },
    { propertyName: "comments", propertyType: "string" },
    // { propertyName: "anotherProp", propertyType: "date" }
] as const satisfies ReadonlyArray<SurveyQuestion>;

Okay, great.

Now all  we have to do is define SurveyWithQuestions in terms of questions.  First we can get the type of questions using the TypeScript typeof type operator, and index into it with number to get the union if its element types:
type QuestionType = typeof questions[number];

/* type QuestionType = {
    readonly propertyName: "isNewUser";
    readonly propertyType: "boolean";
} | {
    readonly propertyName: "satisfactionScore";
    readonly propertyType: "number";
} | {
    readonly propertyName: "comments";
    readonly propertyType: "string";
} */

And now we can iterate over that union and remap it to object properties:
type ResponseFormat = {
    [T in QuestionType as T["propertyName"]]:
    TypeMap[T["propertyType"]]
}

/* type ResponseFormat = {
    isNewUser: boolean;
    satisfactionScore: number;
    comments: string;
} */

And finally, we can extend it with any other "static" properties to get SurveyQuestions:
interface SurveyWithQuestions extends ResponseFormat {
    date: Date;
    username: string;
}

Let's test it out:
let survey1: SurveyWithQuestions = {
    date: new Date("1/1/2023"),
    username: "johndoe",
    isNewUser: true,
    satisfactionScore: 5,
    comments: "happy user",
}; // okay

So that works as desired.  Let's see what happens if we add a line to our questions definition:
const questions = [
    { propertyName: "isNewUser", propertyType: "boolean" },
    { propertyName: "satisfactionScore", propertyType: "number" },
    { propertyName: "comments", propertyType: "string" },
    { propertyName: "dateOfBirth", propertyType: "date" } // <-- add this
] as const satisfies ReadonlyArray<SurveyQuestion>;

let survey1: SurveyWithQuestions = { // error!
    date: new Date("1/1/2023"),
    username: "johndoe",
    isNewUser: true,
    satisfactionScore: 5,
    comments: "happy user",
};

// Property 'dateOfBirth' is missing in type ...
// but required in type 'SurveyWithQuestions'.
So the compiler now expects a dateOfBirth property to exist.  Let's give it one:
let survey1: SurveyWithQuestions = {
    date: new Date("1/1/2023"),
    username: "johndoe",
    isNewUser: true,
    satisfactionScore: 5,
    comments: "happy user",
    dateOfBirth: "yesterday" // error!
    // Type 'string' is not assignable to type 'Date'.
};

Oops, wrong type:
let survey1: SurveyWithQuestions = {
    date: new Date("1/1/2023"),
    username: "johndoe",
    isNewUser: true,
    satisfactionScore: 5,
    comments: "happy user",
    dateOfBirth: new Date(Date.now() - 8.64e7)
}; // okay

Looks good!
Playground link to code

Dynamic Typescript object properties


Accordion plus-minus icons on open/close - Vue2

Question: Changing icons on open/close accordion states.
Template:

Quesstion?

Data:
data () {
 return {
   isActive: false
 }
}

It does work, when i click on accordion header, my icon changes from plus to minus, but if i have more that one question, they all will be changing plus to minus, and vice versa, because they're sharing the same data isActive. How to separate each element, so only clicked item would have icons changed.
Answer: To create separate state for your questions I would simply make a component out of your question. This way every question has its own state.
Of course that leads to the problem of every component having the same template, so you can make a component slot to pass in the unique content for each question. Optionally you can pass the unique content into a question component with props if the data is small enough.