testing my REPOSITORY layer with DBUnit/Junit, should I manually build scheme or automate it? what's the advantages?

Question: I am thinking on how to design my unit-tests for my java based-repositories and encountering design problems:
Lets assume I have a Consumer table with data related to my consumer:
{ ID, Name, Phone }
And my ConsumerRepository extends BaseRepository which extends JPA repo and supports findByPhone, findByName, findAll queries and save option.
I'm using H2 in-memo DB and DBUnit for those tests, all configured and running and was thinking about this:

When launching data to my in-memory DB, should I be configuring the data with the ConsumerTestData.xml (DBUnit) and manually adding the Consumer data for each test for e.g:
<dataset>
<CONSUMER CONSUMER_ID="1" FIRST_NAME="Elvis" LAST_NAME="Presley" PHONE="+972123456789" EMAIL="email@example.com" CREATION_DATE="2017-08-29"/>
<CONSUMER CONSUMER_ID="2" FIRST_NAME="Bob" LAST_NAME="Dylan" PHONE="+972123456780" EMAIL="email@example.com" CREATION_DATE="2017-08-29"/>
<CONSUMER CONSUMER_ID="3" FIRST_NAME="Lady" LAST_NAME="Gaga" PHONE="+972123456781" EMAIL="firstname.lastname@example.com" CREATION_DATE="2017-08-29"/>
</dataset>

or should I automate it? for e.g:
@Test
public void findByPhone(){
    ConsumerEntity consumerEntity = ConsumerUtil.createRandomConsumer();
    ConsumerEntity savedConsumerEntity = consumerRepository.save(consumerEntity);
    assertThat(consumerRepository.findByPhone(savedConsumerEntity.getPhone()).isEqualTo(savedConsumerEntity.getPhone());
}

While my createRandomConsumer generates random data.
Pros:
I think automating would be much more generic and handy as if ConsumerEntity might change or any code changes next - i will not have to change my .xml file and just be able to add things to the TestEntity function.
Cons:
Creating new objects and saving to in-memo DB might be more difficult if contains any constraints in the DB scheme.

Should I use DBUnit at all? if automating it - why should I use DBUnit? is it better just to use JUnit (Rolling back the data after each test and just adding the data I need for the test automatically as in the example above?)
If chose to use DBUnit for this - and manually added - what are the advantages of such thing? why is it better than using simple JUnit with Spring?

Thanks!
Answer: 1) Testing with only random or runtime generated fixture is not fine.
It doesn't make tests reproducible, so make them harder to debug if fails and it doesn't make tests document the code either.
Besides, fixtures with explicit data reduces side effects as the data generation may introduce.
Are you sure that the generated data respect the requirements ?
Are you sure that your generate tool works as expected ?
Have you tested it ?
And so for...
Finding required edge cases is fine but inventing not required edge cases means your tests will change your requirements.
And you don't want that.
If you identified all specific cases and you want to generate some data because you deem that you have too many combinations (dozen of input cases for example), of course generating fixture by relying on the requirements is nice.
Otherwise, don't make it as it seems an overhead.
2) DBUnit, it is a choice.
Before I used it. Now, I stopped. It has some strengths but it is cumbersome and its maintenance/improvements are very light.
Recently, I tried DbSetup from JBNizet (a SO member).
It is rather a fine API to insert Data in a database from Java code : simple and straight usable.
For example to insert data in DB, An Operation can be defined as :
Operation consumerInserts = sequenceOf(
    insertInto("CONSUMER")
        .columns("ID", "FIRST_NAME", "LAST_NAME")
        .values(1, "Elvis", "Presley")
        .values(2, "Lady", "Gaga")
        .values(3, "Bob", "Dylan")
        .build();
)

3) So, nothing to add.
Comment: I am not an expert in this area, but the answer reads fine to me. For the record: sometimes "random" testing is fine, for example when thinking about quickcheck ( https://en.wikipedia.org/wiki/QuickCheck ) . The key element there is to know your random *seeds*, so that you are able to repro a failed test easily later on.
Comment: Thanks for your'e comment- 1.about the dynamic generated fixture- what happens if I change the ConsumerEntity fields later on? If I would like to have a last-name attribute as well, I would have to del the whole data and make it again? 2. Aren't randomness will add more features to my test? it will also include edge-cases as it will generate lots of kinds of data- or it is not what I want to test but test the DATA_ACCESS and not the data itself? 3. if so - do I need also to test CRUD operations? are like the CRUD testing operations are a must for any repository check? Ty
Comment: 1) You have to delete nothing. You have just to change your fixture dataset to add this field. 2) You implement according to a requirement, not randomness data. Inserted data have to be validated according to a specific format and not accept anything. Edge cases and acceptable cases have to be identified. Randomness will not do that for you. 3) What you want to test is not the CRUD repository. It relies on JPA/Hibernate and Spring as wrapper and you know that these are OK. What you want to test is your entities mapping and to test it, you can of course rely on in CRUD operations.
Comment: @Downvoter please respect people that take time to answer and comment your downvote.
Answer: You seem to be asking 2 questions: whether to use DBUnit and whether to use randomization.
As for DBUnit

It adds extra steps and extra maintenance costs. If you already have code to save entities (via XxxRepository), then there is no reason to introduce yet additional tool.
This is true not only for DBUnit but for any tool that duplicates existing persistence logic.
Instead you can just create an object instance, fill all the fields and save with the repository. This makes refactoring much easier.

As for test randomization

I think your test looks very good. With randomization you can cover more cases with less tests, find tricky cases that you couldn't think of yourself, isolate your tests easily (e.g. generate unique username instead of keeping track of them somewhere), etc.
As per cons: good randomziation (and good tests in general) require a good command of OOP, so not everyone can easily use it when the project grows big. Also tests start failing from time to time because they are written in haste and not every possibility is considered. To catch such cases you should run the tests locally many times (which sometimes people forget). Good news: IntelliJ can repeat tests N times for JUnit (for TestNG there is an annotation).

In general you should think more when you write randomized tests. But if written properly they provide better coverage and lower maintenance overhead. If you're interested in different randomization techniques, check this out.
Comment: Thanks. another question related is: do I have to "save" each time data to the in-memo DB? that what will happen if I use the randomization idea, so test becomes also related with save method. but more generic, more easy to refactor and easy to control. what do you think?
Comment: Are you asking if you should use `save()` method or some other way to insert data? I think I stated this in the answer - that yes, you shouldn't duplicate code and should re-use the existing `save()`.


Redirect to file as well as to STDOUT in bash

Question: I've a long bash script with multiple echo statements.
I had a requirement to redirect bash script's output to a file without using redirection from bash shell. I could accomplish that by doing:
exec 1>>/tmp/output

How do I do something like both redirecting to a file and not stopping to output in STDOUT?
I don't want to edit each and every echo statement to accomplish it.
Answer: Use tee
your_script | tee /tmp/output

Comment: I specifically asked for `I had a requirement to redirect bash script's output to a file without using redirection from bash shell.` Anyways, I got it on how to do it but can't delete the question now. `exec > >(tee file)`
Comment: Your requirement is confusing.  Piping is arguably different from redirection.  Anyway, glad you got it worked out.
Answer: Got the help from #bash IRC.
exec > >(tee file)


Set c++14 standard usage for nvcc in MSVC 2017

Question: Stupid question, but I can not understand how to set up c++14 standard usage for nvcc in MSVS (MSVC). I tried to add "-std=c++14" in the Command Line and "/std:c++14" in "Additional Compiler Options", but got
nvcc warning : The -std=c++14 flag is not supported with the configured host compiler. Flag will be ignored.
How to correctly set up this option?
Comment: It's quite possible.  That seems like a different question.
Comment: There is no need to use it on the windows platform.  Support for it is automatically enabled (in CUDA 9.x with VS2017)
Comment: @Robert Crovella, so, Is this correct that compilation errors in pair "Blaze+Thrust" are connected with Blaze and nvcc incompability? Because I can write simple code which is compiled by cl.exe fine, but failed to be compiled with nvcc (without any row of cuda code!)
Comment: @Robert Crovella, It's so strange, really.
Answer: On windows platforms, the support for e.g. C++11 and C++14 is dictated by the platform.  It is already enabled (C++14 requires CUDA 9.x or later, C++11 was supported with earlier versions of CUDA such as CUDA 7.5).
This means that the support will be a function of which CUDA version and which Visual Studio version you are using, and there are no switches to pass to enable it.  Attempting to use a switch such as -std=c++11 or -std=c++14 will be met with a compile warning on windows.


How clean git repository with commit which not in work tree

