How to access web.xml init parameters in JSP

Question: I have stated my init parameter in web.xml and on accessing same in init.jsp I get output as null. I am using Tomcat-8
My web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
    <display-name>SecondWebProject</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>InitJsp</servlet-name>
        <jsp-file>/init.jsp</jsp-file>
        <init-param>
            <param-name>default_username</param-name>
            <param-value>default user</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>InitJsp</servlet-name>
        <url-pattern>/init.jsp</url-pattern>
    </servlet-mapping>
</web-app>

MY init.jsp is:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Init jsp</title>

 Default username is: <%= config.getInitParameter("default_username") %>

 Default username is: <%=
 getServletConfig().getInitParameter("default_username") %>

File structure within Eclipse is as:

I am not able to find where I am doing wrong. Any help from your side will be valuable..
Answer: Please Make sure u put the  jsp at proper place/path.
 I tested ur code(with tomcat7) & it is running fine, Only if i Put my jsp at correct path, path which is mentioned in web.xml
Check snapshot for reference, if place jsp directly under WebContent/init.jsp ,it will run fine otherwise results null(check the url in snapshots which results null)

Check the directory structure
Comment: thanks for replying, but I have placed _init.jsp_ at correct place. I have added the screenshot of file structure in my question.
Comment: right click the jsp and run on server, n show the coming url
Comment: It is now working. I first cleaned and then stopped Tomcat; on restart it worked. I don't know what was the actual problem, but this trick worked. Thanks for the effort :)
Comment: Good!! I thought of saying that, but i was cross checking at my end , as it was not running fr u even aftr evrythng luks fine,


How to execute update ($set) queries in MongoDB Compass tool?

Question: I'm new to MongoDB Compass tool and am trying to update a field in my collection. Please can someone suggest where the update query must be written. Could find no options or panes in the tool to write custom queries be it selection / updation for that matter.
In the Default Window only the selection/projection/restriction options are found.
Any help is much appreciated.
Comment: Almost 5 years later and this is still not possible unless using the shell
Comment: I'm also waiting for this feature. The shell simply does not cut it for entering queries and displaying results. It feels like this tool could be open sourced for the benefit of the company and users alike.
Answer: In the latest version, there is a "_MongoSH" in the bottom left corner of the window.
Thx to @Boštjan Pišler for the hint about a new feature.
Old answer:
I had the same issue, it looks like a simple feature to implement (since document updates are possible) but... AFAIK there is no such option in compass, you can do it through mongodb shell (CLI client).
Comment: Please refer comment from @Bostjan below, looks like there is a way now, although in beta.
Comment: Unfortunately, as of now the option for mongoshell is removed from compass.
Comment: @Mohamedabdelmagid i still see it in latest compass for Linux 1.39.2.
Comment: Oh, thanks, for pointing that out, it seems it was removed for version 1.39.1 on Mac, now that I upgraded it's there again.
Answer: The tool was recently updated with a shell (currently in beta) which is accessible by clicking the dark bar on the bottom of the window "_MongoSH"
Comment: I'm using compass for months and I realised it now, thanks.
Answer: At the bottom left, _MONGOSH:

There you can call updateMany and any other methods available in the MongoSH syntax
Worth to mention that before running your commands you may want to change the default DB by using use my-db-name:
use book-store-db
# now the variable `db` points to the book-store-db

db.getCollection("books").updateMany({"year":"2022"}, [{ $set: { "price":"0"} }])

Comment: worth to add that you need to write `use my-db-name` if the shell is not pointing to your desired db
Comment: Thanks @AnnetteC. I updated the answer to mention it.
Answer: You can use mongo MongoSH. Currently its in Beta.
Answer: Just move your mouse over a document and find a little pencil. You will enter in update mode. You can change fields, values, arrays, etc.
Comment: @Pat is obviously asking about a way to execute an update statement, e.g. `db.collection.updateMany()`


Standards on presenting graphs and charts in vector format?

Question: In his up-voted answer to Software needed to scrape data from graph, Alexey writes (with respect to the need for data scraping off of raster graphs) "But nowadays the good practice is to publish graphs in vector form."
To rip off my comment to Alexey from that page: Is there a good reference for best practices around which vector format(s) to present graphs of data in? For example, ought I use an eps encapsulation of an svg file in my LaTeX manuscripts, or am I supposed to output graph in LaTeX directly? Or something else?
Answer: Or make your data and code available using R, ggplot2 and knitr so it is fully reproducible. And then you can use the gridSVG package to create SVG versions of the ggplot2 plots.
Comment: GREAT! How about you edit your answer to make that more explicit, and possibly offer a link or two to the requested "best practices" or guidelines? Or create a how-to right here. :)
Comment: Making data and code available (I try to do both) does not really address the question, which was specifically about vector format graphs and charts.
Comment: It would be if you then also used the gridSVG package to create SVG versions of the ggplot2 plots


KNN does not take into account the actual magnitude of the distance

Question: Suppose I have 3 two dimensional points $(0, 0), (10000000, 0), (-1, 0)$ and $(0, 0)$ has label 1.0. If we were to use 1-NN to predict the label for $(10000000, 0), (-1, 0)$, then the answer for both are $1.0$. This does not make sense since the actual distance (Euclidean distance) from $(10000000, 0)$ to $(0,0)$ is way larger than the distance from $(-1,0)$ to $(0,0)$. How could their prediction result be the same? Intuitively, we should be more confident predicting the label of $(-1, 0)$ to be 1.0. Is there a way to reflect this confidence?
Answer: We actually should not be more confident in one of the label assignments because according to the assumption made by our learner, both label assignments are equally valid; for a $k$-NN classifier we $k=1$ we assign each unlabelled item to the class of its closest neighbour. That is because we rely strongly on the contiguity hypothesis: "items of the same class form a contiguous region and regions of different classes do not overlap."
For $k>1$, we assign each new item to the majority class of its $k$ closest neighbours with the rationale being that based on the contiguity hypothesis, an item will have the same label as the majority of other known items located in its neighbourhood. We can have a probabilistic output (i.e. quantification of confidence) based on the fraction each class. This brings back to the original example for $k=1$ presented by the OP. The prediction for both unlabelled points has to be the same because there is no other alternative.
As an immediate work-around, we could define some radius $d$ outside which there is no concept of neighbourhood. This would be akin to find use DBSCAN to label points as inliers or outliers and then use 1NN to classify inlier points only. More formally, there are methodologies like Hubness Information k-Nearest Neighbor (HIKNN (2009)) where all neighbours are not "treated equally" extending standard $k$-NN assumptions (and have subsequent impact to our outputs). There is also a reasonable literature on proximity graph methods for nearest neighbours (2020) if one wants to dig this deeper.
Comment: Thanks for answering. Even though I do have the hubness problem. However I cannot try to 'reduce' them because most of the points only have one same neighbor in the problem I faced. I want a method to penalize the estimate based on the distance. One quick thought would be cosine distance * estimate. However that only calculated $P(A = B) * \text{Prediction of B}$, which does not feel correct.
Comment: Happy to help. I think in this case one should move away from 1NN. It is a noisy method after all. And if as you say "*most of the points only have one same neighbour*" then it makes sense to question whether using a neighbour-based classifier even makes sense. Being informal: $k$NN are relevant in "smallish" ($<10$) dimensions that can be reasonably normalised.


Remover imagem de destaque do post

Question: Como faço para remover a imagem em destaque de uma publicação (imagem postada na postagem) sem removê-la da página inicial do site?
Nota: Tenho um site de imagens com citações e isso é altamente problemático porque desencoraja a publicação e ainda repete a mesma mensagem na imagem duas vezes na página.
Depois de consultar respostas para um problema semelhante, que dizia que o single.php do site deveria ser encontrado e remover algumas linhas, eu abrir um novo problema:
O tema Neutro wordpress que eu uso não possui single.php.
Alguma dicas?
Exemplo (minha página inicial) LINK
página com publicação e exemplo de imagem destacada exemplo
Answer: Você deve verificar o tipo de post selecionado na pagina de edição do post.
Caso ele seja um post padrão, você deve editar o arquivo "content.php" a imagem se encontra na linha 21.
Remova o código:

<?php if ( (function_exists('neutro_has_get_the_image') ? neutro_has_get_the_image() : '' ) ) if (comments_open() && !post_password_required())
    comments_popup_link('0', '1', '%','comment-counter'); ?>

    <?php $featured_image = neutro_featured_image_widths();
    if ( current_theme_supports( 'get-the-image' ) ) get_the_image( array( 'size' => $featured_image['size'], 'width' => $featured_image['width'], 'height' => $featured_image['height'], 'image_class' => 'featured-thumbnail', 'before' => '
', 'after' => '
' ) ); ?>

outros arquivos como:
content-aside.php
content-audio.php
content-status.php e etc...
Também podem conter esse mesmo código que puxa uma imagem destacada.
Espero ter ajudado!
Comment: Obrigado Gabriel, sua dica funcionou perfeitamente.
Comment: Obrigado vote na minha resposta.

Remover imagem de destaque do post


7 - How can I add a region inside another region?

Question: I'm surprised I can't find the answer to this online.
I'm currently creating a custom header for my drupal site, so I've created a custom_header region in the .info and a region--custom-header.tpl.php file. Inside the region, I need to add another region.
I've tried to print the other region inside the header region, but nothing is showing up.
Good practise or not aside, how can I do this?
Comment: Can't you change the position of region in `page.tpl.php`?
Comment: @SumitMadan Yes I could, and that works. but I have quite a number of page templates so I want to group all regions that belongs to the header inside the header region.
Comment: If you created any region that will need to be changes in every tpl file. May be this post can help you http://groups.drupal.org/node/195038.
Comment: No You cant do that.
Answer: You cant do it that way. But its drupal and it spread true love, so worry not, heres a solution.

Activate php filter under modules
Create a custom block
add <?php print views_embed_view(yourviewname, block); ?>
Comment: **Note:** This answer is perfectly valid, but there are risks with enabling PHP Filter, you can **[read about them here](http://drupal.stackexchange.com/questions/2509/what-are-the-downsides-of-using-custom-php-code-in-blocks-nodes-views-args#answer-2512).**
Answer: No You cant do that. Whatever use case you're looking for can be achieved through blocks
Answer: It's possible, but it'll get hacky and fragile. This sounds like a 'golden hammer' problem, a different tool would likely work better.
Have you considered using Panels or Display Suite to accomplish what you're doing? Panels are better if you want a more WYSIWYG type interface, Display Suite is better if you're comfortable coding.
Answer: If you don't want to mess with template files or lack coding skills, you can use
Panels

An Overview of Panels The Panels module allows a site administrator to create customized layouts for multiple uses. At its
core it is a drag and drop content manager that lets you visually
design a layout and place content within that layout. Integration with
other systems allows you to create nodes that use this, landing pages
that use this, and even override system pages such as taxonomy and the
node page so that you can customize the layout of your site with very
fine grained permissions.

With Panels, you can add more regions to your nodes.
With mini panels, you can add blocks with regions inside them.


Marshalling from C# to a DLL with a TCHAR** x[] parameter

Question: I am trying to call a Win32 DLL from some C#. The DLL function is declared as follows:
extern "C" __declspec(dllexport) UINT foo(TCHAR** list[], int& listSize, TCHAR* error);

In C#, I declare the external function like so:
[DllImport("foo.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
static extern uint foo(StringBuilder[] list, ref int listSize, StringBuilder error);

My problem has to do with the list parameter, which is an array of StringBuilder classes.
Some test code where I call the DLL function is as follows:
(Note: I realise that there are boundary checks missing, etc. At this stage, I am just trying to get things working).
// allocate a buffer for a possible error message being returned
StringBuilder error = new StringBuilder(1000);

// allocate buffers for the list of strings returned
StringBuilder[] list = new StringBuilder[10];
for (int i = 0; i < 10; i++)
{
    list[i] = new StringBuilder(1000);
}

int listSize = list.Length;

uint result = foo(list, ref listSize, error);

Passing the StringBuilder as a buffer for the error parameter, works fine. I can set its contents in the DLL as follows:
_tcscpy(error, _T("Something went wrong");

When the C# call to foo returns, the string error variable has the text we set it to in the DLL.
But, I cannot work out how to marshal the StringBuilder[] list parameter.
In the C++, I am able to set the contents of the list array:
_tcscpy((*list)[0], _T("First item"));
// and so on...

And, even though there is no crash that occurrs due to any possible problematic marshalling, the list in the C#, when the call to foo() returns, does not contain any of the strings we set in the C++.
I'm guessing that the problem is with the DllImport and how I've declared the list parameter should be marshalled.
By the way, the example DLL has a matching function which one would then call to deallocate the "TCHAR** list" returned by the example foo shown above.
Comment: `TCHAR** list[]`? Do you have an array of strings, or an array of an array of strings?
Comment: An array of pointers which point to pointers to TCHARs. Confusing, I know.
Comment: So why did you define the managed signature as `StringBuilder[]`? This is equivalent of `TCHAR **` I guess. But neither will work in your case :).
Comment: Well, maybe my definition is wrong too. It's all related to my problem, that I'm trying to get working.
Comment: For the error parameter, StringBuilder works well, and that's a TCHAR*. So, I assumed that for TCHAR** list[], that StringBuilder would be correct.
Answer: I have not done this in a while, but you should try the follwing in order to marshal the array list correctly:
Add a
[MarshalAs(UnmanagedType.LPArray, ArraySubType.LPTStr, SizeParamIndex=1)]
attribute to list, and you should add an out, since the data is allocated in C++ code.
Answer: OK, I have found a solution to my question. It looks like the answer lay in IntPtr. The C function created and returned an array of string in "TCHAR** list[]".
First, I changed the declaration in C# to:
[DllImport("foo.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)]
static extern uint foo(out IntPtr[] list, ref int listSize, StringBuilder error);

Then, when the call to the DLL returned, I needed to extract the strings from the array:
string[] returnedList = new string[listSize];
IntPtr[] ptrArray = new IntPtr[listSize];

Marshal.Copy(list, ptrArray, 0, listSize);

for (int i = 0; i < listSize; i++)
{
    returnedList[i] = Marshal.PtrToStringAuto(ptrArray[i]);
}

And that resulted in getting back the array of strings from the C DLL.
Comment: If this works then you have high odds for leaking memory, not getting the string buffers released.  Test this by pinvoking the function a million times and make sure that memory usage doesn't blow up.
Comment: The DLL has an associated function that the user needs to call to free the "TCHAR** list[]" returned by the aforementioned _foo_ example.
Comment: Do mention such details in a question.  That skips having us to wonder how such an api function could possibly work as intended and produces wrong answers that are not useful to anybody.


What's wrong with this interpretation of a 95% confidence interval?

Question: Note: I asked a version of this as part of another question, but I'm re-asking it as a stand-alone question with more detail.
I've been trying to come up with more intuitive/less confusing ways to accurately explain what a given (say) 95% confidence interval (e.g. "the 95% CI runs between 2.5 and 3.7") actually means. I know that it does not mean "there is a 95% chance that the true value is within this interval" (because the true value is not a random variable) but that it is correct to say that, "out of all possible 95% CIs that could have been calculated from these data 95% of them will include the true value." However, based on my interpretation of the Central Limit Theorem and frequentism, I believe the following statement should also be valid interpretation of a 95% confidence interval that ranges between A and B:
"if it were true that the true mean was the the value we actually estimated, and we replicated our study a 100 times, estimating the mean each time, then 95% of those estimates would fall between A and B."
I've been told this is wrong, but I just want to understand why it's wrong.
Here's my logic. Let me know if and where there is a problem.
(First off, to avoid having to talk about t distributions let's just say that all sample sizes in this discussion are large enough that the distinction between normal and t distributions is irrelevant).
We want to estimate some parameter $\mu$ in a given population. The CTL says that if we draw a large number of random samples from this population and generate an estimate $\hat \mu$ in each of them, these estimates will form a normal curve, with a particular standard deviation, centered on the true value  $\mu$. We therefore know, for example, that 95 percent of these estimates will be within 1.96 standard deviations of the true value. Of course, we only have one of these estimates, and we don't know how big the standard deviation of this sampling distribution actually is. However, we use the standard deviation $\hat \sigma$  of  $\hat \mu$ in the data we actually collected as an unbiased estimator and thus estimate the standard error as $\hat \sigma / \sqrt n$.
Now, let's assume for the sake of argument that $ \mu=\hat \mu$. (obviously this is unlikely to be the case, but it is analogous to the hypothetical we use when interpreting p values: "if the null hypothesis were true..."). Under this assumption the CLT tells us that if we again took repeated random samples, other estimates of $ \mu$ from those samples will be distributed normally around $\hat \mu$  (because $ \mu=\hat \mu$), meaning that 95% of those estimates will be within 1.96 standard deviations of $\hat \mu$. As noted above, we estimate the size of "one standard deviation" in the sampling distribution by the standard error. This allows us to can calculate the following
$$A=\hat \mu+1.96*SE$$
$$B=\hat \mu-1.96*SE$$
We can therefore say "if $\mu= \hat \mu$, and we replicated our study a large number of times times, estimating the $\hat \mu$ each time, then 95% of those estimates of would fall between A and B."
Of course, the formula I used was just the standard formula to calculate a 95% confidence interval around $\hat \mu$. So it seems like the sentence above should be a valid interpretation of a 95% confidence interval. If it's not, why not?
Comment: You might find the graphical analysis of confidence interval construction at https://stats.stackexchange.com/a/426994/919 to be enlightening.  Among other things, it shows conceptually that the CLT is irrelevant; normality is irrelevant; and lack of bias in estimates is irrelevant for understanding confidence intervals.
Answer: Your statement is imprecise in terms of true and estimated values, but not so much of the mean, but of the standard deviation.

if it were true that the true mean was the the value we actually estimated, and we replicated our study a 100 times, estimating the mean each time, then 95% of those estimates would fall between A and B.

Note that A and B depend on a single estimate of the standard deviation, namely the one from the original experiment. Your replications only estimate the mean, not standard deviations.
If your original experiment underestimated the SD, then replications will yield estimates of the mean that are contained in your original interval [A,B] in fewer than 95% of cases. If your original experiment overestimated the SD, your replicates will fall in the interval more often than 95%. And you will either under- or overestimate the SD with probability 1.
With whuber, the solution lies in keeping the CI calculation and a result from such a calculation (which is known as "a CI") strictly separate. A CI can only be interpreted as a particular result from a CI calculation. Yes, this is unintuitive. Unfortunately, there is simply no intuitive and correct interpretation of CIs.
Comment: "Unfortunately, there is simply no intuitive and correct interpretation of CIs." Intuition is subjective. For me the straight "in the long run, 95% CIs computed in this way from samples generated from the assumed model will contain the true parameter" is intuitive enough.
Comment: Ah, thank you, that does make sense. I had a hunch that the SD part of this was what was tripping me up, but wasn't sure. I guess this is why statisticians decided that the best way to describe these things was to just redefine the word "confidence" to mean something unintuitive and obscure, so that CIs *seem* intuitive to people who think the word means what it does in normal English (a statement about subjective belief).
Comment: *Unfortunately, there is simply no intuitive* and *correct interpretation of CIs* – sounds true...
Answer: The big problem with your statement ["if it were true that the true mean was the value we actually estimated, and we replicated our study a 100 times, estimating the mean each time, then 95% of those estimates would fall between A and B."] is that we want to make an inference about the true mean, whereas you are discussing a hypothetical application in which the true mean has a different value.
Regarding confidence intervals, to calculate a confidence interval you have already assumed a statistical model, say with random variable X, observed sample x, and random confidence intervals C(X) = [L(X, U(X)]. In short, the lower and upper limits bounce around from sample to sample but 95% of the possible intervals contain the true mean. Post-sample, my confidence interval C(x) = [L(x), U(x)] either does or does not contain the true mean. The genius of Neyman was to use the word "confidence" to explicitly acknowledge a different meaning than would obtain were the word "probability" used in place of it.
Suppose I compute a 95% confidence interval for the true mean. Given the assumed model, we state 95% confidence that the CI produced by my sample contains the true mean only because the assumed process (i.e., the model and C(X)) produces correct confidence intervals 95% of the time.
Sure, I don't know whether the observed CI is correct or not, but the 95% accuracy of the process that generated it is somewhat reassuring. Given the assumed model, either the observed CI contains the true mean or we have suffered a rare event [Note the past tense here.] In particular, our 95% confidence claim is neither a probability, nor a posterior probability, nor a belief. Note that there is nothing random left, the observed confidence interval either contains the true mean or it does not. By using the word confidence, we face up to that reality.
Had the degree of confidence been higher, say 99.9%, we would have been even more confident (because if it doesn't contain the true mean then it means I have suffered extreme bad luck [note past tense again] that occurs only 0.1% of the time).
There is an important caveat regarding such confidence claims. Confidence would be undermined if it was known that the confidence interval procedure that I was using had poor conditional properties. (There are a number of contrived examples that demonstrate this.) In such circumstances, it is better to base confidence claims on appropriate conditional probabilities rather than on the unconditional probability.
If you want an authority for why confidences are not the same as probabilities, the text Cox and Hinkley (1974) p. 227-228 spells out why confidences cannot be manipulated as if they are probabilities.
Comment: Good point about the idealised model, As Cox says, everything in statistics is provisional. I have edited my answer to say" Given the assumed model, we state 95% confidence that ..." I have changed the "I" to "we" regarding the claim as it is meant to include other (frequentist) statisticians using the same model. Other well-known frequentists are happy with the "we are 95% confident" format.
Comment: I don't like the wording "I am/we are 95% confident", because the 95% are a mathematical statement about a property of the CI under an idealised model; there is no necessary implication about my/your/our personal confidence. (Personally, in any real situation, I believe that the assumed model is not true and a true parameter value therefore does not exist, so for sure I'm not confident at all that this non-existing value is in the CI.)
Comment: For example, the (frequentist) statistician Kiefer's (1977) JASA article extended the confidence concept in a number of ways including to conditional confidence. He wrote, for example, "we are conditionally 96% confident that our decision is correct" p. 791. As you say, these confidences are not personal. Confidence claims are a consequence of the model selected and the sample only.


Remove "Payment method" tab in user profile

Question: Commerce don't give me any customize options for the user profile of the user,
I don't want the "Payment method" tab to appear in the user profile, how can I cleanly remove/disable this?
Can someone confirm me if it's work with tab tamer?
I read this issue: How to add / remove tabs from user profile?
But i can't use it because i have bootstrap barrio as theme and the module have a problem with barrio ...
Comment: Does this answer your question? [How to add / remove tabs from user profile?](https://drupal.stackexchange.com/questions/102810/how-to-add-remove-tabs-from-user-profile)
Comment: Specifically, see this answer: https://drupal.stackexchange.com/a/227991/5147  You'll need to add some code to a custom module to remove it if Tab Tamer doesn't work for your theme.
Answer: What about simply not granting the "Manage own payment methods" permission? That is a simple solution that doesn't require coding?
Answer: this is not a solution, if i change this permission the tab is is from the user profile removed, this is correct, BUT the problem of this permission change is that all users can't select anymore a payment method if they want to buy a product... it is not only for the user page... i solved it with a custom module, but it's sad that Commerce isn't mature enough to solve something like this without extra code either, I've been dealing with Drupal Commerce 2 since D8,D9 for 3 years now and I have to regret this decision... I have the feeling it will never really finished and it's nothing for simple users... the time I've invested... never again a shop with Drupal
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: So having to write a few lines of code means Commerce isn't mature enough? So what is your suggestion? We create an admin page to disable all routes defined by Commerce?

I've been dealing with Drupal Commerce 2 since D8,D9 for 3 years now and I have to regret this decision... I have the feeling it will never really finished and it's nothing for simple users... the time I've invested... never again a shop with Drupal

So all of this frustration just for a simple problem like this? As far as I know, no-one forced you to use Drupal Commerce... I'm here trying to help you and I'm getting a rant back... And then people complain when they don't get a timely answer...
Comment: I'm sorry, it wasn't meant to be a personal attack, but I've accumulated a lot in these 3 years... It's not your fault, this problem is harmless but I often get frustrated. All ok .. and thank you and the full team for the work on Commerce
Answer: I solved it simply in CSS. Drupal is often overcomplicated. Maybe not the "Drupal way" but outcome is the same:
<code>.path-user .tabs--primary a[href*="payment-methods"] {
    display: none;
}
</code>


Norm of Position Operator in $L^2[0,1]$

Question: I was wondering what is the norm of the position operator $Xf(x)=xf(x)$ in $L^2[0,1]$. I have two different results.

The first one is the simplest and the reasonable:
$$||X|| \overset{||f(x)||=1}{=}  \sup||xf(x)||=\sup||x||=1, $$
since $x\in[0,1]$.

The second method is the usual one I have always applied for L^2 opeartors:

$$||Xf(x)||^2=\left(\int_0^1xf(x)\text{d}x\right)^2\le\left|\int_0^1x^2\text{d}x\right| \left|\int_0^1f^2(x)\text{d}x\right|=\frac13||f(x)||^2 \qquad \implies \qquad ||X||=\frac{1}{\sqrt{3}}.$$
Both are different, and I am not able to find the mistake in the second method. Can you help me?
Thank you in advance :)
Comment: I think you're confusing yourself with notation.  If you think about the definitions used in the first approach more carefully, you should be able to see why it's wrong.
Comment: I am not able to see it.If there is no inconvenience, I would like to have an explicit answer.
Answer: The "mistake" is in both methods.
In the first one, you are mixing norms. The result is correct, though.
In the second, you have   $\|Xf\|_2^2=\int_0^1 x^2 f^2(x)$, and you cannot apply Cauchy-Schwarz.
The usual calculation is
$$
\|Xf\|=\left(\int_0^1 x^2 f^2(x)\,dx\right)^{1/2}\leq\left(\int_0^1 f^2(x)\,dx\right)^{1/2}=\|f\|,
$$
so $\|X\|\leq 1$. Further for each $\delta>0$ you can find $f$ with $\|Xf\|\geq(1-\delta)\|f\|$, proving that $\|X\|=1$.
Comment: Right. In the first method $||x||$ is $|x|$.
Comment: In the second method, I forgot to squared $xf(x)$. That is true. Thank you very much.
Comment: No, it's not just that. In the first method you are treating the norm as if it was the infinity norm, when it should be the $2$-norm. So, you cannot conclude directly, from $\|f\|=1$, that $\sup\{\|xf\|:\ \|f\|=1\}=\sup\{|x|:\ x\in [0,1]\}$. You need to do as I mention in the answer.

Norm of Position Operator in $L^2[0,1]$


Bound for graph's size with cycles

Question: I have the following problem:

Let $G$ be a simple graph with $n$ vertices and such that every cycle in $G$
  has length $\leq3$. Then $e(G)\leq\dfrac{3(n-1)}{2}$.
  (where $e(G)$ is the number of edges of the graph $G$)

I think it could be a good idea to prove this by induction, but do not know how to use the bound for the length of the cycles.
Comment: I don't understand, if graph is simple how can it have 2 cycle? Or I don't understand the term simple.
Comment: Simple means that the graph is undirected, unweighted and is not a multigraph (graphs with more than one edge between vertices)
Comment: So the only cycles wich are possible are 3-cycles?
Comment: Yes, that's correct. Because 2-cycles will mean that 2 vertex are joined by 2 edges, and we do not allow them here.
Answer: Suppose graph has 3-cycles $C_1,C_2,...C_k$ and $\varepsilon$ edges. Each cycle has 3 edges and because of condition that each cycle is of length 3 every edge is in at most one 3-cycle. So we have $$   k\leq {\varepsilon\over 3}$$
Suppose graph has spanning sub tree $T$ which has exactly $n-1$ edges. Then each edge which is not in $T$ (we have $\varepsilon -n+1$ of those) must be on exactly one 3-cycle. But we can't have more those edges than the 3-cycles. So we have
$$ \varepsilon -n+1\leq k \leq {\varepsilon\over 3} \Longrightarrow \varepsilon \leq {3n-3\over 2} $$
Comment: For greater generality, we can let $T$ be a full spanning forest (the union of spanning trees on each connected component). This still has at most $n-1$ edges (fewer if the graph is not connected) and is still a maximal acyclic subgraph.
Comment: Yes, yes, I assumed graph is connected. But if not you can proceed as you said.
Comment: @JohnWatson, when you say "Then each edge which is not in T (we have $\epsilon - n +1$ of those) must be on exactly one 3-cycle", I do not see why this is true.
Comment: Say we have an edge $AB$ which is on two 3-cycles, say $ABC$ and $ABD$. But then we have a 4-cycle $ADBC$. It is exactly the same argument as I had when I count the number of all possible 3-cycles.
Comment: Yes, I understand that if one is in two 3-cycles, you have a 4-cycle; but why having those edges in $T$ makes them unable to be on a 3-cycle. You can have a spanning tree with edges that belong to a cycle, can't you? I do not see the implication "edge in tree" $\rightarrow$ "edge not in cycle".
Comment: But I was looking relation with edges not on the tree and the cycles. I'm not interesting what is happening with the edges in the tree.
Comment: Why can't we have more edges that aren't in $T$ than 3-cycles?
Comment: EDIT: I saw that. It is because every edge that is not in the tree is exactly in (only) one cycle, so there cannot be more edges than cycles.
Comment: Could it be that the graph do not have a spanning sub tree with $n-1$ edges? Or you can always find one?
Comment: If it is connected you can do this always.

Bound for graph's size with cycles


The uniform measure on $A^{\mathbb{Z}}$

Question: Let A be a finite set and consider $A^{\mathbb{Z}}$. A is equipped with the discrete topology and $A^{\mathbb{Z}}$ with the associated product topology.
By $\mu_u$, denote the uniform measure on $A^{\mathbb{Z}}$.
Now my question is: How is $\mu_u$ to be understood i.e. how it is defined?
I guess it is something like giving same weight to each configuration, whatever that weight is. But whats the topological support of this measure? Maybe whole $A^{\mathbb{Z}}$ is the support?
Edit:
Sorry, now I found in the text linked in the comment what is meant (on p. 4):
Let $[u]_t:=\left\{x\in A^{\mathbb{Z}}: x_t=u_1,\ldots,x_{t+\lvert u\rvert}=u_{\lvert u\rvert}\right\}$, i.e. this is a cylinder set. And then
$$
\mu_u([u]_t)=1/\#A^k
$$
if $u$ is of length $k$.
I know this measure under the notion Bernouilli-measure.
But one questions remain: What is the support of this measure? All cylinder sets?
Comment: Where did you see this referenced?
Comment: I saw this here :http://arxiv.org/pdf/math/0312136.pdf on page 15 below the formula for $h_{\text{Top}}(F)$.
Comment: The support is $A^{\Bbb Z}$.
Answer: If $F\subset\Bbb Z$ is finite then $A^F$ is a finite set, so there is a uniform probability measure $\mu_F$ on $A^F$; that's the measure that assigns the same measure to each point.
And there is a natural projection $\pi_F:A^{\Bbb Z}\to A^F$. The uniform measure $\mu_u$ is defined by $$\mu_u(\pi_F^{-1}(S))=\mu_F(S)\quad(S\subset A^F).$$

Asking whether the support is the set of all cylinder sets makes no sense; if $\mu$ is a measure on $X$ then the support of $\mu$ is a subset of $X$, not a subset of $\mathcal P(X)$.
Here the support of $\mu_u$ is $A^{\Bbb Z}$. That follows from the definition of the support of a measure, since if $V\subset A^{\Bbb Z}$ is a nonemmpty open set the definition above shows that $\mu_u(V)>0$.
Comment: I am wondering what might be $F$ here.
Comment: ??? Read again - I said what $F$ is.
Comment: Sorry, I meant what F is in the linked text from where I got the issue.
Comment: Ah, I found it. I'll add it to my answer.

The uniform measure on $A^{\mathbb{Z}}$


How do I change the sound of the Instrument Sytrus / preset "Angelic whistle" so it doesnt deafen you?

Question: I have a song and I want to use a whistle for a secondary melody it has. I chose the instrument Instrument Synth Classic / Sytrus / preset "Angelic whistle". The problem is the sound is too sharp I guess, and it deafens you when you listen it. I've heard songs where they used whistles and they werent annoying at all. How can I set that instrument in FL Studio so it doesnt deafen you when you listen it?
Comment: You can also use a channel EQ to reduce the high frequencies.
Comment: Set the mixer level
Comment: Try monitoring your whole mix at a lower volume.
Answer: The "Angelic whistle" preset is simply a sine wave with unison, vibrato, and reverb.  EQ will not do anything useful.  Turn the volume down.  Consult the FL Studio manual if you are not familiar with the volume controls.
Comment: I did that, I turned the volume down for that sound, it seems to be ok


Is there a terminating state in UPPAAL?

Question: How can I create a "terminating" state in UPPAAL? If there is no edge from a state the execution will stop with deadlock. If the state has a loop without any guard the execution has never stopped. What is the best way to stop the Simulator execution without deadlock (if there is)?
Comment: Timed automata do not have designated terminal state, so the question starts with wrong assumptions. The simulator is meant for model validation. If the model contains a loop then the correct simulation will not terminate. Verification on the other hand, may terminate when the property of interest is proven (some state of interest is reached, or the verifier detects a loop, or verifier detects that the state space was searched exhaustively).
Comment: Surely the manual covers that?
Comment: I did not find the answer in the manual.
Comment: Then can you please update your question to say what you looked for in the manual? It's always a [good idea](/help/how-to-ask) to make sure that you mention what you already tried, including that you searched and what for, so that it's clear how detailed an answer needs to be when someone who might be able to answer sees your question.
Answer: No there isn't any specific terminating state.
Check out the comments below the question for more details.

Is there a terminating state in UPPAAL?


Android .jar file requires referenced project to be opened

Question: I'm very confused about adding external .jar files to my project.
I downloaded https://github.com/chrisbanes/Android-PullToRefresh library project.
After importing it to Eclipse, I cleaned & built it.
After that, in the bin/ folder of the library project, there is a .jar file.
Next I copied this .jar file to the /libs directory of my project from which I want to reference it.
As far as I understood, from now on there is no need to keep the library project in my workspace, because i added the .jar file to my project.
Picture of the projects tree:
https://www.dropbox.com/s/7w4tzis8v1vv4aj/jarProblem.png
When I'm running the referencing project with the library project open : no issues.
As soon as i close the library project: NullPointerException <- seems not to find the library.
I already tried every possible combination of build path configuration but I can't get my main project to be built with the pulltorefresh project closed.
I thought it was the sense of a .jar file to distribute a library without having to attach the source files.
It should work the same as the android-support-v4.jar ... for which i don't have the source code either.
What am I missing here ? Thank you.
Answer: There's a difference between a jar file and a library project.
Jar files can contain only code, no android resources.  These just need to be placed in your libs folder and linked in.
Library projects can contain Android resources.  They need to be compiled as Android libraries in Eclipse, and kept around as their own project.  You then tell your main project that it references this one.  Its necessary to keep the library project around because it needs to build the /gen files from it for your resources to be right.  It also needs to be able to grab the contents of its assets folder.
Given that this library has a res folder, its an Android library project and can not be used as a simple jar.


Estimated Time of Completion given Progress and Elapsed Time

Question: Say I have some task that I have spent an hour on, and I am 33% done. It should take me 3 hours to complete this task. Another task may be 50% done, and I have spent 3 hours on it. That should take a total of 6 hours. What is that equation?
Something like time_remaining = f(percent_done, time_spent)
Answer: Since
 time used  =  percent done * total time

you want
total time = (time used)/(percent done)

If you want the remaining time
time remaining = total time - time used

               = time used * (1/(percent done) - 1)


dojo: A gap between dijit.layout.BorderContainer and its child

Question: I followed the following site to do some layout in dojo:
http://dojotoolkit.org/documentation/tutorials/1.7/dijit_layout/
The problem is there's gap between BorderContainer and its children. How to eliminate them?
Answer: Set the gutters attribute to false.
new BorderContainer({
    ...
    gutters: false
});


non Lebesgue measurable set with empty interior?

Question: Let E a set contained in R with non-empty interior.
Then i know that it can be seen as the countable union of open disjoint intervals and every intervals has positive measure. So, there exist a subset of E s.t. is not Lebesgue measurable (Vitali-set like).
But if E has EMPTY INTERIOR?
I think that, due to the fact that Lebesgue measure has no atom, necessarily the measure of E is zero, so there is no non-measurable subset. Is it correct my idea?
Answer: Every set of positive measure in $\mathbb R$ contains a non-measurable subset. [See https://math.stackexchange.com/questions/2079436/does-every-non-null-lebesgue-measurable-set-contain-a-non-measurable-subset?rq=1 ]. If $C$ is  fat Cantor set then $C$ has no interior but there is a non-measurable subset.
Comment: yes, you are right. I hadn't thought of the generalised Cantor set. But the first part (E with non-empty interior) is true right?
Comment: Just to specify, the error in my proof is that empty interior does not imply measure zero if i correct understand
Comment: @maru0032 That is right. Fat Cantor sets have empty interior but they don't have measure $0$.
Comment: @maru0032 If $E$ has non-empty interior then it has positive measure so it contains a non-measurable subset.  But your argument is not  correct. Just because $E$ contains an interior point you cannot say that $E$ is an open set. If it is not open you cannot express it as a  union of open intervals.


Como ajustar margens no R markdown

Question: Estou criando um documento no R Markdown, mas quando vou gerar o markdown ele ocupa toda a área do navegador, ficando ruim a leitura. Gostaria de saber como ajustar as margens, para que ele crie uma barra de rolagem, mas respeitando um espaço de margem à direita e à esquerda.
Comment: Infelizmente, esta pergunta não pode ser reproduzida por quem for tentar respondê-la. Por favor, [dê uma olhada neste link](https://pt.meta.stackoverflow.com/questions/824/como-criar-um-exemplo-m%c3%adnimo-reproduz%c3%advel-em-r) e veja como fazer uma pergunta reproduzível em R. Assim, as pessoas que desejarem te ajudar conseguirão fazer isto da melhor maneira possível.
Answer: Inclua abaixo do YAML o código abaixo (O YAML é o cabeçalho do RMarkdown):
<code><style type="text/css">
.main-container {
  max-width: 90%;
  margin-left: auto;
  margin-right: auto;
}
</style>
</code>

Como ajustar margens no R markdown


Lockar SELECT quando faço um UPDATE - SQLServer

Question: Vou dar um exemplo do que estou fazendo, mas a pergunta mesmo está no final.
Tenho uma tabela com 4.100.000 registros e estou criando um robo que lê esses dados e exporta para o MYSQL(não entra em pauta, apenas para ambientar).
Eu tenho duas colunas BIT, uma se chama processing e a outra migrated, num loop infinito executo esse comando
SELECT TOP 100 Title,Tamanho,Caption,dataHoraIndexacao,Date,Resolucao,Base,Altura,orientacao,codigo,NomeArquivo FROM migracao.Reuters WHERE processing = 0 and migrated = 0

Pretendo executar varios robos ao mesmo tempo para poder agilizar o processo, a questão é, quando eu faço o SELECT logo após a população da minha List no c#, eu dou um update em todos os itens como processing = 1 e isso leva um tempo, imagine que enquanto dou o UPDATE um outro robo da um SELECT e retorna os mesmos dados que eu estou dando UPDATE, ou seja informações duplicadas.
A pergunta é: Como lockar uma tabela enquanto dou um UPDATE na mesma?
Comment: Editei a pergunta , na verdade é quando dou um UPDATE e não um SELECT
Answer: Se quiser bloquear a tabela para escrita até o término de uma transação use:
Code Snippet
SELECT * FROM TABELA (HOLDLOCK)

Se quiser bloquear a tabela para leitura e escrita até o término de uma transação use:
Code Snippet
SELECT * FROM TABELA (XLOCK)

Lembre-se de que impor bloqueios a tabela inteira poderá diminuir a concorrência e introduzir lentidão em seu banco de dados (mais processos terão de esperar até que o bloqueio da tabela termine).
Comment: Marcelo,preciso lockar a leitura até o momento em que eu finalizar o UPDATE, mas enquanto isso haverão INSERTS rolando em outros processos, SELECT pode esperar tranquilo, a melhor opção seria (XLOCK)  então, correto?
Comment: Acredito que sim, Leonardo. Mas o melhor mesmo é testar os dois e ver qual se adequa melhor a sua necessidade.


Eliminate Views Entity Reference Duplicates. I have some titles the same on purpose

Question: I have a view with an entity reference pulling in what I need from a content type. There are, on purpose, titles that are the same.
Is there a way to compare what is output and then only show one of the titles?
I am showing these in a select list.
This is not duplicates, as they are separate entries... so using the Query Settings > Distinct isn't the correct solution in my case.
Answer: You can use hook_views_pre_render to get at the results array before it is output to the screen.
e.g.
<code>function my_module_views_pre_render($view) {
  if ($view->name == 'the machine name of the view') {
    foreach ($view->result as $result) {
      // do some kind of comparison and de-duplification
    }
  }
}
</code>


Proof that $\sum \limits_{k=3}^\infty k\left({\frac{5}{6}}\right)^{k-3} =48 $

Question: I have this problem
Proof that
$\displaystyle\sum_{k=3}^\infty k\left({\displaystyle\frac{5}{6}}\right)^{k-3} =48 $
I tryed this:
$\displaystyle\sum_{k=3}^\infty k\left({\displaystyle\frac{5}{6}}\right)^{k-3} = \displaystyle\sum_{k=1}^\infty k\left({\displaystyle\frac{5}{6}}\right)^{k-3} - \displaystyle\sum_{k=1}^2 k\left({\displaystyle\frac{5}{6}}\right)^{k-3} = \displaystyle\sum_{k=1}^\infty k\left({\displaystyle\frac{5}{6}}\right)^{k-3}-3.48 $,  Now
$\displaystyle\sum_{k=1}^\infty k\left({\displaystyle\frac{5}{6}}\right)^{k-3} = 1*\left({\displaystyle\frac{5}{6}}\right)^{-2} + 2*\left({\displaystyle\frac{5}{6}}\right)^{-1}+ 3*\left({\displaystyle\frac{5}{6}}\right)^{0} + .........
 = \left({\displaystyle\frac{5}{6}}\right)^{-2}(1+2*\left({\displaystyle\frac{5}{6}}\right)^{1}+ 3*\left({\displaystyle\frac{5}{6}}\right)^{2} + .....)$
Let $x=(5/6)$
\begin{eqnarray}
1+2x+3x^2+4x^3+\dots = 1 + x + x^2 + x^3 + \dots \\
+ x + x^2+ x^3 + \dots\\
+ x^2 + x^3 + \dots \\
+x^3 + \dots \\
+ \dots \\
=1 + x + x^2 + x^3+\dots \\
+x(1+x+x^2+\dots) \\
+x^2(1+x+\dots)\\
+x^3(1+\dots)\\
+\dots \\
=(1+x+x^2+x^3+\dots)^2=\frac{1}{(1-x)^2}
\end{eqnarray}
then
$\left({\displaystyle\frac{5}{6}}\right)^{-2}\left({\displaystyle\frac{1}{1-5/6}}\right)^{2}= 51.48$ finally
$\displaystyle\sum_{k=3}^\infty k\left({\displaystyle\frac{5}{6}}\right)^{k-3} =51.48-3.84 = 48$
Am I right??
Thanks for your help :)
Answer: HINT:
If we are allowed to use Calculus,
we know  $$\sum_{0\le r<\infty}a t^r=\frac a{1-t}  $$ if $|t|<1$
Differentiate both sides wrt $t$  and then multiply by $t^{-4}$

Alternatively, we can use Arithmetico-geometric series formula  to show that $$\sum_{0\le r<\infty}rat^r=\frac a{1-r}+\frac r{(1-r)^2}$$
Now divide either sides by $t^4$
Comment: On your second last line, you need $S(1-x)$ instead of just $(1-x)$.
Answer: The crux of your proof -- that
$$ \sum_{n=0}^{+\infty} n x^{n-1} $$
factors as
$$ \sum_{n=0}^{+\infty} (n+1) x^{n} = \left( \sum_{n=0}^{+\infty} x^{n} \right)^2 $$
does indeed look correct.
It might be good to translate your argument into ordinary summation notation:
$$\begin{align}
\sum_{n=0}^{+\infty} (n+1) x^{n}
&= \sum_{n=0}^{+\infty} \sum_{m=0}^n x^{n}
\\&= \sum_{m=0}^{+\infty} \sum_{n=m}^{+\infty} x^n
\\&= \sum_{m=0}^{+\infty} x^m \sum_{n=0}^{+\infty} x^n
\\&= \left(\sum_{m=0}^{+\infty} x^m\right) \left( \sum_{n=0}^{+\infty} x^n \right)
\end{align}$$
Can you see how your argument corresponds to this calculation?
(this sort of calculation doesn't work in general: specifically where I swapped the order of the two sums. But power series, geometric series, and sums of positive numbers are all very nice and allow natural things like this to work)


Retrieving the code inside a 'with' statement

Question: INGORE THIS QUESTION
I clearly didn't explain well at all and none of the answers seemed to be on-topic for what I had in mind.

In the example shown below, I am trying to make a more concise loop where it will eventually look like l(n), l*n or something similar.
In the example shown, the code will print "hello" 5 times (or whatever I set it to be) and then execute the code within the with loop, which is not unexpected.
However, the idea is the loop the code shown (pass in this case). How can I replace print("hello") with the code written within the with statement? Is it possible? I suppose that this isn't what a with statement should be used for so is there an alternative?
class loop:
    def __init__(self, loops):
        self.loops = loops
    def __enter__(self):
        for x in range(self.loops):
            print("hello")
    def __exit__(self, *args):
        pass

with loop(5):
    pass

EDIT:
Here is the edited code since I don't think I stated clearly enough what I was trying to do:
class loop:
    def __init__(self, loops):
        self.loops = loops
    def __enter__(self):
        pass
    def __exit__(self, *args):
        pass

with loop(5):
    print("This will loop 5 times")

with loop(10):
    print("This will loop 10 times")

So at any point in the program I could simply type the bottom two lines with any code and it would work. Could I make this work?
Comment: Why not `for _ in range(5):`?
Comment: Override `__nonzero__` and do `while loop(5):`
Answer: I would avoid creating a class at all if you just want a  concise loop.
def loop(n):
    for _ in range(n):
        print("Hello")
        # Or whatever you want

loop(5)

Answer: I don't think you can loop through the code inside with block.
The closest thing would be to pass lambda as a second parameter.
class loop:
    def __init__(self, loops, action):
        self._loops = loops
        self._action = action
    def __enter__(self):
        for x in range(self._loops):
            self._action()
    def __exit__(self, *args):
        pass

def f():
    print("hello")

with loop(5, f):
    pass

Though you don't need with at all in this case:
def loop(n, f):
    for _ in range(n):
            f()

def my_printer():
    print("hello")

loop(5, my_printer)

Also I would avoid creating you own methods for loops, language already has built in syntax to create loops, just you it directly:
def my_printer():
    print("hello")

for _ in range(5):
    my_printer()

Comment: I would reject any code like this I saw in a code review.
Comment: No, the question was how to access the body of a `with` block from the context manager (which you cannot do). This is a workaround, but that doesn't mean one should write code like this.
Comment: Is it possible for you to elaborate on the answer? This just provides a solution but does not really help the user understand why it works.
Comment: @Enthus3d It is just slightly modified code provided in the question. From my perspective it is pretty straightforward and doesn't need any explanations. You you think it needs explanation, feel free to modify the answer, stackoverflow allows to to that and I think even encourages.
Comment: @chepner  I would also block such code in review (but not "reject" though as it means something different). Though I believe the question was about how to pass function as a first class object into `loop` for the purpose of learning.
Comment: I wouldn't go so far as to edit your answer for that, I am just pointing it out so you're aware that people may find it less friendly if you give a code block without explanation, as it makes them look for the differences themselves, and could confuse them.
Comment: I agree that your answer is definitely adequate for answering the asker's question, and it's clean code, I just think it could have been better if you had given an explanation.
Comment: @Enthus3d I updated the answer. Have just noticed he wants to use `with` body to loop over. I don't think Python allows to call body directly.
Comment: @chepner Yep. The code is bad. But the question was not to assess the code quality. I believe it is more for learning purposes to find you what you can do with Python.
Answer: Don't use a loop.
def loop(n):
    for _ in range(n):
        print("Hello")
loop(5)
Then this will print "Hello" 5 times.
Comment: Is there a way to do it more 'dynamically' for example a module that you can import that will allow it? Defining a function defeats the point of reducing the amount of code written.
Comment: for _ in range(n):
Comment: print(" Hello ")
Comment: @Doot Your `with l(n):` would only save 8 characters over `for _ in range(5)`, ignoring the code you would have to write to *define* `l` in the first place. Python already provides a concise, *obvious* way to do what you want.
Comment: Listen to Chepner^^^
Comment: I have updated the question as functions would not be much better than a for loop, as chepner said


Accept two parameters with same name?

Question: I have this code now
public ActionResult Index(Guid? id, string alias)
{
    var room = db.Rooms.FirstOrDefault(r => r.RoomLink == id || r.Alias == alias);

    if (room != null)
    {
    //some code with room...
    }
}

My goal is to accept two kinds url (parameters) in my action.
String
www.example.com/Rooms/Aliasstring

Guid
www.example.com/Rooms/387ecbbf-90e0-4b72-8768-52c583fc715

I have id in routes so alias is always null.
Would be nice if I could do it like this (if parameter is a Guid OR parameter is a string OR both Null)
public ActionResult Index(Guid? id, string? id)
{
    var room = db.Rooms.FirstOrDefault(r => r.RoomLink == id || r.Alias == id);
}

But I can't have two id's as parameter.
Routes
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

My model
public Guid RoomLink { get; set; }
public string Alias { get; set; }

Answer: You can avoid your problem with routing by means of simple checking your the input parameter
public ActionResult Index(string input)
{
    Guid guidOutput;
    bool isId = Guid.TryParse(input, out guidOutput);
    bool isAlias = !isId;

   var room = isId ?
              db.Rooms.FirstOrDefault(r => r.RoomLink == input) :
              db.Rooms.FirstOrDefault(r => r.Alias == input);

}

Accept two parameters with same name?


What are some important (discrete) theorems involving (abstract) simplicial complexes

Question: I am interested in looking for some (preferably discrete) theorems involving simplicial complexes.
To elaborate, by discrete I mean the opposite of continuous, which are those theorems relating to continuous maps/topological spaces.
Most books I read introduce simplicial complexes as a means to do simplicial homology etc, hence they don't have many theorems devoted to simplicial complexes themselves.
Thanks. Pointing to a reference will be great too.
Answer: There are many theorems "devoted to (abstract) simplicial complexes". Here are a few examples:

The Kruskal–Katona theorem, characterising $f$-vectors of simplicial complexes.
The Alexander duality for simplicial complexes.
Stokes Theorem for simplicial complexes.
de Rham's Theorem for Simplicial Complexes.
Erdős-Ko-Rado Theorem for Simplicial Complexes.
Comment: Thanks! This helped me a lot.
Comment: @yoyostein You are welcome!


Javascript error while dropping balls

Question: I wrote a javascript code to drop in ball multiple times when clicked on canvas. It is an experiment.
Here is the code:
HTML

<canvas id="myCanvas1" width="134px" height="331px" onclick="draw(0)"></canvas>
<canvas id="myCanvas2" width="134px" height="331px" onclick="draw(1)"></canvas>
<canvas id="myCanvas3" width="134px" height="331px" onclick="draw(2)"></canvas>

JAVASCRIPT
    var balls = [[], [], []],
    canvases = document.getElementsByTagName('canvas'),
    context = [],
    interval,
    boxWidth = 150,
    ballRadius = 10,
    canvasHeight = 235;
for (var i = 0; i < canvases.length; i++) {
    context.push(canvases[i].getContext('2d'));
}

function draw() {
    var movement = false;
    for (var i = 0; i < 3; i++) {
        context[i].clearRect(0, 0, boxWidth, canvasHeight);
        for (var j = 0; j < balls[i].length; j++) {
            if (balls[i][j].y < balls[i][j].yStop) {
                balls[i][j].y += 4;
                movement = true;
            }
            context[i].beginPath();
            context[i].fillStyle = "red";
            context[i].arc(balls[i][j].x, balls[i][j].y, ballRadius, 0, Math.PI * 2, true);
            context[i].closePath();
            context[i].fill();
        }
    }
    if (!movement) {
        clearInterval(interval);
        interval = null;
    }
}

function newBall(n) {
    console.log('new ball', n);
    var last = balls[n][balls[n].length - 1],
        ball = {x: ballRadius, y: ballRadius, yStop: canvasHeight - ballRadius};
    if (last) {
        if (last.x < boxWidth - ballRadius * 3) {
             ball.x = last.x + ballRadius * 2;
             ball.yStop = last.yStop;
        } else {
             ball.yStop = last.yStop - ballRadius * 2;
        }
    }
    balls[n].push(ball);
    if (!interval) {
        interval = setInterval(draw, 10);
    }
}

But balls aren't dropping in. Please tell me that where am I wrong so that I can fix it...
Comment: I had to set an epic title so that it can lure people ;)
Comment: this question title is so epic :D till you come in here and actually read it :P
Comment: Vote up this question so that I can mark question as complete
Comment: you can always pick correct answer no ?
Comment: I can't, unless I have repo points
Comment: Yes you can. Click the checkmark next to the answer.
Answer: balls is [] when the loop starts. So balls[0] is undefined, and thus has no property length.
Comment: Vote up this question so that I can mark question as complete
Comment: Set ```balls``` to something other than ```[]```. Maybe a list of objects with ```x``` and ```y``` properties?
Answer: Your code is always looping from 0 to 3. However, at first, there is no ball around. When you try to reach balls[0], balls[1] and balls[2], you get undefined error.
What you have to do is to change the loop to:
for (var i = 0; i < balls.length; i++)

or if you do not want to change the loop, you can initialize 3 balls at the start:
balls = [ball1, ball2, ball3];

where ball1, ball2 and ball3 are defined as how your ball data type is.
EDIT:
As I understand, you have some number of contexts, and for each context, you want to have a list of balls so that you can draw them.
Then:
balls = []

for (var i = 0; i < canvases.length; i++) {
    context.push(canvases[i].getContext('2d'));
    balls.push([]);
}

and use the remaining code same.
Comment: I did it and it returned another error: `Uncaught TypeError: Cannot read property 'clearRect' of undefined` at the line  `context[i].clearRect(0, 0, boxWidth, canvasHeight);`
Comment: Since you have only 3 contexts, it gives an error again. If having 3 balls is the only case for you, then please try to initialize 3 balls at start.
Comment: You don't call `newBall(n)` function. Change onclick events from `draw(0)` to `newBall(0)`.
Comment: I did it, but balls aren't dropping in
Comment: Vote up this question so that I can mark question as complete.

Javascript error while dropping balls


What is $R$-algebra and do I need to understand $R$-modules for it?

Question: I was given the following definition of $R$-algebra:

Let $R$ be a commutative ring. An $R$-algebra is a ring $A$ (with $1$) together with a ring homomorphism $f : R \to A$ such that

$f(1_R) = 1_A$;
$f(R) \subset  Z(A)$, where $Z(A)$ is the center of $A$.

The pair $(A, f)$ will also be called an $R$-algebra.

As far as I can see from googling, it's not the usual way to define it. Almost everyone does it via $R$-module.
I'm fairly new to algebra, in fact, I'm taking a second linear algebra course and the professor digresses quite a bit. So if possible, I'd like to understand what $R$-algebra is without getting too much into other topics.
Is it possible to develop a feeling for $R$-algebra without first developing it for $R$-module? Or would it be rather unnatural? E.g. one can define a vector space by listing tons of axioms but if we define groups first, the definition of a vector space becomes more compact, elegant, and structured, yet one can comfortably work with vector spaces (by keeping $\mathbb R^n$ in mind) without explicitly understanding groups.
So if it's not too harmful to stick to the above definition:

What are your favorite examples of $R$-algebras?
What role does the ring homomorphism play?
Why do we need $f(R)$ to be in the centralizer of $A$?
Comment: "I'd like to understand what R-algebra is without getting too much into other topics." Why?
Comment: @NajibIdrissi: simply due to the time constraint. I have tried to read an abstract algebra book, yet modules are in the middle of the text and they always make references to some previous topics: ideas, cosets, quotient groups, etc. I felt like I need to read it for weeks if I want to do it properly, chapter by charter.
Comment: Well, consider this: any text about $R$-algebras will have numerous back-references to $R$-modules. It's not often that you can sort math topics, but this one is definitely more "advanced" than $R$-modules. In fact, knowing about $R$-modules would have answered two of your three question (what role does the ring homomorphism play, by is $f(R)$ in the centralizer of $A$).
Answer: Here are some statements you might find helpful.
If you consider only commutative rings with 1, as is the case for anything related to algebraic geometry, you can see that any ring homomorphism $R\rightarrow S$ makes $S$ into an $R$-algebra. I don't deal with, nor do I know anyone who deals with noncommutative rings, so I won't address the condition with the centralizer, which of course is trivial for commutative rings.
$R$-algebras are a natural definition, and it's good to have a name for the idea. Polynomial rings $A = R[x_1,\ldots,x_n]$ are all $R$-algebras. In this case, the ring homomorphism is just the injection $R\hookrightarrow R[x_1,\ldots,x_n]$. Sometimes you want to make a distinction between the elements of $A$ which are "scalars" from the rest, so it might be useful to think about $A$ as an $R$-algebra, as opposed to just a ring (here, you should think of $R$ as being the scalars). For example, you might only want to consider $R$-algebra homomorphisms between $R$-algebras, as opposed to just ring homomorphisms. ($R$-algebra homomorphisms must be $R$-linear. In the case with polynomial rings over $R$, they must be the identity on $R$).
In the case of polynomial rings over a field $k$, it's sort of "obvious" that you should think of the elements of $k$ inside $k[x_1,\ldots,x_n]$ as the scalars, but sometimes, when looking at say $k[x,y]$, you might want to only consider the "$y$-part", in which case you might want to view it as a $k[x]$-algebra, via the injective homomorphism $k[x]\hookrightarrow k[x][y] = k[x,y]$.
Basically, the ring homomorphism determines how the "ring of scalars" (ie, $R$), acts on the $R$-algebra. Of course it doesn't have to be injective, but in many natural situations it is.
Any finitely presented $R$-algebra has the form $R[x_1,\ldots,x_n]/\langle f_1,\ldots,f_m\rangle$, where the $f_i$'s are in $R[x_1,\ldots,x_n]$.
This probably won't make much sense to you, but to me, $R$-algebras are locally what every morphism looks like in algebraic geometry.


Error building project with added static library

Question: When i run my project, i have errors, this project includes static library.
Undefined symbols for architecture i386:
"_OBJC_CLASS_$_Composer", referenced from:
  objc-class-ref in libImageCollage_Simulator.a(ImageCollageTableViewController.o)
"_OBJC_CLASS_$_FirstTableViewCell", referenced from:
  objc-class-ref in libImageCollage_Simulator.a(ImageCollageTableViewController.o)
"_OBJC_CLASS_$_SecondTableViewCell", referenced from:
  objc-class-ref in libImageCollage_Simulator.a(ImageCollageTableViewController.o)
"_OBJC_CLASS_$_ThirdTableViewCell", referenced from:
  objc-class-ref in libImageCollage_Simulator.a(ImageCollageTableViewController.o)
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

What can i do?
Comment: Have you added the library to your user search paths?
Answer: Your Project was linked with Static Library, You havent added libImageCollage_Simulator.a Library in the Project, To add that Go to Build Phases in Project Settings, in Target Dependencies click + and add the library to your project
Also Add Library Search Path here like this
Go to Build Phases and Double Click Library Search Paths, click plus and add the path of the library in your project
Comment: When i click + in Target Dependencies i haven't library in list.
Comment: Then how did you includes static library. It will be like `libraryname.a`
Comment: I copied library and header file into project folder and add it. Xcode automatically add library in "Link Binary With Libraries"
Comment: Did you seen any library in `Target dependencies`
Comment: When i make simple library and add it in project, it works ok. But now, when i make library with many files it doesn't work.


TensorFlow CSV Data

Question: Pessoal eu gostaria de montar meu training_x e training_y a partir do CSV alguém sabe como proceder, comecei mas não consegui finalizar.
import tensorflow as tf
from tensorflow import keras
import os
import pandas

model = keras.Sequential()

input_layer = keras.layers.Dense(3, input_shape=[3], activation='tanh')
model.add(input_layer)
output_layer = keras.layers.Dense(1, activation='sigmoid')
model.add(output_layer)
gd = tf.train.GradientDescentOptimizer(0.01)
model.compile(optimizer=gd, loss='mse')

dir_path = os.path.dirname(os.path.realpath(__file__))
filename = dir_path + "dados.csv"

......

training_x = tf.Variable([[1, 1, 0], [1, 1, 1], [0, 1, 0], [-1, 1, 0], [-1, 0, 0], [-1, 0, 1],[0, 0, 1], [1, 1, 0], [1, 0, 0], [-1, 0, 0], [1, 0, 1], [0, 1, 1], [0, 0, 0], [-1, 1, 1]])

training_y = tf.Variable([[0], [0], [1], [1], [1], [0], [1],[0], [1], [1], [1], [1], [1], [0]])

Meu CSV
outlook,humidity,wind,play
1,1,0,0
Answer: Segue a resolução:
file = ("dados.csv")

def data_encode(file):
    X = []
    Y = []
    train_file = open(file, 'r')
    for line in train_file.read().strip().split('\n'):
        line = line.split(',')
        X.append([int(line[0]), int(line[1]), int(line[2])])
        Y.append(int(line[3]))
    return X, Y

train_X , train_Y = data_encode(file)

TensorFlow CSV Data


Password hashing, salt and storage of hashed values

Question: Suppose you were at liberty to decide how hashed passwords were to be stored in a DBMS.  Are there obvious weaknesses in a scheme like this one?
To create the hash value stored in the DBMS, take:

A value that is unique to the DBMS server instance as part of the salt,
And the username as a second part of the salt,
And create the concatenation of the salt with the actual password,
And hash the whole string using the SHA-256 algorithm,
And store the result in the DBMS.

This would mean that anyone wanting to come up with a collision should have to do the work separately for each user name and each DBMS server instance separately.  I'd plan to keep the actual hash mechanism somewhat flexible to allow for the use of the new NIST standard hash algorithm (SHA-3) that is still being worked on.
The 'value that is unique to the DBMS server instance' need not be secret - though it wouldn't be divulged casually.  The intention is to ensure that if someone uses the same password in different DBMS server instances, the recorded hashes would be different. Likewise, the user name would not be secret - just the password proper.
Would there be any advantage to having the password first and the user name and 'unique value' second, or any other permutation of the three sources of data?  Or what about interleaving the strings?
Do I need to add (and record) a random salt value (per password) as well as the information above?  (Advantage: the user can re-use a password and still, probably, get a different hash recorded in the database.  Disadvantage: the salt has to be recorded.  I suspect the advantage considerably outweighs the disadvantage.)
There are quite a lot of related SO questions - this list is unlikely to be comprehensive:

Encrypting/Hashing plain text passwords in database
Secure hash and salt for PHP passwords
The necessity of hiding the salt for a hash
Clients-side MD5 hash with time salt
Simple password encryption
Salt generation and Open Source software
Password hashes: fixed-length binary fields or single string field?

I think that the answers to these questions support my algorithm (though if you simply use a random salt, then the 'unique value per server' and username components are less important).
Comment: Adding the username to the salt requires the password plaintext to be available to reset the password hash if you ever want to change the username. If that's an issue.
Comment: @blueshift I'm no cryptographer, but…couldn't you get around this by requiring the password to be provided in order to change the username?
Comment: The random part is important it prevents prediction attacks
Comment: From all the comments bellow I did not see an answer in regards to where the salt should go (before or after)?  I was wonder if it was harder to brute-force a hash if the salt is located before, after or possibly both, or maybe it doesn't really matter where its put?
Comment: you could add http://stackoverflow.com/questions/1645161/salt-generation-and-open-source-software/1645190#1645190 to your article list
Comment: Also add http://dba.stackexchange.com/questions/7492/password-hashes-fixed-length-binary-fields-or-single-string-field as a good lead in to the [dba.se] site
Comment: @Jeach: I don't think it makes a lot of difference, but I'd put the salt at the start so it has maximum chance to affect the hash computed from the following password. However, it should randomize OK at the end too. Even better, perhaps, put some of the salt before and some after.  Do it differently from other people.  That means that the attacker has to custom target your salted hashed passwords, rather than being able to use work done on other people's passwords. (See the LinkedIn attack.) It increases the amount of work that has to be done on average. The attacker might get lucky, even so.
Comment: @BlacklightShining: Yes.
Answer: The salt just needs to be random and unique. It can be freely known as it doesn't help an attacker. Many systems will store the plain text salt in the database in the column right next to the hashed password.
The salt helps to ensure that if two people (User A and User B) happen to share the same password it isn't obvious. Without the random and unique salt for each password the hash values would be the same and obviously if the password for User A is cracked then User B must have the same password.
It also helps protect from attacks where a dictionary of hashes can be matched against known passwords. e.g. rainbow tables.
Also using an algorithm with a "work factor" built in also means that as computational power increases the work an algorithm has to go through to create the hash can also be increased. For example, bcrypt. This means that the economics of brute force attacks become untenable. Presumably it becomes much more difficult to create tables of known hashes because they take longer to create; the variations in "work factor" will mean more tables would have to be built.
Comment: This answer is wrong.  The purpose of salts is *not* so "shared passwords aren't obvious".  The purpose is to make dictionary attacks much harder.  (Allowing dangerously incorrect responses like this to be marked as an "answer" is a fatal design flaw of this site.)
Comment: Salting also protects us from a rainbow table based attack
Comment: @ColinMackay I suggest that you read http://codahale.com/how-to-safely-store-a-password/ to find out why your answer is dangerously wrong.  The long and short of it is, "brute force is faster than you think".  Having the salt is necessary - without it people can just use a precomputed lookup table - but not sufficient to protect users with weak passwords (that would be most of them).
Comment: @btilly The link you provide is pure (dangerous) bunkum. bcrypt is no more effective at preventing brute force attacks than salting a password. The aim of an attacker is to gain access. Therefore all he needs to do is bruteforce possible passwords, not hashes. The bcrypt alternative moves the computational expense to the server and is therefore a waste of resources, nothing more. If you use a password 12345 and I brute force that password, no matter what weird computationally expensive encryption technique you use you are pwned. A random salt is just fine and don't allow weak passwords!
Comment: Yes; as I've noted in comments to other answers, my question morphed as I wrote it, and I realized the random salt was necessary, but didn't take the time to reflect that it was also sufficient.  Adding the user name to the mix mainly lengthens the data that the hash algorithm has to work on, helping protect short passwords.  How real that extra protection is, I'm not sure.
Comment: "Dangerously wrong"? It may be incomplete (it does help protect in the case of two users that happen to share the same password), but where is the danger in this answer? If I know, I'll gladly correct the answer.
Comment: @GlennMaynard: I agree with your last portion of your statement. There should be a Vetoable icon bellow the checkmark icon, once an answer is accepted as to: a) Provide the user time to update their answer, or b) To force the answer as 'vetoed'.
Comment: Glenn Maynard and DeveloperChris make compelling arguments. No matter how much you disguise a stored password, a brute force attack will succeed in cracking it if user chose a weak one.
Comment: "No matter how much you disguise a stored password, a brute force attack will succeed in cracking it if user chose a weak one." So, how is this the fault of the algorithm used to disguise the password? Going by your response, we might was well just throw our hands in the air and say "sod it! There's no point, the users are too stupid and they're going to get cracked anyway."
Answer: I think you are over-complicating the problem.
Start with the problem:

Are you trying to protect weak passwords?
Are you trying to mitigate against rainbow attacks?

The mechanism you propose does protect against a simple rainbow attack, cause even if user A and user B have the SAME password, the hashed password will be different. It does, seem like a rather elaborate method to be salting a password which is overly complicated.

What happens when you migrate the DB to another server?

Can you change the unique, per DB value, if so then a global rainbow table can be generated, if not then you can not restore your DB.

Instead I would just add the extra column and store a proper random salt. This would protect against any kind of rainbow attack. Across multiple deployments.
However, it will not protect you against a brute force attack. So if you are trying to protect users that have crappy passwords, you will need to look elsewhere. For example if your users have 4 letter passwords, it could probably be cracked in seconds even with a salt and the newest hash algorithm.
Comment: I think you may well be right - as I wrote the question, I realized the random salt was necessary; I didn't take the time to note that it was sufficient, too.  Having said that, one concern is to give the hash algorithm more data to work on - and user name helps a bit, as does the salt.  Recovery to another DBMS server instance is a valid concern - one I'd not thought of.  Username and salt would be fine under that, and user name is not 100% necessary.  Thanks.
Answer: I think you need to ask yourself "What are you hoping to gain by making this more complicated than just generating a random salt value and storing it?"   The more complicated you make your algorithm, the more likely you are to introduce a weakness inadvertently.  This will probably sound snarky no matter how I say it, but it's meant helpfully - what is so special about your app that it needs a fancy new password hashing algorithm?
Comment: @Peter: no offense taken - I understand what you're saying.  One aspect of "what's different" as I was writing was "make sure different servers with the same password store different keys".  As noted in other comments, I realized near the end of the question that the random salt was necessary; I didn't spot that it was sufficient.  And the extra data in the hash helps protect short and poor passwords.  What I can't assess is how much difference that makes.
Comment: Continuing: If the salt is an 8-byte integer and the password is a single letter, does an SHA-256 hash really protect it enough?  If the user name is 3 characters and the 'server unique' data was, say, a 32 character randomly determined (but fixed) string, does that help protect the data - 44 bytes of data to work on instead of just 9.  It seems like it should be safer (9 bytes could be rainbow attacked; 44 bytes probably couldn't as easily be attacked).  Maybe the 'server unique' just needs to be a 'fixed 32-byte string'; ...
Comment: Continuing (2): ... or maybe it needs to pad 'salt plus password' to 64 bytes (or 32 bytes, or some other number) with fixed string?  Or maybe this is all a grand goose chase; it really doesn't matter.
Answer: Why not add a random salt to the password and hash that combination. Next concatenate the hash and salt to a single byte[] and store that in the db?
The advantage of a random salt is that the user is free to change it's username. The Salt doesn't have to be secret, since it's used to prevent dictionary attacks.
Comment: +1 for mentioning that a user is no longer free to change their user name !
Comment: @pb: in this context, I don't want users changing their name, thanks.  In some contexts, that might be valuable, but as far as this app is concerned, a user's name is fixed (or, more accurately, if someone changes their name they become a new, different user).  Just using random salt and password is probably OK; I'm a little concerned to ensure that there is enough material for the hash algorithm to get its teeth into - that is another part of the reason for adding more than just the salt. As I wrote the question, I realized the random salt was necessary; I didn't notice it was sufficient too.
Comment: the user would still be able to change their username, but you would have to rehash their password at that time.  On the other hand, using a random salt has the same or greater benefits as using a non-random salt.


Partitioning Integers using only elements from a specific set

Question: I know how to partition given $p(x)$ using a generating function as my textbook on discrete mathematics explains it in detail. However, I want to know if it is possible to restrict the source elements of the partition? So, given I want to find the partition of $x$ is it possible to do it using only elements from $S={y_1, y_2, y_3, ..., y_p : y_i \in \mathbb{Z} \forall i}$.
An example might be partition any number using only 4 and 9.
If so, how?
This is a homework question of sorts but this is not the actual homework question (because I can solve that - I just can't find a general answer for it yet and this is a way I think I can generalise (possibly)).
Comment: Just a recommendation: If you're interested in these things, you will surely love the wonderful little book "Integer partitions" by George Andrews & Kimmo Eriksson. http://www.amazon.com/Integer-Partitions-George-E-Andrews/dp/0521600901/
Comment: @Hans thanks very much. When they finally let me back in the library I'll see if we've got it.
Answer: It's the same generating function method.  If $p_S(n)$ denotes the number of partitions of $n$ using only positive integers in some set $S \subset \mathbb{N}$, then
$$\sum_{n \ge 0} p_S(n) x^n = \prod_{s \in S} \frac{1}{1 - x^s}.$$
A popular choice is $S = \{ 1, 5, 10, 25 \}$ (the problem of making change).  When $S$ is finite the above function is rational and it is possible to give a closed form for $p_S$.
If the question is about whether such a partition exists at all, for sufficiently large $n$ this is possible if and only if the greatest common divisor of the elements of $S$ divides $n$.  For small $n$ there are greater difficulties; see the Wikipedia article on the Frobenius problem.  When $|S| = 2$ (say $S = \{ a, b \}$) and the elements of $S$ are relatively prime, the largest $n$ for which no such partition exists is known to be $ab - a - b$.  When $a = 4, b = 9$ this gives $23$, so for any $n \ge 24$ such a partition always exists.
Comment: Thanks Qiaochu, I did wonder if it would be similar to the existing formula but it was late and I couldn't think it through. +1 and the answer I needed.


Angular Service utilizando packages de terceiro

Question: Estou criando um service em angular que consome um package para consultar uma api, porém recebo sempre o mesmo erro;

Can't resolve all parameters for ApiService: (?).

o Código:
import { Injectable, Inject } from '@angular/core';
import { WooCommerceAPI } from 'woocommerce-api';

@Injectable()
export class ApiService {
  woocommerce: any;

  constructor(@Inject(WooCommerceAPI) woocommerce: WooCommerceAPI) {
    this.woocommerce = woocommerce({
    url: 'http://wc-project.dev/',
    consumerKey: 'ck_123',
    consumerSecret: 'cs_123',
    wpAPI: true,
    version: 'wc/v2'
  });
}

  getProducts(): any {
    return this.woocommerce.get('products');
  }
}

Já tentei utilizar com OnInit mas recebo o erro

this.woocommerce is undefined

como a função ngOnInit é iniciada antes mesmo da declaração dos atributos até entendo esse erro.
Mas como posso utilizar o package da api em meu service ?
Answer: Como a API não faz parte do Angular você precisa importar tudo com * e associar diretamente a uma variável na hora do import.
Você também não precisa colocar dentro do constructor já que ele não possui nenhum provider.
import { Injectable, Inject } from '@angular/core';
import * as WooCommerceAPI from 'woocommerce-api';

@Injectable()
export class ApiService {
  woocommerce: any;

  constructor() {
    this.woocommerce = WooCommerceAPI ({
    url: 'http://wc-project.dev/',
    consumerKey: 'ck_123',
    consumerSecret: 'cs_123',
    wpAPI: true,
    version: 'wc/v2'
  });
}

  getProducts(): any {
    return this.woocommerce.get('products');
  }
}


Lat Long or Long Lat

Question: There seems to be no standard whether Longitude,Latitude or Latitude,Longitude should be used.
WSG84 and stuff based directly on it, seem to prefer Long,Lat.
"Normal people" always tend to speak of Lat, Long - so I've very often seen code or frameworks that use Lat, Long (e.g. google Maps)
Is there any strong argument for either way?
Comment: For anyone reading this, it's not correct; WSG84 is lat/long and that's how the relevant ISO spec says you should present latitude and longitude. The currently accepted answer, which states there is no universal standard, is factually incorrect. A bunch of popular JavaScript libraries ignore the standard (and hundreds of years of convention), really because some developers found it easier to do it that way and didn't know or care about the existing standard or the long standing convention.
Answer: You are correct, there is no universal standard on the order:
In mathematical functions which do an universal conversion, between x,y or lon,lat or inverse, the lon,lat order should be used, because the x-axis relates to longitude and y to latitude and the x,y order is usually preferred.
Further, if you program a piece of code which is related to draw a lon,lat coordinate on x,y coordinates (screen), I also would use the lon,lat order because of the direct relation to x,y.
The order lat,lon is the classical one, coming from (old) navigation and geography. I assume that latitude in that field is used first because it was easier to measure (using only a ruler, the sun and a stick for length of shadow measuring).
The longitude was not determinable for long time. If you read old adventure reports, they only tell the latitude that their expeditions reached).
I think therefore they use latitude first, the measurement of longitude came later in history, once precise chronometers have been available and transportable.
So for apps that display coordinates info on a screen you should display latitude first.
Comment: [ISO 6709 (Wikipedia link)](https://en.wikipedia.org/wiki/ISO_6709#Items) says Latitude first, Longitude second.
Comment: So, unfortunately, "there is no standard on the order" is an incorrect answer.
Comment: Just a note, in "classic" geodesy you usually work with a left-hand-coordinate system when you use Cartesian coordinates, i.e. X-Axes is the vertical axis - usually named "northing". Y-Axes is used for "easting". However, in geoinformatics it is again mostly the right-hand coordinate system. So, always make a clear definition like "lat/lon" or "easting/northing"
Answer: As mentioned in the comments by @Midavalo, there is a standard for the representation of geographic locations by coordinates: ISO 6709.
It describes that a geographical point is specified by the following four items:

a first horizontal coordinate (y), such as latitude
a second horizontal coordinate (x), such as longitude
optionally, a vertical coordinate, i.e. height or depth
optionally, an identification of the coordinate reference system (CRS)

The order, positive direction, and units of coordinates are supposed to be defined by that CRS, but when such a CRS identification is missing -- which is very often -- the data must be interpreted by the following conventions:

Latitude comes before longitude
North latitude is positive
East longitude is positive
Fraction of degrees is preferred over sexagesimal (degrees, minutes, seconds) notation

So, unless another coordinate reference system is mentioned, the standard is "latitude, longitude, (elevation)".
Comment: The order latitude first applies only when the coordinate is exclusively interpreted as geographic coordinate. In function with mixed interpretation, like in geo transformations the order lon, lat is prefered. ISo 6709 does not apply for mixed usage.
Comment: generally speaking any standard is as standard as amount of people which chose to follow it. if wikipedia says its standard it doesnt really mean anything. anyone can write anything on the internet these days.
Comment: I agree, the ISO spec is the right thing to follow. The order for the representation is explicitly spelled out in the standards doc and it's hazardous that a bunch of tech bros willfully ignore it (ignoring literally hundreds of years of convention out of hubris).
Answer:
There seems to be no standard whether Longitude,Latitude or Latitude,Longitude should be used.

The problem is the exact opposite: there are several competing standards. There's ISO 6709 which specifies Lat-Long and is followed by the EPSG:4326 Geodetic Parameter to represent coordinates on the World Geodetic System. But there's also the CRS:84 parameter which uses the same coordinate system but with inverted axis (Long-Lat).
It's a matter of choosing which standard to follow rather than lacking standardization. Still, that doesn't mean that all choices are equally convenient.

Is there any strong argument for either way?

Yes, prefer Lat-Long for GIS data unless you're catering to a specific audience or use case. As mentioned, most people default to Lat-Long and many GIS applications will too, so if you have no reason to prefer Long-Lat, stick to Lat-Long. Otherwise, it might be better to just pick whatever convention your tools will favor. For instance, Long-Lat is the choice for GeoJSON so if you're primarily processing GeoJSON data, it's your call to decide if it's worth it to convert back and forth. If you're not using GIS software and just want to store coordinates as if they were (x,y) points on a plane, Long-Lat is more intuitive - but beware the risks of rolling your own geodesic calculations instead of using a proper GIS library to interpret coordinate reference systems.

Lat Long or Long Lat


Easy way to override which screen shows up first iOS

Question: Right now I'm trying storyboards out, and I have my UITableViewController as my rootViewController. Now on some instances if my user is not logged in, I want another UIViewController to appear first. I understand I can perform a segue to it, but from my understanding the TableView will still try to get loaded, which is not what I want unless they supply info on this UIViewController that I'm trying to get to appear first (if say a key doesn't exist in NSUserDefaults) for example.
So my question is, is there an easy solution I can maybe add to my appDelegate to "override" the rootViewController from storyboard, or appear before it, then have a button simply on it to dismiss back to that rootViewController in storyboard?
Thanks!
Answer: Really similar to this question: UIStoryboard load from app delegate
You should set the Storyboard ID in the Identity section of the View Controller in Interface Builder. Then you can get that screen via
UIViewController *viewControllerToShow = [storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];

You will end up with something like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

   UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:[NSBundle mainBundle]];

       UIViewController *vc = nil;
       if (someKindOfCheck) {
           vc = [storyboard instantiateViewControllerWithIdentifier:@"MyViewController"];
       }
       else {
           vc =[storyboard instantiateInitialViewController];
       }

       // Set root view controller and make windows visible
       self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
       self.window.rootViewController = vc;
       [self.window makeKeyAndVisible];

   return YES;
}

Comment: Instead of initialize new instance of storyboard, you could aswell use self.window.rootViewController.storyboard if you only have one storyboard.
Answer: You could:

Use a different initial view controller (you can specify this in the storyboard). In that view controller, check if the user is logged in. If they are, just transition directly to the table view controller via a manually triggered segue. If not, display the login screen.
Subclass UITableViewController. Check for the login in viewDidLoad.  If not, present a modal login view controller.

You probably don't want to do it in the app delegate since that would require you to manually load the storyboard, which means unnecessary code.
Comment: You can also argue that the login screen shouldn't handle this logic in it's viewDidLoad. It should be handled "outside" of it, in my opinion. It's more a matter of philosophy than premature optimization.
Comment: I humbly disagree. This will cause the "login screen" to always be created, even though it's not needed. I would go with manual initialization in app delegate.
Comment: That's a premature optimization.  iOS loads and unloads view controllers all the time.  Why wouldn't we trust it to do the right thing?  Initialization in the app delegate, in fact, over-constrains the OS -- it's forced to load the storyboard at a specific time.  How do we know it hasn't already loaded the storyboard by the time didFinishLaunchingWithOptions is called?  In a high-level programming environment -- especially iOS -- it's best not to fight the system.
Comment: But the idea of the storyboard is to have a visual representation of the flow of your program.  The first thing the program needs to do is log the user in;  there's a view controller for that.  The next thing is to show the table; there's another view controller for that.  We can see the flow without looking at any code.
Comment: Thanks for the advice you two, and for the answer Anna - app seems to be flowing great with your implementation! You're my hero!
Answer: An easy way would be to set your table sections to 0 if the user isn't logged in, for example;
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger numberOfSections = 0;
if (userLoggedIn)
{
  numberOfSections = 1;
}

return numberOfSections;
}

Comment: If I went this route, would you happen to know the best route of displaying text in the middle of the UITableView saying "Not logged in" for example? Would it be best practice to simply have a button hidden then not hidden when this is the case, and vice versa?
Comment: When I have done it I have just added a UILabel in the middle of the view. However as you are going to immediately segue to your other UIViewController, then this may not be necessary, especially if that is a modal view.


How to inform client that data has finished without closing socket

Question: I'm having trouble writing a server-client communication passing a bitmap as data.
At my server side I have
<code>InputStream in = rs.getBinaryStream(1);
                        ByteArrayOutputStream f2 = new ByteArrayOutputStream();
                        int c = 0;
                        while ((c = in.read()) > -1) {
                            f2.write(c);
                        }
                        bytes = f2.toByteArray();
                        username2.write(bytes, 0, bytes.length);
</code>
And at my Android client, I have
<code> ByteArrayOutputStream out = new ByteArrayOutputStream();
            final byte[] buffer = new byte[2048];
            int read = -1;

            while ((read = receiveimagem.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
</code>
The problem is, the client just understands that the sending is over when I close the outputStream at server side. But the structure is inside a loop and if I close the socket, it won't work again. How can I tell the client that the data is over? The code stucks in the Android client at the while. I know I should send the length and check it, but I don't know how to use the length to check the end of the file.
Answer: Your main problem in communicating the length of the image to the client is that the server itself doesn't know the length of the input before it begins transmitting the image. The server should read the entire image into a buffer first, then send the buffer's length to the client. The client can then execute a for loop, using the received size in the for loop's condition. A better solution would be for the client to read all of the image in one call, so you don't need to loop in the client. Doing I/O one byte at a time generally can and should be avoided. Also remember to flush both the output streams!
Comment: Reading in one call will not solve this problem. A read can transfer as little as one byte at a time. It is not guaranteed to fill the buffer.
Comment: I have tried to get the ByteArray size through bytes.lenght and send it to the client. At the client side, after getting the size, how can I make this for loop?
Comment: Thank you. Reading what you said, I could come out with a solution. Just made a for(int i=0, i<(lenght got from server), i++). Thank you so much. Also made final byte[] buffer = new byte[1]; so I can count it one by one
Comment: @user3318082 There is no need to read one byte at a time. It could hardly be less efficient. You should read into a byte array of reasonable size, say 8k, and use the count returned by `read()` to tell you how much data was actually read. See my answer in the duplicate for how to do this under the control of an overall target length.