Question: I cleaned the Git repository (Bitbucket cloud) with bfg, but the last commit remained uncleaned (as written in the bfg documentation: By default the BFG doesn't modify the contents of your latest commit on your master (or 'HEAD') branch, even though it will clean all the commits before it.).
However, I didn't see it and wanted to run git gc in a Bitbucket.
For this I did "git reset --hard HEAD" and rolled back to it then "git push --force".
But repository size increased?!
Now I have this commit with the old history left in the repository, and bfg cannot clean it, what should I do?
How can I remove it, since it is no longer attached to the working tree?
Answer: You can tell BFG to change the last commit too with the --no-blob-protection flag. *(This is from the BFG-Repo-Cleander documentation).
Alternatively, you can create a new commit that removes the bad file and then run BFG normally.
Comment: I tried to do so, but the commit is no longer in the working tree and the bfg does not see it
Answer: Try again, this time using newren/git-filter-repo, which will replace BFG and git filter-branch
As mentioned in its documentation:

[there is] an extra steps to delete the other tags and do another gc are still required to clean out the old objects and avoid mixing new and old history before pushing somewhere

git filter-repo does avoid confusing users (and prevent accidental re-pushing of old stuff) due to mixing old repo and rewritten repo together.

Note: on the server side (ie, where you are pushing to), a git gc needs to be run, which is done regularly but not immediately.
That is the case for GitHub, as well as BitBucket.
See Atlassian documentation "How to perform a manual garbage collection on a repository"

Bitbucket implements its own garbage collection logic without relying on git gc anymore (this is achieved by setting the [gc] auto = 0 on all repositories).
  When a fork is created, the pruneexpire=never is added to the git configuration and this is removed when the last fork is deleted.

As mentioned here:

BitBucket will run git gc themselves in response to doing git reset --hard HEAD~1 (which discards last commit) followed by git push -f.

So in your case:
git commit --allow-empty -m "empty commit"
git push

git reflog expire --expire-unreachable="30m" --all
git prune --expire="30m" -v
git gc --prune="30m"
git reset --hard HEAD~1
git push -f

And a git gc should be done on BitBucket side!
Answer: I wrote in bitbucket support, they ran the script "git gc" on server and the old story was cleaned
Comment: Bitbucket support could have some answers about why their own process did not trigger a `git gc`.
Comment: You should be able to trigger a `git gc` on BitBucket side (without having to contact them). See [my edited answer](https://stackoverflow.com/a/58570961/6309).
Comment: I know, I did it, it didn't help me


Migrating from webstorm to Visual Studio 2015 - importing files from subversion using ankhsvn

Question: I have been using the Webstorm trial version for a month and it has expired, so now I am considering using Visual Studio.
However, I have come across a stumbling block using ankhsvn, which is that I cannot figure out how to "import" files from existing files in subversion and add them to a project. Add to Subversion simply adds a new folder to the repo and I cannot see the existing files in the project explorer.
Is there a newbie friendly tutorial on how to import files from an existing svn repo to a solution in local space?
Answer: D'oh! Turns out I just needed to use Tortoise to check out the files, then create a blank solution in the same folder as the check out (this is important or ankhsvn won't play nice), and then add existing website to the project.


Prove a limit, going back to definition

Question: I have to use only the definition of limits (ie I can't use algebra of limits) to prove the following:
$$\lim_{x \to 2} x^2 = 4$$
I can't think of what to use as an arbitrary constant, or how to start this, thanks.
full proofs would be brilliant!
Comment: https://math.berkeley.edu/~btsou/limit%20x%5E2.pdf
Comment: Please provide more context, and show some evidence that you really tried to solve the problem (and what you tried). This will help you receive answers that are most appropriate for your level.
Comment: Possible Duplicate of: http://math.stackexchange.com/questions/330297/prove-that-lim-x-to-2x2-4-using-epsilon-delta-definition
Answer: You want to make
$$
|x^2 - 4| = |x-2||x+2|
$$
small, and $|x-2|$ is allowed to be small itself. So, you just need to restrain the domain of $x$ such as
$$
|x+2|
$$
is not too big. Say $|x+2| < 5$. What are the implications for the interval of $x$? can $x$ be close to 2 in this interval? What is then the choice of $\delta$ in terms of $\epsilon$?
Can you take it from here?
Answer: Use h method
First substitute x with $2+h$ where $h \to 0^+$ ( is a small positive quantity)
$$\lim_{h \to 0} (h+2)^2$$
Then expanding it comes out to be.
$$ \lim_{h \to 0}(4+4h+h^2) $$
Then as $h$ is very small ignore $4h$ and $h^2$
we get,
$$\lim_{x \to 2} x^2 = \lim_{h \to 0}(4+4h+h^2)= 4$$
Comment: I recommend using this method in future applications also. Don't treat this as a solution but as a good approach for most questions (it's very basic too)
Comment: although this works it doesnt use the definition of limits!
Comment: I didn't use algebra of limits and this method is purely based on the definition of limits

Prove a limit, going back to definition


Do 3D ear impression scanners yield higher quality custom flat-response attenuators compared to traditional ear impression techniques (eg, spleading)?

Question: I am getting a new pairs of flat-response attenuators (a.k.a., "musician earplugs"). Do 3D ear impression scanners yield higher quality custom-molded flat-response attenuators compared to traditional ear impression techniques (e.g., spleading (source: Westone Earpiece Guide 2022))?
Comment: I'm voting to close this question because it's not about music practice or theory.
Comment: @PiedPiper it's a question about music equipment, which is on-topic.
Comment: To me this is borderline leaning towards off-topic, but I'll let the community decide. The reason is we don't allow questions around generic sound equipment outside of the practice of music. Another analogus example is if you wanted answers on a home audio system amp or speakers while there are other amp and speaker questions here, they fall outside of our general expertise. See https://music.meta.stackexchange.com/a/831/7222.
Comment: @Dom Thanks, I see, I'd argue that flat-response attenuators are typically purchased by music practitioners, whereas home audio system amp or speakers are typically purchased by anyone.
Comment: Something that definitely is used primarily by musicians are moulded in-ear monitors. Perhaps the question would be less controversial if it included those.
Comment: A question about something used by musicians to protect their hearing seems legitimate to me. The problem is can anyone provide a knowledgeable answer here? It seems to me like someone would have to have experience with both types of attenuators to do that.
Comment: As far as I can tell it's not even different types of attenuators but different way to create the ear model they are based on. My experience is that there's nothing left to be improved in traditionally molded set, but the process itself was slow and uncomfortable.
Comment: @ojs thanks, yes, it's the same type of attenuators, just different way to create the ear impression.
Answer: 3D scanning may produce a more accurate mold of the human ear but the quality of an in-ear impression (spleading) depends on the skill of the person.
3D scanning is less messy and more comfortable, but I have found no practical (performance) difference in the quality of the attenuators produced by the two techniques. The quality of the lab making the attenuators is a greater consideration.
So go with the method that is most economical and practical for you.
Comment: @Downvoter: Why the downvote?


Como usar uma variável JavaScript em uma pagina php via ajax

Question: Basicamente eu preciso usar uma variavel JavaScript em uma php para depois registrar, no banco. Tenho um botao <button id="btnTestar">TESTE</button> que leva ate a pagina carrinho.php.
Na pagina carrinho.php eu quero receber a variavel.
$teste = $_POST['teste'];

codigo ajax

$(document).ready(function () {
$("#btnTestar").click(function(){
    var teste = "testando";
        $.ajax({
          type: "POST",
          url: "carrinho.php",
          data:{'teste':teste},
          success: success,
          dataType: dataType
        });

    });
});

Eu não sei oque está errado pois nunca usei ajax antes então estou na duvida.
o erro que aparece na pagina php é essseNotice: Undefined index: teste
Comment: Tenta passar `teste: teste` ao invés de `'teste': teste`
Comment: Tente modificar no AJAX: data: teste
Answer: Ao meu ver não faz sentido você redirecionar para mesma página que está enviando os dados via ajax.
Se fosse assim basta fazer um formulário básico com o seguinte código:
<form action="carrinho.php" method="post">
  <input name="teste" type="text" value="testando">
  <input type="submit">
</form>

A vantagem de utilizar o ajax é não precisar carregar a página novamente ou não ser direcionado para uma outra página.
O que nós podemos fazer é trazer os dados da outra página com o ajax.
Neste código abaixo é possível enviar a variável teste e receber o retorno pelo ajax, esse retorno será inserido na div com o id result.
No código PHP será lançada uma exceção caso o valor seja em branco.
Nesse código você pode apagar o valor do input para testar qualquer outro valor.
JavaScript:
$(document).ready(function () {
  $("#btnTestar").click(function(){
    $.ajax({
      type: "POST",
      url: 'carrinho.php',
      data: {
        teste: $('#teste').val()
      },
      success: function (result) {
        $('#result').html(result);
      },
      error: function (result) {
        $('#result').html(result);
      }
    });
  });
});

HTML:
<input id="teste" type="text" value="testando">
<button id="btnTestar">Teste</button>

PHP:
$teste = $_POST['teste'];
if ($teste == '') {
    throw new Exception('Recebido valor em branco!');
} else {
    echo "Valor recebido: " . $teste;
}


Where are the Java HttpSession attributes stored?

Question: Are the objects serialized and sent to the user and back on each connection (stored in cookies) ?
Or are they stored in the server heap and the cookie is only a very small identifier ?
Any information about this topic would be helpful.
Thank you
Comment: Related: http://stackoverflow.com/questions/3106452/java-servlet-instantiation-and-session-variables/3106909#3106909
Answer: You got it on the second guess.
The cookie contains a JSESSIONID. That id is used to look up the user's HttpSession in a map that the server maintains. At least this is the most common way. There are more intricate ways that the server can implement this, but shuttling the entire state back an forth in a cookie isn't one of them.
This has some implications. First, if the server goes down, you lose session state. Second, if you have a server cluster, you need to get the user connected to the same server each time, or they will lose their session between subsequent requests. Lastly, session hijacking becomes a possibility if someone finds a way to copy someone else's JSESSIONID and replace theirs with it.
Comment: Your last paragraph is not entirely accurate.  Popular Java web servers (at least Tomcat and JBoss) can be configured to persist session state to disk so that it can be preserved across a crash or server restart.  The same servers also support sharing session state between all nodes in a cluster so that the user can hit any node in the cluster without losing their session (and so that if a cluster node goes down, the user can continue their session with a different node as if nothing has happened).
Comment: @aroth - You are correct. My second paragraph was referring to the issues to the most common way sessions are handled in Tomcat, especially as it comes out of the box (so to say). I alluded to the more intricate systems available, but didn't think that this question required a deep dive into all the intricacies of persistent/shared sessions. If you look at the original question, all it was asking for was clarifications on how the cookies worked for session state. I intentionally left out all the different possibilities.
Comment: Are there any safe alternatives?
Answer: The cookie just contains a session identifier (typically called JSESSIONID).  The server maps this identifier to whatever data is currently stored in the user's session.
The data itself may be stored in memory, or it may be serialized to database or to file depending upon what server you are using and its configuration.


set block to appear after page view

Question: This is probably a simple question, but how do you ensure a page view sites above a block on a page? Currently I have a page view which displays some content and then have a block view which holds some other content.This block view was added to the page view via the blocks page. Problem is the block appears before the page view content, any ideas on how to reorder this?
Answer: If I understand the question right, the answer should be as simple as changing the block region :
go to:
https://www.example.com/admin/structure/block
and change the specified block region to footer or a region below "main content region".
You may check regions positioning by clicking on "Demonstrate block regions (Your-Theme-name)"
Comment: The issue is that some of the content is produced as part of a page view and not as a block. The block content however seems to displace it and push it down. What I want to happen is for the page content to stay above the block.

set block to appear after page view


Isoperimetric problem.

Question: Introduction.
The isoperimetric problem is to determine a plane figure of the largest possible area whose boundary has a specified length (wiki).

I know several ways to solve this problem and I do not ask about any of them. I want to ask about my own solution which I describe below.
What do you think is it valid?
Solution
It is quite obvious that figure must be convex
in order to bound the largest area.
Suppose we have convex figure $\Phi$. Without
loss of generality we can assume that length of
$\Phi$ is equal to 1, so $l = 1$. Next step is
to draw a straight line (call it $L_1$) that intersects $\Phi$
so points of intersections, say, $p_1$ and $p_2$
are split $\partial\Phi$ into two curves, say, $l_1$ and $l_2$ which have equal length.
$L_1$ splits $\Phi$ into two
figures, say, $\Phi'$ and $\Phi''$. Now the following algorithm should be executed:
Algorithm

If $S(\Phi')\geq S(\Phi'')$ then substitute ∂Φ″ with the reflection of ∂Φ′ around the line dividing Φ″ from Φ′.
 Else vice-versa.
Choose another line $L_i$ which is do the same job as the line $L_{i-1}$.
Return to step 1.

Where $S(\Phi)$ is area bounded by $\Phi$. It requires to note that $L_i$ can be chosen in the following way: every iteration point $p_1$  shifts along $\partial \Phi$ by $1/\sqrt{2}$. The second point $p_2$ then appear in order to fulfill the above condition.
It is obvious that $\Delta(S(\Phi))\geq 0$ after
each iteration of the above algorithm. Also obvious that if initial figure was a circle then
$$\lim_{n\to\infty}{S(\Phi_0) - S(\Phi_n)} = 0.$$
BUT. It is not obvious for me the opposite statement:
$$\forall \Phi_0: \lim_{n\to\infty}{\Phi_n} = \mathrm{Circle}.$$
Comment: You are imitating Steiner simmetrization, but your argument is very much incomplete.
Comment: @MoisheCohen, It seems you are right. Thank you.
Comment: It is an interesting approach, but it does not really work. If the initial curve is an ellipse, every chord bisecting the perimeter also bisects the area, but the area of an ellipse can be increased without affecting the perimeter, since the perimeter of an ellipse is given by the AGM mean.
Comment: I do not understand  your logic. Could you explain what do you mean in more details.
Comment: I haven't a proof of your last statement, but I tried your algorithm with Mathematica, starting from a square, and I got a nice circle.
Comment: To proof you would check all convex closed curves;) BTW could you post here some of your iterations.
Comment: I'll certainly do that later, now I'm busy. Let me add that you simply wrote "If S(Φ′)≥S(Φ″) then change ∂Φ″ to ∂Φ′ ", which is too vague. In my algorithm, I substituted ∂Φ″ with the reflection of ∂Φ′ around the line dividing Φ″ from Φ′.
By the way: I also tried a version of your algorithm, where at each step the half with LOWER area is taken. The result is quite surprising.
Comment: I have edited formulation. Your second result is intriguing. Wait for it.
Answer: This is not an answer: I'm just showing some results I obtained with Mathematica from the algorithm described above.
Starting from a square, one readily ends with a circle (50 iterations are shown):

Starting from a rectangle (base : height = 100 : 1) one gets a circle again (50 iterations are shown). Notice that at a concave polygon might arise in the process, in which case one of its halves could be a self-intersecting polygon.

To prove that the iteration always tends to a circle, one could argue as follows:
1) polygon area is a not decreasing and bounded sequence, so it must tend to a limit;
2) the limiting figure must be reflection symmetric across any line dividing its perimeter into two equal pieces, but only a circle possesses such a symmetry.
This reasoning is flawed: area tends to a limit, but we don't know that there is a single shape corresponding to that limiting value. There could be, for instance, two or more limiting figures, such that applying the algorithm to one of them one gets another one. I found an example of that in the "minimum" algorithm, see below.
Just for fun, I also considered a "minimum" algorithm, where at each step one reflects the polygon having lower area, instead of the larger one. I was quite surprised when I saw that, starting with a square, a circle would apparently still be the limiting shape (200 iterations are shown):

On closer inspection, however, I realized it is not a "smooth" circle, because it has a jagged perimeter (so I presume the limiting shape could be some kind of fractal).
Starting with a rectangle I got another strange limiting behaviour: not a single shape, but two polygons of different area, with one of them transforming into a rotated copy of the other (200 iterations are shown):

There is a caveat: the area for a self-intersecting polygon can be defined in several ways. I used a formula which counts the different loops with different sign, according to their chirality. Using a different definition could lead to different results.
Comment: WOW. Amazing. Thanks a lot for this. BTW. My arguments were the same as yours when I started to solve the isoperimetric problem but then, wait a minute, who said that algorithm leads us to maximum area. It can be (maybe it cannot be) that starting with one figure all process turned to the loop. I think you said the same in other words. P.S. About ''Minimum'' algorithm. It deserves separate question.

Isoperimetric problem.


Form groups of items, without repetition, that fit a defined value

Question: I'm having a hard time finding a solution for a spreadsheet on google sheets, javascript language. I was seeing some things like group by and discard. But I still haven't been able to assemble anything mentally that would come to any result.
I need to find items and groups of items (summed) within a dataset that fits the given defined value.
I have a data sheet with defined values, here is an example list

item
value

1
100.00

2
53.50

3
45.00

4
67.00

5
32.50

6
35.60

7
34.70

I need groups of items to be formed so that their sum is ideally 100.00, but it can be something close to that, even a little higher would be possible, but the ideal would be up to (<=).
Expected result logic:

Group 1 = item 1 value 100.00

Group 2 = item 4 value 67.00 and item 5 value 32.50 (since the sum is
99.50, being the closest to 100)

Group 3 = item 2 value 53.50 and item 3 value 45.00 (since the sum is 98.50, being the closest to 100)

Group 4 = item 6 value 35.60 + item 7 value 34.70 (since the sum is 70.30)

It doesn't matter the order of the items or the formation of the item groups. Only items cannot be repeated.
As an output you would only need the items from each group. Ex:
1

4 5

2 3

6 7

But if it had all the results it would be excellent (group, items, total value)
Group 1 item(s) 1 total value 100.00

Group 2 item(s) 4 5 total value 99.50

Group 3 item(s) 2 3 total value 98.50

Group 4 item(s) 6 7 total value 70.30

I'm thinking this way, but I still haven't found how to do it

Action
Rule
Result

Check the maximum value of an ITEM as the LIMITER cannot be lower
Maximum value
Show maximum value. Ex: 100

Set LIMITER as long as it is equal to or less than an ITEM's maximum value
<=MaximumValue
Example: LIMITER: 100

Check if any ITEM has a value equal to the LIMITER 100
value == LIMIT
Set in sequential order (+1 in each cycle) the group number for items with a value of 100 first

check if any sum of ITEM is equal to LIMITER 100
sum of items = value of the limiter, without repeating items already listed
Set in sequential order (+1 in each cycle) the number of the group of items summed with a value of 100

check if any ITEM is = -0.01 which previous search
without repeating items already listed
Set in sequential order (+1 in each cycle) the number of the group of items with values lower than the limiter

check if any sum of items is = -0.01 which previous search
sum of items = value of fetched, without repeating items already listed
Set in sequential order (+1 in each cycle) the group number for summed items with values lower than the limiter

continue searches until no values remain
without repeating items already listed
Set list to last available item

Every help is welcome
Answer: I noticed this question is very similar to the knapsack problem. I'm not very good at explaining it, but here are some resources that do a far better job of explaining it than I could.
https://learnersbucket.com/examples/algorithms/knapsack-problem-in-javascript/


subset of pandas dataframe

Question: I have a dataframe df like
Sample  Percentage  Attribute1  Attribute2
1_A       12.3         xxxx        yyyy
1_A       5.0         aaaa        bbbb
2_B       10           ccccc       ddddd

For each sample, I want to choose the row which has the maximum value in Percentage  and make a dataframe df1. If there exist multiple percentages for a sample (such as 1_A), I would like to make a dataframe df2  in which all the rows other than the one that was chosen for df1. In the example above: df1 will have rows of Samples 1_A and 2_B and df2 will have row from Sample 2B. I tried groupby('Percentage') followed by apply(list) but was not successful for df1.
Answer: IIUC drop_duplicates
df.sort_values('Percentage').drop_duplicates('Sample',keep='last')
Out[1046]:
  Sample  Percentage Attribute1 Attribute2
2    2_B        10.0      ccccc      ddddd
0    1_A        12.3       xxxx       yyyy

Answer: I would do this by first sorting the dataframe by Percentage, so the higher percentages are at the bottom. Then, groupby the Sample column, and take the last row using tail(1) to create df1. Then, to create df2, just find the rows of df whose indices are not in df1:
df1 = df.sort_values('Percentage').groupby('Sample').tail(1)

df2 = df[~df.index.isin(df1.index)]

>>> df1
  Sample  Percentage Attribute1 Attribute2
2    2_B        10.0      ccccc      ddddd
0    1_A        12.3       xxxx       yyyy
>>> df2
  Sample  Percentage Attribute1 Attribute2
1    1_A         5.0       aaaa       bbbb

subset of pandas dataframe


Having a beamer_presentation and a pdf_book in the same Bookdown project

Question: In my Bookdown project, I have both a bookdown::pdf_book and a beamer_presentation specificed in the _output.yml. (Why? Here is an example, and here is the explanation.)
The problem is that pdf_book seems to respect the output_dir specified in _bookdown.yml, but not the beamer_presentation. Thus, when hitting the Build Book button, the presentation won't get into the docs directory, it'll appear in the base directory.
Is there any way to make beamer_presentation respect the output_dir specification?
(Also, it'll mean that something has to be done with the filenames, as by default the the names would be the same.)
EDIT: I realized that using bookdown::beamer_presentation2 instead of beamer_presentation will solve the problem, as it'll respect the output_dir. But I'd call it a partial answer, as my fears in the last sentence realized: this will simply overwrite the pdf_book (as they'll indeed have the same name), so it is still not really working...
Comment: Doesn't this look like a duplicate of https://stackoverflow.com/questions/56639760/bookdown-customize-the-output-filename ?
Comment: @tchevrier The original question (how to respect `output_dir`) was not a duplicate, but the later question in "EDIT" is. I'm okay if anyone wants to vote to close this post as a duplicate.
Comment: Yes, its really a "half-duplicate" now, thanks @tchevrier for mentioning that question.
Answer: Yes, you need to use bookdown::beamer_presentation2, which will respect the output_dir setting in _bookdown.yml.
Regarding to your second problem (two formats having the same output filename), there isn't a nice solution at the moment if you only want to click the Knit button in RStudio---you have to call rmarkdown::render() and specify the output filename in the call, e.g.,
rmarkdown::render('file.Rmd', 'bookdown::pdf_book', output_file = 'book.pdf')
rmarkdown::render('file.Rmd', 'bookdown::beamer_presentation2', output_file = 'beamer.pdf')

Comment: @tchevrier Thanks for the reminder! I have totally forgotten it, but will definitely reconsider it in the future since the [Github issue](https://github.com/rstudio/bookdown/issues/737) is still open.
Comment: Now you know why we all love you so much! :-)
Comment: Thanks very much for the answer! Do you have any prediction whether this feature (i.e. that the output file's name can be specified in `_bookdown.yml`, so that Render button will be sufficient) will ever be implemented? I totally understand that there is no timeline you can promise, just an approximation (I have no idea how complicated this would be).
Comment: again, this solution looks like a duplicate of the one you provided for https://stackoverflow.com/questions/56639760/bookdown-customize-the-output-filename ? I also raised this issue in your related post:  https://stackoverflow.com/questions/58885889/embedding-a-beamer-presentation-in-a-regular-document-with-rmarkdown/60552065#60552065  +1 would be nice feature to have...
Comment: Thank you both! I am really happy that it has an open issue on Github, I already subscribed to its notification. Hope it'll be resolved one day :) Thanks again!
Comment: and if you could somehow help to get pandoc to revert from the idiotic behavior of slapping non-slide content onto a slide - that would be really much appreciated. At this time, it's just me alone fighting against windmills... Don Quichotte style.


Show that $x_{\alpha} \rightarrow x$ in $M$ iff $x_{\alpha}$ is eventually equal to x.

Question: Let $M$ be any metric space. A mapping $P(\alpha)=x_{\alpha}$ of $\Omega_0$ into $M$ will be a net; where $\Omega_0=\Omega - \{\omega_1\}$ and $\Omega$ denotes the set of ordinals $\leq \omega_1$. Show that $x_{\alpha} \rightarrow x$ in $M$ iff $x_{\alpha}$ is eventually equal to $x$.
My attempt
I proved the sufficiency by contradiction.
$x_{\alpha}$ is eventually equal to $x$, then exists $\alpha_0 \in \Omega_0$ such that if $\alpha \geq \alpha_0$, $x_{\alpha}=x$. Let $U$ a open neighborhood of $x$ ($x \in U$) such that $\forall \alpha' \in \Omega_0 $, $x_{\alpha'}$ doesn't belong in $U$. Take a $\alpha^* \geq \alpha_0$, then $x_{\alpha^*}$ doesn't belong in $U$ then $x$ doesn't belong in $U$.
Could you guide me with the first part and if what I did is correct?
Comment: See here https://math.stackexchange.com/questions/1894387/a-net-varphi-0-omega-1-to-m-on-a-metric-space-m-converges-iff-var?rq=1
Answer: For each $n \in \mathbb N$, there exist $\alpha_n \in \omega_1$ such that, for all $\alpha\gt\alpha_1$, $d(x_\alpha, x_0)\lt\frac{1}{n}$. Let $\beta = \sup{\alpha_n}\lt\omega_1$. Then $d(x_\alpha, x_0) = 0$ for all $\alpha \ge\beta$.


How to Use the same object among 3 different osgi bundles that is 3 different java plugin projects

Question: Iam using OSGI framework for my project and iam using Core Java.
There are 3 bundles 1.Interface bundle 2. Implementer bundle(Implements the interface)  3. APP bundle(call the interface methods and we set values to below object)
I have a INTERFACE bundle with below methods
public int addDevice(String Devtype, RegInfo reginfo);
public int modifyDevice(String Devicetype,int deviceID,RegInfo reginfo);
Then iam implementing the above methods in the IMPLEMENTER bundle.From the above as you can see there is a RegInfo object which contains setters and getters.So i will get values set in the APP bundle from the object using getters and use it internally.
Then i need to set values to the RegInfo object in the APP bundle.
I want to share the common RegInfo object among all three bundles.
Please note 3 bundles means 3 different java plugin projects all together.
Thanks in advance.
Answer: I would then assume RegInfo is a type in the API package holding the interface. So the APP bundle would construct and configure a RegInfo object and pass it via the interface to the class implementing the interface.
You don't mention using OSGi services, but this is the recommended way for the implementor bundle to make its implementation of the interface available to consumers. The app bundle would then lookup the service and use it.
RegInfo sounds like it should be a DTO type.
Comment: Yes Hargrave you are right RegInfo is a kind of DTO.So do you have any sample code to use the same.


Basics of probability theory - fifth graders homework

Question: If you write some four-digit numbers using the digits $1, 2, 3, 4,$ place them in the bag, what is the probability of getting the number, which is $4$ in the ones digit(first from the right side)?
Comment: Not sure this is clear.  I'll make a guess:  "You draw the digits one by one, making a number from right to left (first draw is the units place, second the tens place, and so on).  What is the probability that the digit in the units place is the $4$?"  Assuming this is right then the answer is $\frac 14$ by symmetry.  But, honestly, the question is phrased so poorly that many other answers are plausible.
Comment: Thank you. I feel like the task is unfinished, just posted the question here to confirm my guess.
Comment: Given that it's a problem for kids, I'll bet my reading is right...it's the sort of thing you could actually set up so they could experiment with it.  But even so, the phrasing really needs to be clearer.
Answer: One quarter.  One half.  One.  Zero.  $0.179.$  None of the above.
I'm kidding a bit, but the probability is the ratio of the number of four-digit numbers that end in $4$ versus the total number of numbers in the bag:
$$P = \frac{N_{\text{end in 4}}}{N}$$
So if you put $1234, 2234, 4432, 4431, 4433$ in the bag, the probability is $0.4$.  If you put $4432, 1233, 1243$ in the bag, the probability is zero.  If you put $1234$ in the bag, the probability is one.  It depends crucially on which numbers are on the slips of paper in the bag.
Comment: I agree with you. For me, it looks like conditions of the problem unfinished.


Print specific block from a region in drupal 7

Question: The region name is "sidebar_first". and it has two blocks. How can I print this block separately. Please help. I can not find the way to print a specific block from a region in drupal 7.
Comment: Where do you want to print it? in a node / page / another block?
Comment: Any reason not to simply create 2 regions? Or move blocks around with CSS?
Answer: You can use this method:
<code>$module = 'my_module'; // This is the module that provides the hook_block_view
$delta = 'my_block'; // you can get $delta from moduel hook_block_info
$block = module_invoke($module, 'block_view', $delta);
print render($block['content']);
</code>
Comment: Thank you for replying. Do you give a example link?
Comment: @anikbiswas what example would you need? It's already copy-paste-adjust code that requires next to no real work on your part, and what you need to do is described in comments.


Reactjs and typescript error TS2322: Type is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes

Question: I have run into a TS2322 error while passing the method searchForBooks as props to SearchBooks component from the JumboBooks component:
JumboBooks.tsx (Parent)
import { RouteComponentProps } from 'react-router';
...
export class JumboBooks extends React.Component<RouteComponentProps<{}>, {}> {
...
searchForBooks(searchFilters: SearchParameters){...}
...

 public render() {
        return (

<SearchBooks searchForBooks={this.searchForBooks} />
...
}

SearchBooks.tsx
import { RouteComponentProps } from 'react-router';
...
interface IBookSearchProps {
    searchForBooks:(filters: SearchParameters)=> void;
}

export class SearchBooks extends React.Component<IBookSearchProps & RouteComponentProps<{}>, {}> {
isearchForBooks() {
    var filters: SearchParameters = {
        // fill up parameters based on ref values
    };

    this.props.searchForBooks(filters);
  }
  ...
}

export interface SearchParameters
{
    ...
}

Error:

Error:
      TS2322: Type '{ searchForBooks: (searchFilters: SearchParameters) => void; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }>...'.
            Type '{ searchForBooks: (searchFilters: SearchParameters) => void; }' is not assignable to type 'Readonly>'.
              Property 'match' is missing in type '{ searchForBooks: (searchFilters: SearchParameters) => void; }'.
Comment: `RouteComponentProps` is adding a necessary `match` prop to your `SearchBooks` component, but it's not being provided. Does that come from a HOC later on?
Comment: Which component are you using when you're rendering ``? Is that your `JumboBooks` component?
Comment: @RossAllen I have this import { RouteComponentProps } from 'react-router'; statement for both.
Comment: @John Right, but the type complaint is that when you're instantiating `SearchBooks` like this: ``, it's not getting the `match` prop that you said it needed when you did `& RouteComponentProps<{}>`. Where does that `match` prop come from? Is this component wrapped in a higher-order component?
Comment: @RossAllen You've nailed it! Could you please let me know how to pass  the match prop? As an answer to this question instead in this comment.
Comment: @John I don't know how to pass the `match` prop. Where do you expect it to come from? Which component is actually being used as a `'react-router'` Route? You will have to pass the prop down normally.
Comment: @RossAllen I'm quite new to this, could you please suggest the best way to go about it?
Comment: @RossAllen Yes, that's right.
Answer: Only your JumboBooks is actually being using as a RouteComponent (being passed as <Route component={JumboBooks} />), so only it will automatically receive the match prop. Any descendants of JumboBooks that you want to have access to match you will have to pass in like a normal old prop:
export class JumboBooks extends React.Component<RouteComponentProps<{}>, {}> {
  public render() {
    return (

        <SearchBooks
          match={this.props.match}
          searchForBooks={this.searchForBooks}
        />

    );
  }
}

if you don't actually need the match prop, delete the RouteComponentProps<{}> from your SearchBooks component:
export class SearchBooks extends React.Component<IBookSearchProps, {}> {

Comment: Thank you, it worked when I added:


Lower bound on $E\|Z\|$ for normal $Z$

Question: Put $Z \sim N(0,I_n)$. Show that
\begin{align*}
E \|Z\| \geq \frac{n}{\sqrt{n+1}}.
\end{align*}
The CLT says that $n^{-1}\|Z\|^2 = 1 + O_p(n^{-1/2})$, so $n^{-1/2}\|Z\| = \sqrt{1+O_p(n^{-1/2})} \approx 1 + O_p(n^{-1/2})$. Multiplying by $\sqrt{n}$ and taking expectation gives
\begin{align*}
E\|Z\| \geq \sqrt{n} - O(1),
\end{align*}
which agrees with the above bound, but I don't see how to prove it.
Comment: This is all addressed in this post: https://math.stackexchange.com/questions/827826/average-norm-of-a-n-dimensional-vector-given-by-a-normal-distribution
Comment: I see. Thanks for the reference.
Answer: It would help to define $Z$ and $I_n$.  If $Z$ is one random variable. what has that to do with CLT?
As stated $E|Z|=\frac{2}{\sqrt{2\pi}I_n}\int_0^\infty xe^{-\frac{x^2}{2I_n^2}}dx=\sqrt{\frac{2}{\pi}}I_n$
Answer: $$||Z||=\sqrt{Z_1^2+Z_2^2+\cdots Z_n^2}$$
$Z_i$ are independent and $Z_i^2\sim \chi^2_{1}$
$$Y=Z_1^2+Z_2^2+\cdots Z_n^2\sim \chi^2_{n}$$
Chi-square_distribution#Noncentral_moments
$$E(Y^k)=\frac{\Gamma(\frac{n}{2}+k)}{\Gamma(\frac{n}{2})}2^{k}$$
$$E||Z||=E(Y^\frac{1}{2})$$

Lower bound on $E\|Z\|$ for normal $Z$


SPDY http2 + push throws exception in Angular 6 SSR

Question: I have Angular 6 project with SPDY http2 push and SSR enabled. When clicking around more with hard refreshes and navigating around sometimes i got these errors:
and after couple refreshes i got that weired error:

{ AssertionError [ERR_ASSERTION]: false == true
    at PriorityNode.removeChild (C:\git\wearlenses-3-client\web\dist\server.js:130338:3)
    at PriorityNode.remove (C:\git\wearlenses-3-client\web\dist\server.js:130326:15)
    at PriorityTree.add (C:\git\wearlenses-3-client\web\dist\server.js:130427:23)
    at Stream._initPriority (C:\git\wearlenses-3-client\web\dist\server.js:130559:25)
    at new Stream (C:\git\wearlenses-3-client\web\dist\server.js:130534:8)
    at Connection._createStream (C:\git\wearlenses-3-client\web\dist\server.js:131564:16)
    at Connection._handleHeaders (C:\git\wearlenses-3-client\web\dist\server.js:131612:21)
    at Connection._handleFrame (C:\git\wearlenses-3-client\web\dist\server.js:131495:10)
    at Parser.<anonymous> (C:\git\wearlenses-3-client\web\dist\server.js:131332:10)
    at ZoneDelegate.invokeTask (C:\git\wearlenses-3-client\web\dist\server.js:117435:31)
  generatedMessage: true,
  name: 'AssertionError [ERR_ASSERTION]',
  code: 'ERR_ASSERTION',
  actual: false,
  expected: true,
  operator: '==' }

TypeError: Cannot read property 'getPriority' of null
    at C:\git\wearlenses-3-client\web\dist\server.js:130627:32
    at ZoneDelegate.invokeTask (C:\git\wearlenses-3-client\web\dist\server.js:117435:31)
    at Zone.runTask (C:\git\wearlenses-3-client\web\dist\server.js:117202:47)
    at ZoneTask.invokeTask (C:\git\wearlenses-3-client\web\dist\server.js:117510:34)
    at ZoneTask.invoke (C:\git\wearlenses-3-client\web\dist\server.js:117499:48)
    at data.args.(anonymous function) (C:\git\wearlenses-3-client\web\dist\server.js:118352:25)
    at process._tickCallback (internal/process/next_tick.js:112:11)

Here is parts of code:
```
app.get('*', (req: any, res: any) =>
{
<code>try {
    Promise.all([...config.files]).then((data: any[]) => {
            for (let i = 0; i < config.files.length; i++) {
                const pushOptions = {
                    status: 200, // optional
                    method: 'GET', // optional
                    request: {
                        accept: '*/*'
                    },
                    response: {
                        'content-type': config.files[i].mimeType,
                        'Cache-Control': 'public, max-age=30672000'
                    }
                };

                let contentToSend = data[i];

                if (config.files[i].mimeType === 'application/font-woff2') {
                    contentToSend = new Buffer(contentToSend);
                    pushOptions.response['Content-Length'] = contentToSend.length;
                    pushOptions.response['Accept-Ranges'] = 'bytes';
                }

                if (config.files[i].gzip) {
                    pushOptions.response['content-encoding'] = 'gzip';
                    contentToSend = zlib.gzipSync(contentToSend);
                }

                const stream = (<any>res).push(`/${config.files[i].name}`, pushOptions);

                stream.on('error', () => { });

                stream.end(contentToSend);
            }
        }).catch(error => { });
} catch (e) {
    console.log(e);
}

res.render('index', { req });
</code>
});
```
I feel like there should be res.render in another place but if i try to put it after stream.end performance drops.
What I should do differently?
Answer: I have solved this issue. This is some bug and quick fix for this is:
let fs = require('fs')
let path = require('path')
let file = path.join(
    process.cwd(),
    'node_modules/spdy-transport/lib/spdy-transport/priority.js'
)

let data = fs
    .readFileSync(file)
    .toString()
    .split('\n')
if (data.length < 190) {
    data.splice(73, 0, '/*')
    data.splice(75, 0, '*/')
    data.splice(
        187,
        0,
        `
    var index = utils.binarySearch(this.list, node, compareChildren);
    this.list.splice(index, 1);
`
    )
    let text = data.join('\n')

    fs.writeFile(file, text, function(err) {
        if (err) return console.log(err)
    })
}

sources where taken from:
https://github.com/spdy-http2/spdy-transport/issues/47
https://github.com/Noumenae/server/issues/20
https://github.com/spdy-http2/node-spdy/issues/285
https://github.com/spdy-http2/node-spdy/issues/244

As far as I understood everybody just wait for Express 5 which will have natvie http2 support.


Closed-form equation for $\int_{0.5}^{1} Beta(\alpha,\beta)$?

Question: I don't know if this question is too trivial for you guys, it is not for me though...
Is there a closed-form equation for $b = \int_{0.5}^{1} Beta(\alpha,\beta)$?
$$
Beta = \frac{x^{\alpha-1}(1-x)^{\beta-1}}{B(\alpha,\beta)}
$$
$$
B(\alpha,\beta) = \frac{\Gamma(\alpha)\Gamma(\beta)}{\Gamma(\alpha+\beta)}
$$
Google search doesn't help much when querying for a mathematical equation, I really tried...
Comment: What are you integrating, the density or the distribution, or something else? Note that the integral of the density is the regularized [incomplete beta function](https://en.wikipedia.org/wiki/Beta_function#Incomplete_beta_function) which is not generally in closed form but might be doable in particular instances.
Comment: please edit the density into your question. What do you need this in closed form for? (It's easy enough to evaluate in practice). Do you really need the general case?
Comment: It is rather sloppy to omit the differential in this case. Which variable are you concerned with?
Comment: The PDF (Probability density function)
Answer: There is ... but it is complicated, and not sure if that useful. I am assuming the integral you want is
$$
\int_{0.5}^1 \text{beta}(x; \alpha, \beta) \; dx
$$ where the beta density is $\text{beta}(x; \alpha,\beta)=\frac{x^{\alpha-1} (1-x)^{\beta-1}}{B(\alpha, \beta)}$.
With some help from maple this integral is evaluated as
$$
{\frac {1}{{\rm B} \left(\alpha,\beta\right)\alpha} \left( -
{\mbox{$_2$F$_1$}(\alpha,-\beta+1;\,1+\alpha;\,{\frac{1}{2}})}{2}^{-
\alpha}+{\frac {\Gamma \left( 1+\alpha \right) \Gamma \left( \beta
 \right) }{\Gamma \left( \alpha+\beta \right) }} \right) }
$$
Comment: Doesn't this just reformulate the question?  How would one go about computing values of $_2F_1$ accurately?  (It's not simple to do so in full generality.)
Comment: Anyone who does not conceive of an regularized complete Beta function as a "closed form" is *a fortiori* not going to accept an algebraic combination of Gamma and hypergeometric values as closed!
Comment: Maybe --- depends on what is the purpose of the question
Comment: Yes, that is *not* closed form in any sense I have seen the term used.


iOS: sizeWithFont: for custom font

Question: I've been plugging away and I need to use the sizeWithFont: method to properly line up my layout, but it doesn't seem to work with custom fonts. Is there a way to get it to work, or maybe another method I can use?
I'm pretty stumped on this. Any help is appreciated.
Comment: Are you absolutely certain that the custom font is loading properly, and that you're getting the size for the variant of the font (regular, bold, etc.) that you are actually using?
Comment: Yes. It is definitely working. If I set the size manually, the proper font shows up on the view. I have added the ttf files to the project and implemented them in my plist file under the key 'UIAppFonts'.
Comment: Hm, it should definitely be working.  Is it not returning anything at all, or just incorrect values?
Comment: Actually, after further inspection, it may not be working. The font information is all null/0.0f. What could be the problem. When I try viewing the ttf in XCode, it shows all of the letters as per usual and I have put the fonts into the plist. It seems that everything SHOULD work. Given that the font isn't actually being pulled, can I do something now?
Answer: sizeWithFont should definitely work, but if it's giving you a problem then there is a workaround.  You can put the text in a UITextView, add it to your layout, and then retrieve the actual text size and adjust accordingly.  Here's some sample code from one of my projects:
<code>     // Put in the title in
    self.titleView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 195, 195)];
    self.titleView.font = [UIFont fontWithName:@"Bliss Pro" size:20.0];
    [self addSubview:self.titleView];

    self.titleView.text = @"Add your text here";

    // Now get the actual size of the text and resize the title view's frame
    CGRect frame = self.titleView.frame;
    frame.size.height = self.titleView.contentSize.height;
    self.titleView.frame = frame;
</code>
It's a bit hackish, but it certainly works.
Comment: Right! I've had to use this method before to incorporate a description with highlight for copy and paste. But I've figured out the answer and it probably should be known as well. If you come around, could you add it to your answer so that it will have both answers in it?
Comment: The answer is that font names aren't necessarily the same as the name of the file. I was using Gotham-Bold.ttf and I ended up having to import "Gotham Bold", instead of "Gotham-Bold". I wasn't the one to get the font, just to implement it, so its good to know.
Comment: My bad Leena, I forgot to add the line where you actually set the text for the UITextView.  Once there is actual text in the view to calculate the height of, the code will work.  I added the line in now.
Answer: <code>#define kFontSize 14.0    //modify your font size
CGSize size = [yourView sizeWithFont:[UIFont boldSystemFontOfSize:kFontSize]];
</code>

iOS: sizeWithFont: for custom font


Area of astroid given in parametric form

Question: Find the area of the region bounded by the astroid, in parametric form, $(x;y)=(2cos^3 t; 2sin^3 t)$
Well, I used the formula of area given in parametric curves $\int_a^b y(t).x'(t) \,dt$. So, as it's an astroid, I know that I can find the area between $[0; \pi ]$ and multiply it by 2. Then, after differentiating and replacing, I get $2 \int_0^\pi 2sin^3(t).(-6cos^2(t)sin(t)) \,dt$
which can be written as $-24 \int_0^\pi sin^4(t).cos^2(t) \,dt$
The thing is that I integrated using trigonometric identities, but it was really tedious, and, to top it, it was wrong, because when I differentiated the result I didn't get the first function and the area was negative.
Comment: See here https://math.stackexchange.com/questions/66027/how-can-i-calculate-area-of-astroid-represented-by-parameter
Comment: You might have an easier time of it if you use $\frac12(x\,dy-y\,dx)$ as the integrand.
Comment: @Dr.SonnhardGraubner I'm not sure that question helps much. The OP is already trying to use the method given in the accepted answer; the issue appears to be in the details of the actual calculation.
Comment: The sign of your answer came out wrong because you left out a negative sign in the first place. As to why the value is otherwise incorrect, you'll have to show your work for anyone to be able to point out your error.
Answer: We can dispense with the reason that you ended up with a negative area easily: you left a negative sign out in the first place. Referring to this answer to an almost-identical question, the area of the astroid within the first quadrant is $-\int_0^{\pi/2} x'(t) y(t) \,dt$. The negative sign appears because $x$ decreases as $t$ increases from $0$ to $\frac\pi2$.
As for the rest, it's impossible to say why you ended up with the wrong value without seeing your work. However, I think you could've made it a bit easier on yourself by using a different area element. The symmetries of $\sin$ and $\cos$ to me suggest using a more balanced volume element, namely $\frac12(x\,dy-y\,dx)$, or $$\frac12 \begin{vmatrix}x(t)&y(t)\\x'(t)&y'(t)\end{vmatrix} dt = \frac12\left(x(t)y'(t)-y(t)x'(t)\right) dt.$$ You can visualize this as the area of the infinitesimal triangle with sides defined by the vectors $(x,y)$ and $(x+dx,y+dy)$, i.e., an approximation to the area swept out by the radius vector $\mathbf r(t)=\left(x(t),y(t)\right)$ between $t$ and $t+dt$. For the astroid, the integrand is therefore $$\begin{align}\frac12 \begin{vmatrix}2\cos^3t & 2\sin^3t \\ -6\cos^2t\sin t & 6\cos t\sin^2t\end{vmatrix} &= 6\left(\cos^4t\sin^2t+\cos^2t\sin^4t\right) \\ &= 6\cos^2t\sin^2t \\ &= \frac32\sin^2{2t}, \end{align}$$ which can be simplified further to $\frac34(1-\cos{4t})$ using the identity $\cos{2\theta} = 1-2\sin^2\theta$.


Cannot connect to Postgres from remote address

Question: I cannot connect from my machine to a server running Postgres. I think I've configured it all correctly. No firewall are present on the server.
I'm running Postgres 9.1.9 on Ubuntu 12.04 LTS
This is from /etc/postgresql/9.1/main/pg_hba.conf
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

local   all             all                                     peer
host    all             all             0.0.0.0/0               md5
host    all             all             ::1/128                 md5

I have listen_addresses = '*' in /etc/postgresql/9.1/main/postgresql.conf
I've stopped and started the service multiple times.
netstat -tulnp:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN      19312/mongod
tcp        0      0 0.0.0.0:28017           0.0.0.0:*               LISTEN      19312/mongod
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      978/sshd
tcp        0      0 0.0.0.0:5432            0.0.0.0:*               LISTEN      30239/postgres
tcp6       0      0 :::22                   :::*                    LISTEN      978/sshd
tcp6       0      0 :::5432                 :::*                    LISTEN      30239/postgres

My iptable is empty.
When I try to connect to the server with
psql -U postgres -h <MY_IP>

I get:
psql: could not connect to server: Operation timed out
Is the server running on host "<MY_IP>" and accepting
TCP/IP connections on port 5432?

Any help? Thanks
tcpdump on port 5432:
16:33:10.548507 7c:c3:a1:a2:d9:27 (oui Unknown) > 00:00:5e:00:01:01 (oui Unknown), ethertype IPv4 (0x0800), length 78: <MY_MAC> > <MY_SERVER>.postgresql: Flags [S], seq 95915852, win 65535, options [mss 1460,nop,wscale 4,nop,nop,TS val 1189142453 ecr 0,sackOK,eol], length 0

I can connect to postgres on the server (psql -U postgres -h localhost) but I cannot telnet on 5432 from my machine.
Comment: The configuration looks right to me, but connection timeout strongly suggests that there is a firewall dropping the packet.
Comment: Check your server logs - specifically, look for iptables, ufw, or SELinux messages.
Answer: Remember that the maching running the client might also have iptables rules set that block the out- or inbound part of the connections.
Answer: It looks like there's firewall blocking your network traffic. There's no information in your message about networks (client and postgres server), but it looks like there are some firewall rules that blocks traffic between client and server.
Answer: are you using ipv4 or ipv6.
because your tcpdump sample show ipv6 connection, and you dont have enabled ipv6 connection on the pg_hba.conf
::1/128  --------> loopback


How do I query for USB devices not listed in USB Root Hub

Question: Query which works for some devices found in Win32_USBHub
SELECT * FROM Win32_USBHub WHERE DeviceID = '{0}'

Here's the code context,
// Check if USB device is plugged in
string deviceQuery = String.Format("SELECT * FROM Win32_USBHub WHERE DeviceID = '{0}'", deviceID);
using (var searcher = new System.Management.ManagementObjectSearcher(deviceQuery))
    if (searcher.Get().Count == 0)
        MessageBox.Show(@"Device not detected");

However when a device is not listed inside 'Universal Serial Bus controllers', querying from Win32_USBHub does not return the connected device I'm looking for.

Is there another 'table' to query outside from Win32_USBHub which would contain device I'm looking for 'Cardio Perfect PRO-Link USB'? Or would this be a 'custom table'?
Answer: SELECT * FROM Win32_PnPEntity WHERE DeviceID = '{0}'

I guess I didn't search long enough, here's a link which contains a lot of really good examples...
http://msdn.microsoft.com/en-us/library/aa394587%28v=vs.85%29.aspx
The 'table' I was looking for is Win32_PnPEntity it listed all 155 devices I'm connected to.
Comment: I had to use "SELECT * FROM Win32_PnPEntity" but it listed Windows Portable Devices (aka MTP: Media Transport Protocol) which include Android devices.


What is WCF RIA Commanding

Question: What is WCF RIA Commanding? Is that even the proper name?
I have a silverlight application in which I want to use command binding to call methods on the webserver; however I'm unsure as to how to go about creating such a class and method so that it can be picked up by RIA and be used in the silverlight XAML; whiout any code behind.
Answer: a 'command' in the context of a Silverlight (or WPF) application is a class that implements the ICommand interface.
It is used to bind code in ViewModels to controls in Views.
Just about all the decent MVVM frameworks contain them (PRISM has DelegateCommand, MvvmLight has RelayCommand, etc) but it's not too hard to write your own...
Example usage:
in XAML:
<Button Command="{Binding GetCommand}" Content="Get" />

then in the ViewModel (bound to the View's DataContext)
public ICommand GetCommand
{
    get
    {
        if (_getCommand == null) _getCommand = new RelayCommand(GetHandler, CanGetPredicate);
        return _getCommand;
    }
}

private void GetHandler()
{
    // Do the work here - call into the server, or whatever.
}

private bool CanGetPredicate()
{
    // work out if it is valid for this to be called or not
    return (someRule == true); // or whatever
}

Comment: Instinctively I would say that the ViewModel needs to be client-side; right next to the view, but I haven't done enough in RIA services to say if that is true in this case. I found this article which may explain a bit more... http://www.silverlightshow.net/items/WCF-RIA-Services-Part-4-Integrating-with-the-Model-View-ViewModel-Pattern.aspx
Comment: So this code would be server side attached to one of the entities?
Comment: Thanks, I understand better now.

What is WCF RIA Commanding


Chebyshev Polynomial Recurrence relation

Question: the problem states: "Show that $\cos(n\theta)$ is a polynomial in $\cos(\theta).$" Now, using De Moivre's and Binomial theorems i get that
$$\cos(n\theta) = \sum_{k = 0, evens}^{n}\binom{n}{k}\cos^{n-k}(\theta)(\pm(1-\cos^{2}(\theta))^{k/2})$$
Note that the $\pm$ here does not mean both, but it rather means "we don't care which one," and so it is obvious that the RHS is a polynomial in $\cos(\theta).$
So the second part of the problem asks to "use appropriate trig functions" to show that $$T_{n+1}(z) + T_{n-1}(z) = 2zT_{n}(z).$$
Here i am stuck. Since i have never encountered Chebyshev polynomials before, is the RHS i found for $\cos(n\theta)$ the $T_{n}(z)$? And if so, exactly how would i approach the second part of the problem? I tried induction, but either i am too tired right now, or it really does get hairy too fast. Thanks in advance.
Answer: It's strange that the problem statement would drop $T_n$ onto you without ever indicating its relation to $\cos n\theta$. You are right: $T_n(\cos\theta)=\cos n\theta$ for all $\theta\in\mathbb R$. So, the identity you are asked to prove is related to
$$\cos(n+1)\theta + \cos(n-1)\theta = 2\cos \theta \cos n\theta \tag{1}$$
which follows  by expanding the left side using the cosine of sum/difference formulas.
Identity (1) implies
$$T_{n+1}(z) + T_{n-1}(z) = 2zT_{n}(z)\tag{2}$$
 for $z\in [-1,1]$, since these values of $z$ can be written as $\cos \theta$. But this is enough to conclude (2) holds for all $z$: if two polynomials agree in a neighborhood of $0$, then for every $k\in\mathbb N\cup\{0\}$ their $k$th derivatives agree at $0$, which means they have the same coefficients.
Comment: Sorry if i am missing something, but aren't you proving the relation for the specific input?. Wouldn't i need to somehow use the equation i found above to prove the general case?
Comment: I clarified (hopefully),
Comment: oh that is a beautiful result. Wasn't aware of it. Thanks very much!
Comment: By the way, is there a name to this theorem? (if say i wanted to look up the proof of this)


mysql tempo médio, top 10 modelos

Question: Pessoal conforme ilustração da minha tabela abaixo, eu gostaria de obter os seguintes dados:
✓ Tempo em que o POSTO gastou da DATA_ENTRADA ate a DATA_SAÍDA
✓ Tempo médio geral que todos os POSTOS levam da DATA_ENTRADA ate a DATA_SAÍDA
TABELA: OS
+--------------------------------------------------------------+
| ID | POSTO     | MODELO | DATA_ENTRADA | DATA_SAIDA          |
+--------------------------------------------------------------+
| 1  | SÃO PAULO | FW100  | 2014-11-17   | 2014-11-19 12:59:00 |
+--------------------------------------------------------------+

Comment: @Hugo Qual a dúvida que resta então?
Comment: Ok, o que você gostaria parece claro, acho que falta agora dizer o que você tentou e quais problemas teve ao tentar implementar. Se não, fica parecendo que vc está pedindo que façam o trabalho pra você.
Comment: Testa e vê se funciona corretamente.
Comment: sim @JorgeB. testei e aparentemente funciona
Comment: Ou seja, porque duvida que sua lógica esteja incorreta? Se a única dúvida é sobre o `TOP 10` (item 3), porque citar `POSTO` e `POSTOS` (item 1 e 2)?
Comment: @Thomas editei o posto, veja se consegue me compreender
Comment: @brasofilo melhor agora?
Comment: @Hugo Poderia colocar o nome da tabela na pergunta também? Para ajudar nos exemplos de quem for dar a resposta.
Comment: @Thomas feito ;)
Comment: Hugo da próxima vez, ou mesmo nesta (editando), tente demonstrar o que fez. Colocando em seguida a dúvida.
Answer:
Tempo em que o POSTO gastou da DATA_ENTRADA ate a DATA_SAÍDA

Soma de minutos que tal POSTO gastou:
SELECT SUM(TIMESTAMPDIFF(MINUTE,DATA_ENTRADA,DATA_SAIDA)) AS tempo_total_posto FROM `OS` WHERE POSTO = 'SÃO PAULO'

Tempo médio geral que todos os POSTOS levam da DATA_ENTRADA ate a DATA_SAÍDA

Tempo médio geral de minutos gastos
SELECT AVG(TIMESTAMPDIFF(MINUTE,DATA_ENTRADA,DATA_SAIDA)) AS media_geral FROM `OS`

Comment: 2 perguntas, as vezes a diferença da DATA_ENTRADA e DATA_SAIDA é de dias, daria pra converter os minutos em dias no php? Outra como fazer para que lista o resultado em todas as linhas não só especificando o posto
Comment: @Hugo 1) Daria, é só dividir: `$dias = ($minutos / 60) / 24;` ou então mudar o parâmetro da função `TIMESTAMPDIFF` de `MINUTE` para `DAY`. 2) É só remover o `WHERE POSTO`...  Outra coisa, recomendo que, se você for iniciante, não tenha medo de criar mais perguntas no S.O., mas que não fique usando essa pergunta para outras coisas além do enunciado original, pois prejudica a comunidade.
Comment: meu camarada obrigado pela dica

mysql tempo médio, top 10 modelos


Show $\cos(a+b)=\cos(a)\cos(b)-\sin(a)\sin(b)$ with the circle.

Question: How can I prove that $$\cos(a+b)=\cos(a)\cos(b)-\sin(a)\sin(b)$$ using the circle ?
Comment: What does it mean to prove something "with the circle"?
Comment: Here's a proof: http://pages.pacificcoast.net/~cazelais/173/idns-proof.pdf
Comment: @HowDoIMath: Thanks a lot, it's exactly what I was looking for :-)
Comment: Have a look at this http://math.stackexchange.com/questions/1292/how-can-i-understand-and-prove-the-sum-and-difference-formulas-in-trigonometry
Comment: And do you have something to show with the circle that $\cos a+\cos b=2\cos(\frac{a+b}{2})\cos(\frac{a-b}{2})$
Answer:
Let $z_1=\cos a + i\sin a$ and $z_2=\cos b + i\sin b$ then
$$
\eqalign{
z_1 \cdot z_2 &= (\cos a + i\sin a)\cdot(\cos b + i\sin b) \cr
           &= (\cos a \cos b - \sin a \sin b) + i(\cos a \sin b + \sin a \cos b) \cr
}
$$
we conclude
$$
\cases{
\cos(a+b) = \cos a \cos b - \sin a \sin b \cr
\sin(a+b) = \cos a \sin b + \sin a \cos b \cr
}
$$
Answer: I know that the OP is requesting a geometrical demonstration, but I thought that it would be instructive to see a couple of other approaches.
METHOD 1:
Let $f(x)$ be the function given by
$$f(x)=\cos x \cos(y-x)-\sin x \sin (y-x) \tag 1$$
Differentiating $(1)$, we find that
$$\begin{align}
f'(x)&=-\sin x\cos (y-x)+\cos x \sin (y-x)-\cos x \sin (y-x)+\sin x \cos (y-x)\\\\
&=0
\end{align} $$
Therefore $f$ is a constant for all $x$.
First, letting $y=a+b$ and $x=0$ in $(1)$ shows that
$$f=\cos (a+b) \tag 2$$
Then, letting $y=a+b$ and $x=a$ in $(1)$ shows that
$$f=\cos a \cos b-\sin a \sin b \tag 3$$
Equating $(2)$ and $(3)$ reveals that
$$\cos (a+b)=\cos a \cos b-\sin a \sin b$$
as was to be shown!

METHOD 2:
Using Euler's Identity $e^{ix}=\cos x+i\sin x$, we have
$$e^{i(a+b)}=\cos (a+b)+i\sin(a+b) \tag 1$$
and
$$\begin{align}
e^{i(a+b)}&=e^{ia}e^{ib}\\\\
&=(\cos a+i\sin a)(\cos b+i\sin b)\\\\
&=(\cos a \cos b-\sin a \sin b)+i(\sin a \cos b\cos a \sin b)\tag 2
\end{align}$$
Equating real and imaginary parts of $(1)$ and $(2)$, respectively, reveals
$$\cos (a+b)=\cos a \cos b-\sin a \sin b$$
and
$$\sin(a+b)=\sin a \cos b\cos a \sin b$$
as expected!
Answer: I usually forget this kind of identities, so I have found that it is easy to get some of them writing sine and cosine as complex exponentials. In this case we have:
$$\cos(a+b)=\frac{e^{i(a+b)}+e^{-i(a+b)}}{2}=\frac{e^{ia}e^{ib}+e^{-ia}e^{-ib}}{2}=$$ $$=\frac{(\cos a+i \sin a)(\cos b +i \sin b)+(\cos a - i \sin a)(\cos b - i \sin b)}{2}=$$ $$=\frac{\cos a \cos b + i \sin a \cos b + i \cos a \sin b -\sin a \sin b}{2}+\frac{\cos a \cos b - i \sin a \cos b - i \cos a \sin b -\sin a \sin b}{2}=$$ $$=\frac{2\cos a \cos b -2 \sin a \sin b }{2}= \cos {a} \cos {b} + \sin{ a} \sin {b}$$
PS: Sorry, I didn't read the part that said "using the circle", so this is not what you are looking for. Anyway, I leave it here in the case it is useful as an alternative method.
Answer: Rotate the point of coordinates $(\cos a, \sin a)$ around the origin with the rotation of angle $b$ using the matrix $$R(0,b)=\begin{pmatrix}
\cos b & -\sin b\\
\sin b & \cos b \end{pmatrix}$$


Calculating Euler's Number to nth digit in javascript

Question: How to calculate Euler's Number to nth digit in JavaScript?
e   =   1/0! + 1/1! + 1/2! + ...
    =   2.7182818284590...to nth digit  (base 10)

Below code returns only number to 16 decimal point and accuracy is depend upon to the number of iterations/or number passed to function.
Code
function calcE(n) {
  let euler, itr;
  euler = 0
  itr = Number(n)
    for (var i = 0; i < itr+1; i++) {
      let fact = factorial(i)
      euler += 1/fact
    }
  return euler;
}

Demo: miniwebtool
Comment: The closing votes are very strange - the question is not broad at all. It is simple, that is roght, but there is no any simplicity limit set in the rules of SO. And what is simple for one person, is not such for another one. Upvoting for compensation of unfairness.
Comment: @Gangnus, although I can't see the close votes, I agree that too broad is certainly not correct in this case, it seems that too broad is the go to 'I don't know what to flag this as' reason. Its also worth noting that the edits vastly improve the question. +1
Comment: *"...returns only number to 16 decimal point..."* : JavaScript uses IEEE 754 floating point representations, which limits the precision to about 16 decimal digits. So you'll not be able to get more out of it. See https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript
Answer: You should find the first factorial that is greater than 2*10^n. If it is m!, you should count the e number up to 1/m!.
For the estimation of the m! you can use Stirling's approximation. Don't be afraid of e presence there - you can count it all very roughly, really you need only the order. That way allows you to determine the number of addings beforehand. It can be counted by different algorithm and faster.
If you needn't have it beforehand, you can calculate each 1/m! additions and simply compare it to 0.5/10^n. The first addition that is lesser than 1/10^n is the last that you should use.
    limit = 0.5/10^n
    add = 1
    i = 1
    euler = 1
    while(add>limit) {
      add /= i
      euler += add
      i++
    }
    return euler

Comment: This is subject to a subtle trap. The algorithm you describe computes `e` with the 10^{-n} _precision_, which doesn't guarantee the the `n`'th _digit_ is correct. One must estimate the remaining error (via Taylor theorem e.g.), and keep adding until it becomes small enough to stabilize `n`'th digit.
Comment: @user58697 Yes, I have forgotten to multiply by 0.5. Edited. But the existing practice, when talking about n'th digit, means 0.5 precision. Nobody wants to try if the next addition will change the digits that stands in elder positions. Yes, that can mean that sometimes you will have the tail of 100000 instead of 099999 and vice versa, but that does not matter. The target of that practice is the sure future use of 0.5*lastDigit as the upper limit of the possible error, and it works.
Comment: @user58697  If you are interested in more precise error evaluation that 0.5 of last digit, calculate mistakes evaluations together with the main value.
Answer: Found a solution by using npm decimal.js package to handle big decimal.
Euler
function euler(n) {
  let zero = new Decimal(0);
  let one = new Decimal(1);
  let rval;

  for (let i = 0; i <= n; i++) {
    let fval = factorial(i);
    let invert = one.dividedBy(fval)
    zero = zero.plus(invert)
  }
  rval = zero.toFixed(Number(n))
  return rval;
}

function factorial(n) {
  var i = 2,
    r = new Decimal(1);
  for (; i <= n; r = r.times(i++));
  return r;
}

Still not able to compute very large values. An Suggestions?
Comment: You'll have to use the decimal library also for `factorial(i);`, since also that number quickly runs out of the necessary precision. NB: You should keep an incremental value of the factorial to avoid repetitive re-multiplication of something you already did in the previous iteration.


Counting: In how many ways can you order your coffee, given the options at a coffee shop.

Question: I came across this elementary counting problem: A coffee shop has 4 different types of coffee. You can order your coffee in a small, medium, or large cup. You can also choose whether you want to add cream, sugar, or milk (any combination is possible, for example, you can choose to add all three). In how many ways can you order your coffee?
My attempt:
$4*3*2^3$. Is that correct?
Comment: Yes, that is correct.
Comment: As a small nitpick, use `\cdot` or `\times` for multiplication when typesetting rather than `*`.
Answer: Indeed, you're correct!  There are $4\cdot 3\cdot 2^3$ ways to order your coffee.  Four options for coffee, three options for size. And the $2^3$ factor reflects your knowledge that there are two options "yay" or "nay" for each of cream, sugar, or milk: $2\cdot 2 \cdot 2 = 2^3.$ And by the rule of the product, you get $4\cdot 3 \cdot 2^3 = 96$ ways to order your coffee.
Nice job!
Answer: Yup, that is the answer. You have four options for coffee, three options for size, two options for cream, two options for sugar, and two options for milk, and you have to pick one option for each of these five choices. This does indeed give $$4\cdot 3\cdot 2\cdot 2\cdot 2$$


Delphi XE2 access violation in Win 7 64 bits but not in Win 8

Question: I have a Delphi XE2 application (32 bit) that runs in a Windows 8 machine but gives a access violation error in a Windows 7 64-bits with 6GB RAM.
I would understand if I was accessing a large amount of data but it simply states something as:
    Access violation at address 0000CD31. Read of address 00000000.

The address is always consistent. So is the read of address.
Usually from what Ive read this is a pointer trying to access a portion of memory that is no longer valid/in use. But my doubt arises why it works on Windows 8 and not on Windows 7 64 bits...
I have not been able to reproduce this in a local VM (Same Windows in same language in case it was a language issue) and this only happens on the client's PC.
Another even almost worst issue is that I am debugging this for a work colleague so I do not have access to the code and can't try another function (a fix I've read around here) to see if its that or not. So I cant use something like madExpert to actually debug the code. I would need something remote that can tell me information about the program fully complied and running remotely when the access violation happens.
Comment: There's not a lot of point in you continuing since even if you could identify the problem you can't fix it because you aren't able to build a new executable
Comment: There's a bug in the code. If you aren't able or prepared to do any debugging you'll find it hard to solve the problem. Since you've ruled out all the viable options this isn't really a useful question for anyone else, or even for you. Good luck.
Comment: I don't have direct access to the code and the programmer that works on this section is right now on absenteeism due to a injury. I suggested madExpert as you can see because I think that would be the best way to solve this but If I do not have access to the code, there is no way to do it.
Comment: You are accessing a nil pointer somewhere...
Comment: A explanation to the client is all that is needed. Once a explanation is given then he can work on the code once the programmer is back.
Comment: Why was this downvoted exactly?
Answer: If you can't build in something like madexcept, your options are impov limited to

WER
procdump
Reverse engineer the addres to the source code

From those, the easiest is procdump
procdump -ma -w yourprocess

After you get a dump, you can analyze it with windbg
!analyze  -v

That should show you a stack trace that leads to the problem.
Comment: Trying to get the standalone windbg but man, it is difficult to get alone. You have to install the entire SDK...
Comment: That's not necesary. If you can spend the time, take a look at defrag tools on channel 9 on how to build your own usb thumb drive ready for debugging *([Andrew Richards series](http://channel9.msdn.com/Shows/Defrag-Tools/Defrag-Tools-Building-your-USB-thumbdrive))*
Comment: Ah but then you have ample time ;)
Comment: Couldn't install the SDK and the programmer on this code doesn't want to use madExpert. Guess this one will remain unsolved. We are testing it out if it happens in a VM as well.
Comment: @riahc3 - it's been a while since I configured my own thumbdrive but afaik, installing the entire SDK is not required?! You just need to extract the debuggers from it. Did you view the defrag tools session on getting the debugger? If an install is needed (can't remember), can't you try another computer?


Send email after content update

Question: I have create a new content type with a field of email. In this field I put the email address of the person I want.
The case is:
I want every time the node of this content type updated, to send an email to the address from the email field.
With Rules module I cannot find a proper way to make it work because Rules are on a very early point of development.
There is two problems with rules:
1st - I have create a simple action to send an email every time the node is updated. This is work fine. When I create a condition "Node is of type" and select only one content type the sending email action is still working for all content types.
2nd - I cannot find any proper method for what suppose to write to the reciptient field to send the email to the address from the email field.
Can any one help? Any thoughts?
Comment: At structure (admin menu), there is a "Contact Forms" option where you can create new forms and is basically what I think you would need.
Comment: try https://www.drupal.org/project/business_rules
Comment: Business Rules are not working properly. I have try the module in 3 defferent installations  of drupal and every time I create a rules it directing to install drupal....
Comment: No , I want to do it automatically via Rules
Comment: See if this is of any help https://www.drupal.org/project/rules/issues/2852342  #3 gives a solution that seems related to your case
Answer: First, use the -dev version of Rules.
Second, always use the "Show a message on the site" action for testing. This is a LOT easier to debug than "Send email". You can use tokens in the message to test that the values are what you expect them to be, then when you get the right values you can use the email action with those same tokens in your email.
Third, always clear your caches after making changes to a rule.
Fourth, the issue queue contains many complete examples you can use. For instance, here is an example of how to show a system message when an "article" type node is created (from https://www.drupal.org/project/rules/issues/2852342). Try this you will see that "Node is of Type" DOES work to restrict the type - the message will never be shown if you create a node that is not an article:
uuid: c1b8486c-a96b-4f53-903a-8a08cb85355d
langcode: en
status: true
dependencies: {  }
id: test_rule
label: 'Test rule'
events:
  -
    event_name: 'rules_entity_insert:node'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: f8e466d6-51d6-41ea-93f1-34436470f3c3
  conditions:
    id: rules_and
    uuid: 7776a869-e0c6-4499-b09e-da727722213e
    conditions:
      -
        id: rules_condition
        uuid: 6bf893f5-7bcf-420c-9a62-7e1cb9a884f6
        context_values:
          types:
            - article
        context_mapping:
          node: node
        context_processors:
          types:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_node_is_of_type
        negate: false
  actions:
    id: rules_action_set
    uuid: f0bcccfd-685f-4a74-a4fd-0d36b540037a
    actions:
      -
        id: rules_action
        uuid: ec599dbc-cb40-448b-b37b-129d956c2eb7
        context_values:
          message: 'Test rule triggered {{ node.title }}'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message

And finally, here's a complete example for how to send e-mail to an address contained in a field value. This example assumes you have a node content type with machine name "email" which has a single-valued required field of type "email" named "field_email".
uuid: bc3fb7fd-0cbd-416c-8b71-9d6b710eb0ce
langcode: en
status: true
dependencies: {  }
id: send_email_when_content_of_type_email_is_created
label: 'Send email when content of type "email" is created'
events:
  -
    event_name: 'rules_entity_insert:node'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: 265d153c-9ce9-4250-a1b7-b8670be7826c
  conditions:
    id: rules_and
    uuid: 4f570c4e-3558-4628-96dc-aebb7b6d9e65
    conditions:
      -
        id: rules_condition
        uuid: 8014e5b0-680d-46c3-94fc-0785022447ca
        context_values:
          types:
            - email
        context_mapping:
          node: node
        context_processors:
          types:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_node_is_of_type
        negate: false
  actions:
    id: rules_action_set
    uuid: 25127564-6ab9-4587-b1b9-9336781aab9e
    actions:
      -
        id: rules_action
        uuid: 16f51441-39e8-4872-a3c2-e4e12a339f1e
        context_values:
          message: 'Email is {{ node.field_email.value }}'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message
      -
        id: rules_action
        uuid: 2c636fe9-9b9a-46b8-b930-81b9730f5ac2
        context_values:
          to:
            - '{{ node.field_email.value }}'
          subject: 'An Email node was created'
          message: 'An Email node was created'
          reply: ''
          language: ''
        context_mapping: {  }
        context_processors:
          to:
            rules_tokens: {  }
          subject:
            rules_tokens: {  }
          message:
            rules_tokens: {  }
          reply:
            rules_tokens: {  }
          language:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_send_email

If you import these Rules onto your site and inspect how they're constructed they will help you learn how to do this yourself.

Send email after content update


Passar valor de variável PHP dentro de laço while para javascript

Question: Possuo uma variável dentro de um código php com um laço while e preciso modificar essa variável $codigo dentro do javascript.
Essa variável $codigo recebe um número diferente a cada laço de repetição
data-toggle='popover1', data-toggle='popover2' ...

E esse valor precisa ser incrementado também ao javascript
 $('[data-toggle='popover1']'), $('[data-toggle='popover2']') ...

Segue o código:
$(document).ready(function(){
$('[data-toggle="popover<?php echo $codigo; ?>"]').popover({html: true});
});

<?php
$codigo = 1;
while ($codigo < 10) {
$codigo = $i;
$i++;
?>

<button type="button" class="btn btn-primary" data-toggle='modal' data-target='#Alt'>MODAL</button>

<button type="button" class="close" data-dismiss="modal">×</button>

<button id='id_codigo'
type="button" class="btn btn-primary"
data-position="top-left" title="Contato"
data-toggle="popover<?php echo $codigo; ?>"
data-placement="down" data-content="Nome: id='id_nome'

Endereço: id='id_endereco'

Contato: id='id_contato' ">Contato</button>

<?php
}
?>

Segue o código online
Comment: Explica direito qual o problema está enfrentando, o que você deseja de resultado e qual resultado está acontecendo atualmente.
Comment: Vou editar minha pergunta
Comment: Na realidade como essa variável está dentro de um laço de repetição e recebe um incremento a cada repetição, também preciso desse incremento no javascript, ou seja, preciso passar sempre o valor da variável php para o java script dentro desse laço de repetição.
Comment: Não da para fazer isso que você quer, manipular com o *Javascript* variáveis hospedadas em *PHP*. Existe uma distinção de camadas entre cliente(html) e servidor(php).É um ciclo o usuário faz a solicitação de uma página. O servidor inicia um código em *php* e quando **terminarem todas** as atividades em php o servidor devolve ao cliente uma página html e cessa sua atividade. O navegador recebe a página e a renderiza, dependendo das ações do usuário uma nova solicitação é enviada ao servidor. É um ciclo, ora o processamento está no cliente, ora o processamento está no servidor mas nnca nos dois.
Answer: Seguindo o seu modelo você pode fazer algo parecido com isto:
<?php
$i = 1;
while ($i < 10) {
    $codigo = $i;
    $i++;
    ?>

    <button type='button' title='Sem Contato' data-toggle='popover<?php print $codigo ?>'>Sem Contato</button>

    <?php
}
?>

O que fiz foi adicionar o mesmo <?php print $codigo ?> da linha acima. Eu sugiro aninhar isto de outra forma, por exemplo: Imprime todos os botões depois repete o loop imprimindo o JS separado.
Comment: No seu "código renderizado" deveria estar assim `$("[data-toggle='popover1']")` e não assim `$('[data-toggle='popover1']')`. Desculpe a pergunta que não precisa de resposta, você é iniciante em programação?! Se for, dá uma atualizada nos seus conceitos javascript e php, só releia alguns livros para fixar/masterizar o que cada um faz, assim você vai perder bem menos tempo com pequenas coisas. Exemplo, isto ai tá te tomando horas, se você ler dois livros, 1 por dia, você vai deixar de perder várias horas em pequenos trechos. Ou seja, a velha frase de algumas horas afiando o machado.
Comment: No caso pra passar o valor da variável pro javascript é dessa forma mesmo? Aqui não deu certo
Comment: Isto não passa o valor para o javascript, apenas "escreveu" um javascript, se olhar no código fonte renderizado verá que ficou `data-toggle='popover1'` `data-toggle='popover2'` etc. Para passar uma variável segue o mesmo esquema na declaração da variável `var variavelJS = ;`. Posta a necessidade do resultado final pra entender o que você quer.
Comment: Realmente preciso do passar o valor da variável em php pro javascript.
Comment: Então ficaria assim? data-toggle='popover´variavelJS´
Comment: Pronto editei a minha pergunta e fiz como eu gostaria que ficasse
Comment: Bom dia Carlos, então, como o @Augusto Vasques disse, são "camadas diferentes", ou seja, você não consegue acessar uma variável do PHP no javascript nem do javascript no PHP. O que dá pra fazer é escrever o código Javascript usando o PHP. E este código que te passei funciona pra isto, você verificou o "código fonte renderizado" ou seja, no navegador? Tem um detalhe ai que tá passando também é a repetição de aspas simples, se você abre aspas simples deve abrir aspas duplas internamente à primeira e assim sequencialmente, e vice-versa.
Comment: Isso sou iniciante. Obrigado pela resposta.


Just would like a quick explanation regarding Lower Darboux Sums

Question: On Example 1 in this following PDF:
http://home.iitk.ac.in/~psraj/mth101/lecture_notes/lecture15-16.pdf

Consider the function $f : [0, 1] \to \mathbb R$ defined by
  $f(1/2) = 1$ and $f(x) = 0$ for all $x \in [0, 1] \setminus \{1/2\}$

I am trying to accumulate alot of different answered questions in real analysis so that I can start to become more familiar with proofs. I found this PDF today which seems like a pretty good overview (since we are covering integration in class) but on the sheet he says that "For any partition $P$ of $[a,b]$, the $L(f,P)$ is $0$". How do we know this?
Comment: Please put all of the necessary information in the question itself. Don't expect people to read a 4-page PDF to answer your question.
Comment: Sorry I won't do it again.
Comment: No worries. I copied the example to the question this time. :)
Answer: The function $f$ is $0$ everywhere in $[0, 1]$ except for $1/2$. Thus, no matter what partition you choose, the infimum of $f$ will be $0$ in each interval in this partition. This is clear when for the intervals that don't contain $1/2$. For the interval that does contain $1/2$, it must also contain another point, and hence the infimum is also $0$.
Comment: Ah that makes sense. Thank you very much. It's not letting me accept the answer for another 6 minutes but I appreciate it.
Comment: @A.M.C Happy to help!
Comment: Note you could also define a partition of $[a,b]$ to be an ordered tuple $(x_0,x_1,x_2,\dotsc,x_n)$ with $a=x_0 \leq x_1 \leq \dotsb \leq x_n = b$, i.e. some of the $x_i$ could be equal. Then you could have $\tfrac12$ show up multiple times in your tuple at, say, $x_i$ and $x_{i+1}$ and thus $[x_i,x_{i+1}]$ wouldn't contain another point, but this isn't a problem as the length of the interval $[x_i,x_{i+1}]$ is $0$, so it doesn't contribute anything to $L(f,P)$


How do I get the amplitude and phase for sine wave from lm() summary?

Question: A simple sine curve could be written as $\text{amplitude}\cdot\sin(x+\text{phase})$. It can be also written in linear form as $a \cdot \sin(x) + b \cdot \cos(x)$.
I run my analysis with R as:
 fit.lm2 <- lm(temperature~sin(2*pi*Time/366) + cos(2*pi*Time/366))
 summary(fit.lm2)

Coefficients:
                       Estimate Std. Error t value Pr(>|t|)
(Intercept)             26.9188     0.1005  267.87  < 2e-16
sin(2 * pi * Time/366)   1.7468     0.1390   12.56  < 2e-16
cos(2 * pi * Time/366)   1.2077     0.1485    8.13 6.94e-11

The general form of the equation is $y = b_0 + b_1x_1 + b_2x_2$, thus, in my case, it can be written as $y = 26.9188x_0 + 1.7468x_1 + 1.2077x_2$.
If I were to write it back to the simple sine form, $\text{amplitude}\cdot\sin(x+\text{phase})$, is it correct to say that:
$\text{amplitude} = b_0 = 26.9188$
$\text{phase} = \arctan\left(\frac{b_1}{b_2}\right)$
Is this the correct way how to do it?
Comment: Assuming daily data, a divisor of 365.25 or so will be nearer the mark than 366 for a period of several years. You should not notice the difference, but still, there it is.
Comment: Thanks for adding that @Nick Cox. I will experiment it with my dataset.
Answer: The fit is
$$y = 26.9188 + 1.7468\sin(x) + 1.2077\cos(x).$$
Consider a general (non-zero) linear combination $\alpha \sin(x) + \beta\cos(x).$ Viewing $(\alpha, \beta)$ as a vector and writing it in polar coordinates $(r, \phi)$ yields
$$\alpha = r \cos(\phi),\quad \beta = r \sin(\phi), \quad r = \sqrt{\alpha^2+\beta^2}$$
whence
$$\alpha\sin(x) + \beta\cos(x) = r\cos(\phi)\sin(x) + r\sin(\phi)\cos(x) = r\sin(x+\phi).$$
$r$ is the amplitude and $\phi$ is the phase.  In the present case $\alpha=1.7468$ and $ \beta=1.2077$  entailing
$$r = \sqrt{ 1.7468^2+1.2077^2 } = 2.123641$$
and
$$\phi = \arctan(\beta, \alpha) =  0.6049163.$$
Consequently
$$y = 26.9188 + 2.123641 \sin(x + 0.6049163).$$
This can be checked by plotting.  Here is R code to do it:
b0 <- coef(fit.lm2)[1]
alpha <- coef(fit.lm2)[2]
beta <- coef(fit.lm2)[3]

r <- sqrt(alpha^2 + beta^2)
phi <- atan2(beta, alpha)

par(mfrow=c(1,2))
curve(b0 + r * sin(x + phi), 0, 2*pi, lwd=3, col="Gray",
      main="Overplotted Graphs", xlab="x", ylab="y")
curve(b0 + alpha * sin(x) + beta * cos(x), lwd=3, lty=3, col="Red", add=TRUE)

curve(b0 + r * sin(x + phi) - (b0 + alpha * sin(x) + beta * cos(x)),
      0, 2*pi, n=257, lwd=3, col="Gray", main="Difference", xlab="x", y="")

The two formulas agree to sixteen significant figures in double-precision arithmetic. The difference reflects pseudo-random floating point errors. (Because my data are not exactly the same as the original data, the "difference" plot will differ in its details but will still exhibit only tiny variations.)
Comment: Thanks a lot for your effort and time for producing a really comprehensive answer. Really appreciate it.