'path' in array with special characters using imagecache

Question: I have a folder in my sites/default/files directory filled with product jpg's gathered from an external server and back end stock take system.
The files look like this...

Bread.jpg
Bakery.jpg
Cakes+and+Puddings.jpg
Chocolate+Bars.jpg
Chocolates+%26+Treats.jpg
Christmas+Fruit+%26+Veg.jpg

I am using theme_image_style in a custom block template to print the images using an image style from Drupal 7's core image handler like so...
<?php
    print theme_image_style(
        array(
            'style_name' => 'category_header',
            'path' => 'product_group_images/' . $productcategoryurl . '.jpg',
            'attributes' => array(
            'class' => 'category-header-image'
                 ),
            'width' => NULL,
            'height' => NULL,
        )
    );

?>

Where $productcategoryurl is the image name inside the product_group_images folder.
This all works great where the image is only one word, like bread.jpg or bakery.jpg
The trouble I am having is the "+" or "&" (%26) in the image names.
I have tried str_replace to swap the spaces in the product name with "+", but in the path, the "+" is always encoded, and the image is never saved in the new style.
So my path comes out like....

/sites/default/files/product_group_images/Chocolate%2BBars.jpg

Instead of...

/sites/default/files/product_group_images/Chocolate+Bars.jpg

And therefore, no image is created in the /sites/all/files/styles directory.
Is there a way using the "path" in the array to actually use the "+" as a space without encoding it?
I hope ive explained that well enough, its late!
Answer: I would use a hyphen "-" instead of plus "+" as it is URL safe and the standard MO on Drupal
Comment: Yeah that would be ideal. But I'm stuck with a folder of these images and file names which is populated from the external site.
Comment: It seems I missed what you are trying to do with the str_replace() function, are you not renaming the files?
Comment: The stock updates from the factory through an external system, where staff upload the latest product photo. Then on a cron run, all photos are gathered from the other system and placed in a folder in the sites/default folder, so I have no control over the names of the files until they reach that folder. I am trying to do it with those file names, as manually changing the names is not an option as stock is always updated and changed seasonally due to the farms supplying and their yield each year.
Comment: I see what you mean. I am also given the name of the product in the product array. So I am matching the name "Chocolate bars" to the filename "Chocolate+bars.jpg" by using str_replace. The problem is the path name is getting encoded with %2B and i dont think it is using the file name to create the cropped image cache image
Comment: Oh now I understand, yeah this answer doesn't apply at all, will delete it in 24 hours or if you answer, whichever comes sooner.
Answer: You might find it easiest to set up a scheduled task that synchronises the files to another location and changes the file names to match the product name along the way.


standard platform performance test

Question: We're currently running our application on Heroku and are seeing the limitations of its platform (mainly due to the cost of scaling).
We're looking to run our own setup on something like Amazon. There are a few competitors out there in the Cloud that offer pure SSD storage etc. that look attractive.
I wanted to basically find a standard test that I could run to spec out the performance of each of these platforms running a comparable instance.
In no way am I a performance expert so I'm not 100% sure what I'm looking for, I just wanted to see some side-by-sides to make sure we make an informed decision.
Can anyone suggest a test suite (or a few) that might give us a relative benchmark for things like disk, memory, cpu performance etc...?
Answer: You could try the Phoronix Test Suite or a subset of the tests to gather metrics about system performance. It's an easy way to see the CPU and disk subsystem capabilities, for instance.
The best test of all is your application, though. Benchmarks aren't really the same as your actual workloads. So perhaps you can try the various offerings in a limited basis to see if it works for your needs.
Comment: awesome thx so much!

standard platform performance test


How to prove topological equivalences of shapes with side identifications

Question: Past papers at my University frequently ask for a geometric argument that proves that some shape with side identifications is homeomorphic to another shape, e.g. a  torus. Quite frequently there are some strange arguments for this; I'm fine with connecting two shapes together, turning two lines into one if they are next to eachother and in the same direction, reflecting and rotating; but sometimes other things are done, like removing a shape and gluing it on at a different place; is there any foolproof way to know what to do and when, or are there any tips and tricks for deciding what to do that I might be missing?
An algebraic argument would also be fine, though I find it a little harder to think about in this way.
Sorry for the loosely defined question, and thanks for any help you can give!
Answer: "removing a shape and gluing it on at a different place" is weird, but
"turning two lines (edges?) into one if they are next to each other" is OK.
That second operation is part 2 of the first one, so it must be part 1 of the first operation that bugs you.
Here's a lemma for you:
If $R$ is an equivalence relation on $X$, and $S$ an equivalence relation on $Y$, and there's a map $f$ from $X$ to $Y$ with the property that $x R x'$ if and only if $f(x) S f(x')$, then there's a bijection, $\hat(f)$, from $X / R$ to $Y / S$ with the property that $\hat(f)([x])= [f(x)]$ for every element $x \in X$, where $[x]$ denotes the $R$-equivalence class of $x$, and $[f(x)]$ denotes the $S$-equivalence class of $f(x)$.
You can probably prove this lemma.
Now consider a polygon $X$, and slice it into two pieces; call the (disjoint) union of those two pieces $Y$. Let $R$ be the trivial equivalence relation on $X$ (i.e., $x R x'$ iff $x = x'$), and let $S$ be the equivalence relation $Y$ consisting of the trivial relation, together with the relation that says that points in the two "pieces" that lie along the previously-shared edge are "equivalent".
Then the lemma says that $X/R = X$ is in bijection with $Y/S$. In other words, the "cut apart" thing is, with the gluing rule, the same as the original.
This same argument can be extended to handle continuity/topology, with exactly the same consequences: it's OK to cut and paste.
As for "is there a standard rule for how to do these operations?", the answer (for surfaces without boundary) is "yes". If your surface is given to you as several polgyons with edges identified, first glue up edge-pairs until you have only a single polygon for each surface.
Now the classification theorem for surfaces actually consists of an algorithm for sequentially altering such a polygon-description of a surface into a standard one, after which comparison is easy. You apply this algorithm to both your surfaces, and if they come out the same, then they were homeomorphic; if they don't, then they weren't.
I'm not going to repeat the algorithm here -- it's a long chapter in most algebraic topology books -- but it's worth noting that surfaces are incredibly special in this regard: for 3-manifolds (or higher dimensions), there's no known such algorithmic way of testing for homeomorphism.
[Books I like for classification of surfaces: Massey, intro to algebraic topology (or something like that); Seifert and Threllfall, a Textbook of Topology. Very old-fashined, but wonderful.]


Quais são as diferenças entre __autoload e spl_autoload_register?

Question: No php, temos dois métodos de efetuar um autoload de classes:
função __autoload
Exemplo:
function __autoload($class_name) {
    require_once $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2();

função spl_autoload_register
Exemplo:
class Autoloader
{
   public static function load($class)
   {
         require $class . '.php';
   }
}

spl_autoload_register(['Autoloader', 'load']);

// ou
spl_autoload_register(function ($class)
{
     return $class . '.php';
});

É claro que, a princípio, vemos que as diferenças está na declaração: Um, você tem que declarar uma função chamada __autoload, e outro, você usa uma função (já existente) chamada spl_autoload_register.
Porém, o Manual do PHP não recomenda o uso de __autoload, porque em versões futuras poderia ser removida (na verdade, não sei se tem mais esse aviso no manual, porque eu não o encontrei lá quando li o manual de __autoload novamente).
Sendo assim:

Quais são as diferenças entre as duas?
Por que o uso de spl_autoload_register é (ou era) encorajado, ao invés de __autoload (já que, a princípio, __autoload parece mais fácil de usar)?
Answer: A função __autoload() funciona como métodos mágicos como o __construct(), __destroy(), __string, etc.
O __autoload() captura o nome de uma classe não declarada.
Com o nome da classe, basta montar o "path" para carregá-la.
Caso a classe possua uma declaração, o __autoload() é ignorado.
É possível também simplificar a montagem dos "paths" apenas registrando suas bases com a função set_include_path() ou ini_set('include_path','.').
A informação sobre desuso é válida e está reportada no link:
http://php.net/manual/en/language.oop5.autoload.php

Tip spl_autoload_register() provides a more flexible alternative for
  autoloading classes. For this reason, using __autoload() is
  discouraged and may be deprecated or removed in the future.

O texto já menciona o motivo básico no desencorajamento ao uso de __autoload() e preferência pela nova função spl_autoload_register(). A função spl_autoload_register() provê mais flexibilidade e melhorias em relação ao __autoload().
Invocando funções definidas pelo usuário
A função spl_autoload_register() permite definir classes customizadas para a chamada dos eventos.
class AiSeEu
{
   public static function TePego($class)
   {
         require $class . '.php';
   }
}

spl_autoload_register(['AiSeEu', 'TePego']);

Em suma, permite que sejam criados vários __autoloads().
Pode parecer inútil pois é praticamente o mesmo resultado do __autoload(), porém, isso torna-se útil quando se trabalha com programação orientada a objetos.
Parâmetros como função anônima
spl_autoload_register(function ($class)
{
     return $class . '.php';
});

Assim como qualquer outra função do PHP, é possível passar os parâmetros como função anônima.
http://php.net/manual/en/functions.anonymous.php
Include path
Note que, set_include_path() ou ini_set('include_path','.') também são válidos para funções invocadas por spl_autoload_register().
Comment: +1 pelas informações, -1 pelo Teló :)
Comment: AiSeEu::tePego($class); throw new NaoPegouNadaException('erro causado no michel teló')
Comment: Dá vontade de editar essa pergunta, por causa desse Michel Teló
Answer: __autoload é geralmente considerado obsoleto. Ele só permite um único carregador automático . Geralmente, você só deve usar __autoload se você estiver usando uma versão do PHP sem suporte para spl_autload_register.
spl_autoload_register permite que vários autoloaders serem registrados que serão executado até que uma correspondência seja encontrada. Isto significa que se você estiver usando o código do framework ou outras bibliotecas de terceiros que implementam suas próprias autoloaders você não precisa se preocupar com possíveis conflitos causados pelo seu autoload.
Fonte original: Soen
Comment: ótimo complemento. Esqueci de mencionar sobre prevenção de conflito


Problem downloading files from link android java

Question: I have a link where if we go, the .mp4 file will be downloaded automatically, but if the try to do using the download manager then the files is saved as .html format which I want in .mp4.
String ID = "https://presaver.com/download/9Tw-f3i-08k/22";
 DownloadManager downloadmanager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse("ID");
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setTitle("YoutubeVideo");
        request.setDescription("Downloading youtube video");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setVisibleInDownloadsUi(true);
        request.setDestinationUri(Uri.parse(path));
        downloadmanager.enqueue(request);

Comment: `(Uri.parse(path))` Well what is the value of path?
Answer: I think you miswrote this line
Uri uri = Uri.parse("ID");

It should be
Uri uri = Uri.parse(ID); // string ID

Comment: or try to change `https` to `http` .


Uniform convergence of $\left(\frac{\sin x}{x}\right)^{\frac1n}$

Question: The sequence
$\displaystyle{f_n(x)= \left(\frac{\sin x}{x}\right)^{\frac{1}{n}},\, x\in [0,π] .}$
Find whether it converges pointwise, uniformly or not?
Since $\displaystyle{\lim_{n \to \infty}  \left(\frac{\sin x}{x}\right)^{\frac{1}{n}} = 1 \,\forall x \in [0,π]}$, it is pointwise convergent. I know it's not uniform convergent but how to approach for that?
Answer: For $x=\pi$ the pointwise limit is not $1$, it is $0$. This also proves that the convergence is not uniform because the pointwise limit is not a continuous function.
[I am interpreting $f_n(0)$ as $1$ for all $n$].
Answer: If the interval includes pi, then there is no pointwise convergence.
Otherwise there is and to prove that it is not uniform show that
$$\forall n \exists x \in (0,π)\ f_n(x)<1/2$$
Comment: For $x=\pi$, $ f_n(x)=0$ for all $n$, so pointwise limit does exist.


What is an intuitive way for choosing the right Statistical test?

Question: In my Statistics class, we just talked about Statistical tests. So far I've been understanding the material, okay, but now I'm very confused.
I get that Statistical tests are used in hypothesis testing and assumes a null hypothesis of no relationship or no difference between groups to determine whether the observed data fall outside of the range of values predicted by the null hypothesis. And they are used to determine whether a predictor variable has a statistically significant relationship with an outcome variable and estimate the difference between two or more groups.
I'm not clear on when to perform a statistical test and choosing the right statistical test for parametric and nonparametric tests?
Can someone help me figure out choosing the right statistical test, intuitively, and how all those different statistical tests are related?
(References are welcome. I was able to find the descriptions of each statistical test separately, but what I am interested in are the comparison, applications, and advantages.)
Comment: Any chance you can ask a more specific question? This is what a master's degree in statistics covers (incompletely).
Comment: I find this a good reference on choosing the correct test: http://rcompanion.org/handbook/D_03.html
Answer: Do a google search on "flow chart for choosing statistical test" and you will find an overwhelming amount of attempts to make that an easy choice. They may or may not be helpful in memorizing tests, I have never found any of them usefull in determining what to test.
As a beginner, you start learning tests like you learn words in a foreign language: I have learned the t-test, so I have learned to compare means of one or two metric variables. I have now learned the chi-square test of independence, so I have learned to compare count values of two or more groups. I have no learned ANOVA, so I can now do to many groups, what the t-test did to two groups. I have now learned ANCOVA, so I can have continuous predictors as well as nominal ones. I have now learned Pearson correlation, so I I have learned to determine a linear connection between to metrix variables.
Your teachers will ask only questions that can be answered with the tests you have learned so far and if you have difficulties remembering them, then the above mentioned flow charts may provide memory support.
Later in your way into statistics you will learn methods that are less strict in what they do as you can to some extend tailor them to do what you want (linear regression, nonlinear regression, bootstrapping, permutation tests,...).
You asked for intuition and really, you should develop some intution for scale levels (binary, nominal, ordinal, count data, metric, ...) which are usually taugth right at the beginning of classes, when you cannot yet understand their fundamental importance in test choice.
JMTC,
Bernhard
Answer: For intuition - imagine you are walking along a road in a forest and find 5 stones arranged in a line and ordered from smallest to highest. You are surprised to find such a constellation and start wondering: how likely is it for this order to occur without human intervention?
Here you can check various different "null" causes. One might be a hypothesis that wind placed the rocks in such a way. You want to obtain a p-value for this "null hypothesis" so you start placing various rocks on a road, wait for heavy winds, and check if the wind produced such a pattern. You repeat this experiment thousands of times and get a p-value: number of cases where wind, in your experiment, ordered the stones just as perfectly (or more) as you found them on the road. But you can also test for other possibilities. Like maybe that rain helped to order the stones. Here you repeat a similar experiment, but this time you wait for rain. Measure the numbers, get the p-value.
Choosing the right statistical tests boils down to choosing the null "cause" for your observation. In this example different tests would be: testing for rain and testing for wind.
Another detail is the order of stones. If you only want to check how often the wind can order stones from smallest to largest - you do a one tailed test. But you might also count reverse orders, where the stones get placed in decreasing order from largest to smallest.
So, as you see, in effect different tests answer different questions. When you choose one test - you ask one question, and if you choose another test you are asking a different question.

Now let's move on from the stones and briefly touch on parametric vs non-parametric. Say you measure the difference in height between girls and boys in a class. And you want to test the probability for the observed mean difference to occur in a case where there are no difference between those groups in the population.
But you have a problem here. There can be various different scenarios hiding under the "there is no difference in a population" statement, just like there were various alternative under "stones were ordered without human intervention". You have to choose more concretely.
One possibility is to do a non-parametric tests. Let's pick permutations. With the permutation test you shuffle the heights between the groups and measure the mean difference between boys and girls using these shuffled values. You repeat the shuffling thousands of times and deduce a p-value, as the number of shuffles that had higher difference compared to the one that was observed. But behind such a procedure - you chose a concrete null population, without, maybe, being aware. What you in effect stated is that your "null" population is only composed of the heights you observed in a sample. In other words, you made an assumption that your sample reflects the population perfectly. And this is one possible statistical test.
Another possibility is a parametric test. Let's forget the t-test for now and pick something more naive - you can state that each of those groups are drawn from the same normal distribution. If they are, the distribution of their sample differences should be centered around 0 and have a variance that is also deducible from your data. So you pick mean at 0, calculate the standard deviation for both groups, pool them, and now you have a parametric distribution to draw from. For the sake of simplicity, imagine you draw thousands of numbers from this distribution (thousand of mean differences under null of no difference) and deduce a p-value by counting how many of those drawn numbers exceeded the observed value. What did you do here? Instead of claiming that your sample reflects the population perfectly, you made a different assumption about the population - that it is normally distributed with mean 0 and some unknown variance. Then you computed this variance on your sample and used a "plug-in" rule to state that the population has exactly the same variance as the sample. This is a different way to obtain the "null population", and hence a different statistical test.

To summarise: under the hood all of statistical tests work in a similar way. Beneath each of them there is a "null population" lurking. And by selecting between different tests you select a different "null population". Which in itself leads to asking a different question about your observed data.


Using expect & job control for a shell script

Question: I have a question regarding expect, and i would like to know how to achieve this
Example scenario:
I have a command, Let's say test1, which when executed gives the below output
<code>$./test1 --requestid 21 --file test1.xml
 Myrequestid: 21
 Profile: Test Profile
 Filename: test1.xml

 Action (update/validate):
</code>
When the test1 is executed with options --requestid 21 --file test1.xml, creates a file test1.xml with some data related to request id 21 and also presents an interactive menu asking user to either enter update/validate.
Now the user after executing the above command, opens another terminal Edits test1.xml
Note for editing/modifying the xmlfile, i have another script so i just need to call that script.
after editing(once the script that modifies xml file) has completed, It has to return to the terminal where the above command is executed and enter update /validate at the interactive prompt to update or validate the changes.
I would like to automate this task using expect, Could some one provide hints on how best i can achieve the above using expect,
Answer: Your question is not clear.

If you want your text editor to be able to notify the bash script to update or validate the file, this is not a bash-related question : you have to create a script for your text editor in the scripting language of the editor.
If you want your script to be able to launch a text editor (the default one for example), then let the user update/validate your file, expect is irrelevant as you have complete control over your script.  You may as well ask for "update/validate/edit file", and when the user select "edit file", quit ask again "update/validate/edit file" when the user quits the editor using a loop.
Comment: Regarding editing the xml file, I have other scripts to do the editing like xmlstarlet. Sorry for not being clear


Multi-threaded performance testing MS SQL server DB

Question: Let's assume the following situation:

I have a database server that uses 4 core CPU;
My machine has 2 core CPU;
Assume they are of equal speed in terms of GHZ;
Systems are connected over a network (two lines 200mb/s each);

Test tool that I use provides # of threads parameter and will issue commands in parallel to the server.
QUESTIONS:

How would you test parallel reads/writes via stored procedure? Please brainstorm as any advice is appreciated;
How can I prove that many threads are executing the queries on the server (or should I not pay attention to this as this servers and DB's responsibility)?
What controls how many threads are executed at any time primarily in case of SQL server? I checked the "server properties" > processors > # of processors and threads section - waht more should I check?
How can I check that my application truly executes on all my machine cores - in other words - uses real threads instead of virtual ones? Or should I pay attention only to the virtual ones?
Should I pay attention to the network bandwidth? Can it be a bottleneck (I dont' send any big data, only commands with variables).
Comment: SQL Server is generally I/O bound, not CPU bound. If you're testing for performance, concentrate on I/O
Comment: @ElectricLlama thank you for the response. I guess what I really would like to do it to check whether as I increase the thread count that call a stored procedure on my machine - the same happens on the SQL server side. Can I be confident that this happens in development environment if it does on my local machine?
Answer:
1.) not sure perhaps someone else can answer
2.) SQL Sentry allows you to monitor your SQL activity (use the free trial and buy if you like it)
3.) Max Dop controls the number of processors & also the cost threshold will affect parrallelism
4.) Same as 2 perhaps, i'm not sure i understand
5.) Depends on what you are doing are where you see aproblem SQL sentry will show wait stats that may help


Grey border appearing around svg images on retina devices

Question: http://prosepticwp.cloud-2.co.uk/surveys-inspections/ - The blue icons on this page are getting a grey border when viewed on retina devices (iPhone X this problem shows)
I have checked for border css properties but none are set. Any idea?
Comment: can you any of your code?
Comment: I saw the website with retina but I've not saw any border around the icons
Comment: Check it out on iPhone x (I have added images now aswell)
Comment:  -- That is the code.
Comment: Please remove down points I was 1 rep point away from commenting everywhere :( :(
Comment: You should write an actual answer rather than editing your question to contain an answer.
Comment: @RobertLongson Ahh did not know I can do that, that is done now :)
Answer: vertical-align: middle; - This was causing the weird thin grey border to appear around my svg images on chrome. Hopefully, this helps someone else!


Why does Presto always trip me up?

Question: I have noticed that even after months of practicing C.P.E. Bach's Solfeggio in C minor, I still can't get past Molto Allegro. I have tried thinking of it as an eighth note rhythm and that actually helped me get past the Allegro roadblock but I immediately hit another one after getting up to Molto Allegro.
And I am still not near full speed because full speed is prestissimo.
But this has prevented me from practicing a lot of Chopin's pieces including his minute waltz. I am scared I will hit the same roadblock with anything at presto or prestissimo as the one I hit with Solfeggio in C minor, no matter how much time I perfect it at Allegro. Even the Toccata and Fugue in D minor sounds like it would trip me up because a section of the toccata is at prestissimo.
I am advanced enough to practice the Liszt transcription of Beethoven's 5th Symphony. So Presto should be a breeze but no, I can only seem to reach it with my own compositions. Trilling at Allegro for multiple measures is way easier for me than Presto even though the note speed in the trill and in a Presto piece is the same.
So why do I have this roadblock at Presto(like always getting mistakes except for a few lucky times if I try) and how can I eliminate this roadblock if lots of practice at Allegro and eighth note rhythms aren't going to do it?
Answer: Are you reading 'presto' etc. off a scale on a metronome?  The speed range marked 'presto' is only a guide.
Go back to a (much) slower speed.  Make sure your fingering is absolutely 'clean' - no fumbles at all.   Then practice at a higher speed - but one at which you still play perfectly.  There is no point at all in 'taking a run at it' too fast and making mistakes.  Your perfect speed will gradually increase.
All pianists KNOW this is how to practice.  Few actually do it!
Comment: I have gotten down to Allegro and I am perfect at the Solfeggio in C minor. That is the fastest speed I am perfect at so it makes sense that I would want to speed up. I wonder if I am thinking of this all wrong. I wonder if thinking of the sixteenth notes as trills and connecting them will help more than trying to speed up the whole thing. Maybe I only hit this roadblock because I am trying to speed up the whole thing and wouldn't hit it if I thought of it as trilling throughout.
Comment: My teacher taught me to speed up sections of a piece by doing 'metronome drills'. Start at a very slow tempo, play it perfectly then put the metronome up 4 bpm. Play again, put the metronome down 2 bpm, up 4 etc. until you get to your desired tempo. It takes time but I have found it to  be very effective.
Comment: Yep. I have only once actually used this method (it can be tedious!), and was surprised to be able to play the third movement of the Moonlight Sonata at the written tempo for long passages. By slowly ratcheting the speed, I actually got to a point where my perception of time changed and the metronome didn't sound that fast.
Answer: The character indication is the last thing you should worry about when you learn pieces. I'm not saying don't worry about it, just worry about it last. If you are playing a concert at Carnegie Hall then you should keep the character indication in mind.
On the other hand, if this is just some sort of regular performance and especially if the candidate is still in a foundation phase then playing in time with the correct notes and with reasonable articulation would be sufficient.
The character indication is only that last 3 percent that makes a good performance a great one. You may not get full marks for your piece when the character indication is lacking but you may still get 16 / 20.

Why does Presto always trip me up?


Step-wise feature selection with caret

Question: can anyone direct me to a package/commands in R for performing step-wise feature selection, preferably using the caret package.
I have already used linear discriminant analysis (LDA), Random forest, PCA and a wrapper using a support vector machine. I was thinking of including a partial least sqaures or a gradient boosting method, but while trying to use them on multi-class data, they cause R to crash. People have reported similar experiences on multi-class data using caret when attempting to use gbm.
I realize that I haven't used a step-wise approach and I was searching for one that can be implemented on highly correlated, dependent variables for selecting the best performing 20 variables (for example) to create a parsimonious model.
Any suggestions would be welcomed
Answer: caret has a stepLDA method available in train:
slda <- train(Species ~ ., data = iris,
              method = "stepLDA",
              trControl = trainControl(method = "cv"))

This uses stepclass in the klaR package. There are also LDA feature selection tools in caret using rfe and sbf that would be helpful.
Max
Comment: Thanks Max, wondering if you have gotten around to solving the issue with `gbm`, related to the post [here](http://stackoverflow.com/questions/15585501/usage-of-caret-with-gbm-method-for-multiclass-classification)? Thanks though for your suggestion.
Comment: I think so. Try updating caret and gbm.

Step-wise feature selection with caret


Deriving the binomial-beta conjugate model

Question: I think I am correctly deriving the binomial-beta conjugate model, but my answer differs slightly from what's on Wikipedia's page on conjugacy.
My solution
Assume that
$$
X_t \sim \text{Binomial}(m, \theta)
$$
where $\theta$ is the unknown probability of success and $X_t$ has support over values $0, 1, 2, \dots m$. Let $X = (X_1, X_2, \dots, X_T)$. The likelihood is
$$
p(X \mid \theta) \propto \theta^{\sum x_t} (1 - \theta)^{Tm - \sum x_t}.
$$
Place a beta prior on $\theta$ with model hyperpriors $\alpha_0$ and $\beta_0$,
$$
\begin{aligned}
p(\theta) &\propto \theta^{\alpha_0 - 1} (1 - \theta)^{\beta_0 - 1}.
\end{aligned}
$$
Then the posterior is
$$
\begin{aligned}
p(\theta \mid X)
&\propto \theta^{\alpha_0 + \sum x_t - 1} (1 - \theta)^{\beta_0 + Tm - \sum x_t - 1}
\\
&\Downarrow
\\
\theta \mid X &\sim \text{Beta}\Big(\alpha_0 + \sum_{t=1}^{T} x_t, \beta_0 + Tm - \sum_{t=1}^{T} x_t \Big).
\end{aligned}
$$
Wikipedia's solution
Wikipedia writes
$$
\theta \mid X \sim \text{Beta}\Big(\alpha_0 + \sum_{t=1}^{T} x_t, \beta_0 + \sum_{t=1}^{T} N_t - \sum_{t=1}^{T} x_t \Big)
$$
In other words, they write $\sum_{t=1}^{T} N_t$ where I write $Tm$. Who is correct? What is $N_t$?
Answer: Binomial distribution is a distribution for the total number of successes in $n$ independent Bernoulli trials, each with probability of success $\theta$. It doesn't really matter in how many experiments did you observe the results, you care only about total number of successes in total number of trials. You could as well shuffle the data and it would not change the results because the trials are i.i.d., same applies to re-groupping and aggregating it.
Comment: If it helps, one explanation for the above is that the total number of successes is _sufficient_ in the classical sense of _sufficient statistics_.
Comment: @gwg $Tm = \sum_{t=1}^T N_t$, $N_t$ are counts in individual experiments. You just assumed $N_1 = N_2 = \dots = N_T = m$.
Comment: Where is the mistake in my derivation? I don't see how what you're saying—which I believe I already understand—maps onto my formalism vs. Wikipedia's. For example, I don't know what $N_t$ is.


Find solution of linear equation when knowing relation between columns

Question: The exercise I have to solve is the following:
"Suppose $A$ is a $5\times 4$ matrix with columns $a_1, a_2, a_3, a_4$, and $a_1 + a_4 = a_2 + a_3$.
Which of the following vectors is (certainly) a solution of the equation $Ax = 0$ ?
$$\begin{split}
\mathbf u &= [\begin{matrix}1& -1& -1& 1\end{matrix}]\\
\mathbf v &= [\begin{matrix}1& 1& 1& 1\end{matrix}]\\
\mathbf w &= [\begin{matrix}1& -1& 0& 0\end{matrix}]\\
\end{split}$$
(all of these are $4\times 1$ matrices)
I know the correct answer is matrix $\mathbf u$ however I can't understand why. In my solution I wrote matrix $A$ as follows while taking into consideration the given relation between its columns:
$$A=\begin{bmatrix}
1 &-1 &-1& 1\\
 0 & 0 & 0 &0\\
 0 & 0 & 0 &0\\
 0 & 0 & 0 &0\\
\end{bmatrix}$$
Therefore the solution here considering only column $a_1$ is a pivot column is the following ($s, t, u$ arbitrary scalars):
$$[\begin{matrix}1& 1& 0& 0\end{matrix}]b
 + [\begin{matrix}1 &0 &1& 0\end{matrix}]c
 + [\begin{matrix}-1& 0 &0 &1\end{matrix}d
$$
(again all of these are $4\times1$ matrices)
And then I found that only vector from above can be written in this form is vector $\mathbf v$. So what am I missing? Thanks in advance!
Answer: HINT
Notice that $x = (x_{1},x_{2},x_{3},x_{4})\in\mathbb{R}^{4}$ is a solution of $Ax = 0$ iff
\begin{align*}
x_{1}a_{1} + x_{2}a_{2} + x_{3}a_{3} + x_{4}a_{4} = 0 & \Longleftrightarrow x_{1}(a_{2} + a_{3} - a_{4}) + x_{2}a_{2} + x_{3}a_{3} + x_{4}a_{4} = 0\\\\
& \Longleftrightarrow (x_{1} + x_{2})a_{1} + (x_{1} + x_{3})a_{3} + (x_{4} - x_{1})a_{4} = 0
\end{align*}
Based on such relation, can you realize why $u = (1,-1,-1,1)^{T}$ is certainly a solution?
Comment: Thanks for the answer. I realized my solution was embarrassingly wrong and I was able to solve it another way. But your solution is also correct.


How do I improve performance on a MySQL query with NULL?

Question: I have several million records in the following table:
CREATE TABLE `customers` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `store_id` int(10) unsigned DEFAULT NULL,
  `first_name` varchar(64) DEFAULT NULL,
  `middle_name` varchar(64) DEFAULT NULL,
  `last_name` varchar(64) DEFAULT NULL,
  `email` varchar(128) DEFAULT NULL,
  `phone` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `index_store_email` (`store_id`,`email`),
  KEY `index_store_phone` (`store_id`,`phone`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Query #1 takes ~800ms:
SELECT COUNT(*) FROM `customers` WHERE `store_id` = 1;
Query #2 takes ~1.5ms:
SELECT COUNT(*) FROM `customers` WHERE `store_id` = 1 AND `email` IS NULL;
Query #3 takes a whopping 5 seconds:
SELECT COUNT(*) FROM `customers` WHERE `store_id` = 1 AND `email` IS NOT NULL;
Notes:

I've simplified the table to ask the question, but the query is identical.
Yes, my table is optimized.
Yes, both fields are indexed, see the create syntax above.
There are only a few store_ids, but every record has one.
There are very few customers with email set to null.

I find a few things strange here:

Query #1 is simplest! There are only a few possible INT values. Shouldn't it be fastest?
Why is Query #3 so slow? I could cut the time in half by doing the other two queries, and subtracting #1 from #2, but I shouldn't have to.

Any thoughts on this seemingly basic question? Feel like I'm missing something simple. Did I sleep through a class in db school?
Comment: Have you tried looking at the `EXPLAIN`? My guess is that it's a lot slower because of the data in the table. If there are only a few rows with `email = NULL` then it can easily use the index and return quite fast. The first query is slower because it has to walk through many more rows, if there are only a few different `store_id` results MySQL might decide that walking through the entire table is faster than walking through the index. Which can be the wrong choice
Comment: Additionally, the `possible_keys` tells you which indices are possible for the current query and the `key` indicates which index (if any) was actually used.
Comment: In some cases MySQL guesses wrong... you can force MySQL to use the index: http://dev.mysql.com/doc/refman/5.7/en/index-hints.html
Comment: Get rid of the store_id index
Comment: Are you looking to get the count of all customers in that store, or are you looking to do something else? I ask because adding a LIMIT to your query would drastically optimize your performance.
Comment: @zsawaf: it's a `COUNT(*)` query, how would a limit help in this case?
Comment: @zsawaf: Good idea, but `LIMIT` is not an option in these queries, and as @Wolph points out, never an option for `COUNT(*)` queries.
Comment: @Wolph: The `EXPLAIN` shows everything is keyed and in working order. What should I be looking for?
Comment: @neokio: look at the `rows`. It should tell you how many rows were examined to return the results.
Comment: Correct, that's why I was asking if you wanted to count all rows, or if you had a different query in mind. If what Wolph suggested doesn't help, the only other thing I can think of is to split up the load into different databases, and simultaneously retrieve queries.
Comment: @Wolph: You're totally right, it's using the wrong `key`, though the right one is listed in `possible_keys`. There's no way to tell it which index to use, is there?
Comment: I'm going to revise the post to better represent my actual syntax.
Comment: @Wolph: Check out the syntax. Your suggestion revealed that Query #3 was inexplicably keying off of `index_store_phone`. Removing it solved the immediate problem, the Q3 now takes 1.4 seconds. But what will happen when I add that index back in later?
Comment: @Wolph: Excellent, `USE INDEX` within a query is a revelation. You've just improved my game. I think others might benefit as well. Rehash these tips into an answer so I can accept it :)
Comment: Show us the `EXPLAINs`.
Comment: If mysql is using the wrong index in this simple table, file a bug at `bugs.mysql.com`.
Comment: If there are "several million rows", why does it say `AUTO_INCREMENT=1`?  Perhaps that is an _old_ `SHOW CREATE TABLE`?  And maybe something else changed?
Answer: At times the MySQL query parser guesses wrong when it decides which indices to use. For cases like these the index hints can be useful (http://dev.mysql.com/doc/refman/5.7/en/index-hints.html)
To force the use of an index:
SELECT * FROM table1 USE INDEX (col1_index,col2_index)
  WHERE col1=1 AND col2=2 AND col3=3;

To force the use of an index including replacing table scans:
SELECT * FROM table1 FORCE INDEX (col1_index,col2_index)
  WHERE col1=1 AND col2=2 AND col3=3;

To ignore a certain index:
SELECT * FROM table1 IGNORE INDEX (col3_index)
  WHERE col1=1 AND col2=2 AND col3=3;

To debug which index is being used the EXPLAIN statement can be used: (https://dev.mysql.com/doc/refman/5.7/en/explain-output.html)
EXPLAIN SELECT * FROM table1
  WHERE col1=1 AND col2=2 AND col3=3;

Comment: Thanks @Wolph. Also worth mentioning how useful `EXPLAIN` is for revealing hiccups in the query parser.
Answer: Drop the index with just (store_id); it is redundant with two other indexes.
This will probably also obviate the need for FORCE INDEX, etc.
INDEX(store_id, email) works for all three queries.


R lm() interaction terms or effect?

Question: I have quick look but I do not seem to find the answer to the following question. Basically, I get the following output when I run lm():
<code>    Call:
lm(formula = y ~ as.factor(x1) * x2, data = data)

Residuals:
     Min       1Q   Median       3Q      Max
-13.7237  -3.4391   0.8872   3.7576   8.3555

Coefficients:

                             Estimate Std. Error t value Pr(>|t|
(Intercept)                  8.448e+01  1.646e+00  51.318   <2e-16 ***
as.factor(x1)2               5.273e-01  2.967e+00   0.178   0.8597
as.factor(x1)3               2.442e+00  2.542e+00   0.961   0.3416
x2                          -3.259e-05  8.820e-05  -0.369   0.7134
as.factor(x1)2:x2           -2.641e-04  2.636e-04  -1.002   0.3215
as.factor(x1)3:x2           -2.728e-04  1.314e-04  -2.076   0.0434 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 5.809 on 47 degrees of freedom
  (2 observations deleted due to missingness)
Multiple R-squared:  0.207, Adjusted R-squared:  0.1227
F-statistic: 2.454 on 5 and 47 DF,  p-value: 0.04683
</code>
The question is what is the interpretation of regression coefficients? More specifically what do the estimates of interaction mean? For example, is  -2.728e-04 the interaction term or the effect of x2 on (x1)3?
Thank you very much in advance!
Answer: For the individuals with x1 equal to the reference value (here 1), an
increase of x2 by one unit is associated to an increase of y by -3.259e-5.
For the individuals with x1 equal to 3, an increase of x2
by one unit is associated to an increase of y by -3.259e-5 + (-2.728e-4).

R lm() interaction terms or effect?


Utilizando função e arquivo de cabeçalho (header)

Question: Estou fazendo um programa simples porém utilizando arquivo de cabeçalho .h (header) e uma função olá mundo, mas estou com a seguinte mensagem de alerta: Undefined reference to 'imprime'. Pedi para outra pessoa testar e disse que deu certo o que pode ser ainda?
Segue código:
=== Arquivo MainCodeCount.c ==

#include <stdio.h>
#include <stdlib.h>
#include "LibCodeCount.h"

int main(int argc, char *argv[])
{
    imprime();

    return 0;
}

=== Arquivo CodeCount.c ===

#include <stdio.h>
#include "LibCodeCount.h"

void imprime()
{
    printf("Ola mundo!\n");
}

=== Arquivo CodeCount.h (header) ==

void imprime();

Comment: Agradeço atenção senhores, mas resolvi da seguinte maneira: Apenas configurei o gcc no path do windows e os comandos:
gcc -c MainCodeCount.c
gcc -c LibCodeCount.c

depois,

gcc -o HELLO MainCodeCount.o LibCodeCount.o

Executei o Hello.exe e foi.
Comment: Se você resolveu seu problema dessa forma, melhor colocar como uma **resposta** ao invés de um comentário. Assim fica mais fácil saber o que voc6e fez para resolver seu problema.
Answer: O problema é meramente que você compilou apenas um arquivo, o MainCodeCount.c e deixou o CodeCount.c de fora. Assim sendo não há ninguém definindo a função a função imprime() na etapa de linking e o erro ocorre:

undefined reference to imprime()

A correção é compilar todos os seus arquivos:

gcc -c MainCodeCount.c                            (MainCodeCount.c -> MainCodeCount.o)
gcc -c LibCodeCount.c                             (LibCodeCount.c -> LibCodeCount.o)
gcc -o Hello MainCodeCount.o LibCodeCount.o       (*.o -> Hello.exe)

Outra coisa que falta no seu código mas que da forma que está não vai lhe causar nenhum problema são os header guards. Em todo arquivo de cabeçalho use o seguinte:
#ifndef MYHEADER_H
#define MYHEADER_H

// seu código aqui

#endif

Ou:
#pragma once

// seu código aqui

O objetivo é que o cabeçalho seja processado apenas uma vez por unidade de compilação, mesmo se incluído mais de uma vez.
Answer: Tente referenciar em todos os arquivos
#include "CodeCount.h"

Answer: Tente em CodeCount.h, mudar o código para:
#ifndef __CODECOUNT_H__
#define __CODECOUNT_H__

void imprime();

#endif

Em teoria a sua mensagem de erro não tem a ver com referências duplicadas, mas estou sem outras ideias do que pode ser agora.
Comment: Sorry,
mas é LibCodeCount.c e .h
Comment: Sem problemas. Se possível, edite a pergunta para mostrar o nome certo do arquivo.
Comment: Editei a resposta com outra possível solução.


Counting number of yields by an iterator?

Question: One can consider the functions
def f(iterator):
    count = 0
    for _ in iterator:
        count += 1
    return count

def g(iterator):
    return len(tuple(iterator))

I believe the only way they can differ is that g might run out of memory while f doesn't.

Assuming I'm right about that:

Is there a faster and/or otherwise-better (roughly, shorter without becoming code-golf)
  way to get f(iterator) while using less memory than tuple(iterator) takes up,
  preferably inline rather than as a function?

(If there is some other way for  f, g to differ, then I believe that
f is more likely than g to properly define the functionality I'm after.
I already looked at the itertools documentation page, and don't see any solution there.)
Answer: You can use sum with generator expression yielding 1 for every item in iterator:
>>> it = (i for i in range(4))
>>> sum(1 for _ in it)
4


Octopus downloading resulting configs

Question: I like to see a way (ideally thru Octopus web interface) to download resulting .config files, after transformation.
Use case: look at environment A with package B and get B.config with all transformations applied so I can use B.config to debug locally using connection strings pointed to A.
Answer: One could enable the "Custom Deployment Script" and use the post deployment script section with an artifact.

Octopus downloading resulting configs


Why did Safari drop support for SharedWorker?

Question: Why did Safari drop support for SharedWorker?
And are there any working polyfills using, for example, localStorage and StorageEvent as a communication port? (Yes, the shim would have to detect and recreate the master Worker)
Comment: Someone from Apple will add a clarifying comment - in an alternate universe..
Comment: ["Shared workers can not communicate across processes currently, so they should better be disabled"](https://bugs.webkit.org/show_bug.cgi?id=116359)
Comment: I looked through that commit, and I still can't see a sensible reason for why this was dropped... other than laziness on Apple's part in implementing it properly. Chrome seems to have implemented this differently. Shame the fork isn't being looked at by Apple.
Answer: Directly from one of the WebKit Engineers:

The implementation of Shared Web Workers was imposing undesirable
  constraints on the engine. It never gained any adoption.

Source here
Comment: Several years later: the WebKit team has [shown renewed interest](https://bugs.webkit.org/show_bug.cgi?id=149850#c5) in SharedWorker and [appears to be actively working on implementing SharedWorker again](https://bugs.webkit.org/show_bug.cgi?id=230382).
Answer: I can't find any polyfills for SharedWorker.
It seems that one can be created by implementing a StorageEvent based communication port across workers. The downside being that StorageEvents are not portable for WebWorkers, and you have to maintain state across each browser tab and know when to flick on/off each master worker.
Comment: You can also use a `MessageChannel`, with the tabs discovering each other through a `ServiceWorker`
Answer: From my understanding the answers here are correct, but it's also due to the lack of SharedWorker adoption by web developers (a chicken and egg type situation).
If you're in need of a polyfill, you can use the one I created. I couldn't find one for one of my projects, so I created this one, https://sharedworker.okikio.dev/.

Note: it doesn't handle cross tab communication, but you can use the CacheStorage API together with a ServiceWorker and MessageChannel or use IndexedDB and ServiceWorker (from @jakearchibald on Twitter) to create a similar effect

Also: I should mention that Safari is working on supporting the BroadcastChannel API, which would cover the cross tab communication aspect, it's currently available in the Webkit Technology Preview
Answer: Since safari default's behaviour on cookies is preventing third-party cookies on tracking.
If safari allows us to use SharedWorker, developer(google or tracking company) can use it to access identify between different window tab.
That's the reason why safari drop the SharedWorker, interestingly, it support WebWorker but not SharedWorker.

It's my guess, not the official reason.
Comment: No. Same-origin policy still applies to shared workers. See stuartd's link: https://bugs.webkit.org/show_bug.cgi?id=116359
Comment: Maybe they meant ITP


How Can I Automate Tasks in Xcode?

Question: I'm building an app in Obj-C / Xcode and I'm running into some repetitive tasks.  For example if I want to add an image resource to my project I just go through the same identical steps... only difference is the path to the resource.
How can I automate these tasks?
Is there some sort of Xcode macro-recorder like in Photoshop and Excel?
Answer: There's definitely no macro recorder, but there are some tools you can use. First, there's Applescript, which is the most likely to be of use for this particular problem. I'm not promising it'll be easy, however. There isn't a rich collection of Applescripts for Xcode that I know of, so you'd need to dig through the Scripting Suite using Script Editor and see what's available.
For text things, there are User Scripts, which you can create from the script menu (it looks like a scroll). You can write perl, python, ruby, or whatever you like to process selected text and turn it into other text.
You can also create text macros (Edit>Insert Text Macro).
Another major repetitive task is setting up your initial project. For that you can create new project templates to be set up as you like them. I have most of a walkthrough of that written up, and should have something posted on Cocoaphony this week or early next as part of my Building the Build System series.

How Can I Automate Tasks in Xcode?


Module isomorphism, simple modules, and quotients

Question: I'm reading R.S. Pierce's Associative Algebras. While proving a preliminary lemma to Nakayema's Lemma, the following is mentioned:
Let $M$, $N$, be two $A$-modules where $N$ is a submodule of $M$ and $M/N$ is simple. Let $u\in M$, $u\notin N$. Then $uA+N=M$.
This must be really elementary but I can't see why. I'm assuming it's related to some isomoprhism theorems and probably Schur's lemma. Or maybe it follows directly from the definitions of simple modules or quotient rings? Anyway, I don't think the assumption $u\notin N$ is necessary.
Any help would be much appreciated.
Comment: Sure it is necessary, take $A=M=k$ and $N=0$. Then if $u\in N$, i.e. $u=0$ then $uA+N=0\neq M=k$.
Answer: Because of the isomorphism theorem for modules there is an inclusion-preserving bijection between the submodules of $M/N$ and the submodules of $M$ containing $N$. Thus, because $uA+N$ properly contains $N$ and $M/N$ is simple it has to be equal to $M$.
Comment: Thanks, I knew I'm missing something basic.


Facebook asks for domain should not contain protocol information

Question: I am getting error while verifying an app ID and app secret code...
Error App Domains: http://mayihelpyou.oodus.com should not contain protocol information.
not sure what this error is and how to resolve.... plz help
Answer: they ask to delete http:// protocol
so use your simple domain
<code>mayihelpyou.oodus.com
</code>
Comment: Thanx this resolves the problem.... actually they were asking for the protocol at website url and I have mistakenly placed it at app domains... though thanz alpha... you are too quick...


Select text for copying Android EditText

Question: I want to select some text inside an EditText which is the child element of a ListView. The selected text has to be set on a clipboard. I am unable to find any examples regarding this. How should i go about this? selectionStart and selectionEnd don't work on this.
Thanks.
Comment: I have explicity said in comment don't have time. Dont be too much dictating. Here issue is yours and community is trying to help you. Dont think community will write everythin for you. If link is not useful you may ignore. Your every response is dictating and that is not good.
Comment: sorry, don't have much time to write required for your issue, Few minutes of SO search gave me this link, this may help you. If you already tried this I am sorry.http://stackoverflow.com/questions/2679948/focusable-edittext-inside-listview
Comment: Hey, I am not dictating anything. I am trying to prevent the community from junk answers. Don't get me wrong!
Answer: here is the possible solution . in getView method of listview perform following operation:
enter code here:

public View getView(final int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unneccessary calls
            // to findViewById() on each row.
            final ViewHolder holder;

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.main, null);

                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new ViewHolder();

                holder.subText = (TextView) convertView.findViewById(R.id.subTxt);

                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }

            //TEXT BOX position is 0 then
            if(position == 0) {

                ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); clipboard.setText(txtEdit.getText().toString());
            }
            return convertView;
        }

Answer: Use this code on list selection event
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);  clipboard.setText(txtEdit.getText().toString());
Comment: you can try this, It won't work. I have tried every possible way out there. But it doesn't seem to work. There is an issue with list focus in android. It always confuses between child elements and parent elements.
Answer: You can open one dialog on editText long click event inlistView custom adapter and display two option copy and paste in them
you can copy text programically using
ClipboardManager clipboard =
                              (ClipboardManager) c1.getSystemService(c1.CLIPBOARD_SERVICE);

                         clipboard.setText("Text to copy");

and get Text Using
System.out.println(clipboard.getText());

Comment: don't you understand the problem. Listview has issues with child elements.
Answer: InputConnection ic = getCurrentInputConnection();
ExtractedText extracted = ic.getExtractedText(
                    new ExtractedTextRequest(), 0);
            /*If selection start and end are not equal then selected text
             * needs to be deleted and updated to core*/
            if (extracted!= null && extracted.selectionStart != extracted.selectionEnd) {
}

Use api given by ExtractedText
Answer: EditText already provide this functions on long press....means pressing a long touch on editText it pops up with context menu asking select all, select text, copy all.
Comment: Please try doing that in a listview and then we can discuss it later on.
Comment: sorry, it was my mistake that haven't saw the same thing in ListView. Now i also wonder how to do that.


Threepenny GUI - Using sink with a canvas

Question: I'm learning how to use Threepenny GUI, I've hooked up to a click event stream from a canvas, mapped that event stream to a stream of Point and applied accumB to [] and that Event Point to get a Behaviour [Point]
where Point:
data Point = Point {
  x :: Int,
  y :: Int
}

And the code to map the click Event stream to the Behaviour [Point]:
let pointStream = uncurry Point <$> UI.mousedown canvas

let pointsStream = fmap (:) pointStream

let pointsAccumB = accumB [] pointsStream

pointsBehaviour <- pointsAccumB

I would then like to draw these points to a canvas element which I have added to the body of the HTML in the setup method.
I've managed to draw the points from the behaviour like so:
on UI.click drawButton $ const $ do
  UI.clearCanvas canvas

  points <- currentValue pointsBehaviour

  -- Draw the points here

But the problem is I would like to have the points be drawn to the canvas each time the user clicks the canvas, without requiring the user to go and click a button. Or, in other words, I would like to combine a draw point function into the point stream.
From my research, it looks like sink may be the function that I need to use to tie together the behaviour and the mutation of the UI in an FRP style.
But, I'm struggling to understand how to piece this together (i.e. what would the sink application look like for this given use case?). Is it even possible to do this with Threepenny currently?
Answer: Wrap your point-drawing code in a WriteAttr and pass it to sink. The attribute might be defined like this:
drawnPoints :: WriteAttr Canvas [Point]
drawnPoints = mkWriteAttr $ \canvas point -> do
  UI.clearCanvas canvas
  -- Draw the points here

You can then connect your actual points and canvas using sink:
element canvas # sink drawnPoints pointsBehaviour


Reading SIM contacts on Symbian S60

Question: I am looking for a working code snippet for Symbian S60 5th edition in which you can read SIM contact details.
If possible, I would skip using RPhoneBookSession, but if that is the only way, please provide code snippet how to use it.
Thank you.
Answer: What you want is the example code from the relevant chapter of the Quick recipes on Symbian OS book, which you can find here.
EDIT-1:
Should have read the question more carefully.
The CContactDatabase API should synchronize with the SIM Phonebook seamlessly by using RPhoneBookSession so you don't have to.
To figure out what's wrong, I would suggest calling RPhoneBookSession::GetLastSyncError, RPhoneBookSession::GetPhoneBookCacheState and RPhoneBookSession::GetSyncMode.
I would also suggest doing all this both before and after adding a new CContactICCEntry to the database yourself.
Of course, this is all supposing Nokia didn't just brutally disable Phonebook synchronization...
EDIT-2:
If Nokia disabled Symbian's phonebook synchronization, they may have replaced it with their own, which would mean that using the CPbkContactEngine::AllContactsView method could yield different results than the CContactDatabase approach.
Let's face it, though. If the Contacts application provided with the phone doesn't even allow you to save a contact on the SIM, Nokia may have removed all possibilities to interact with the SIM phonebook period.
EDIT-3:
You could try to develop against phbksyncsvr.lib using the binaries in the Product Development Kit (PDK) from the first real version of the Symbian Foundation operating system: Symbian^2. Binary compatibilty between versions of Symbian OS can sometimes help you.
Comment: If you are referring to ContactReadField example and chapter 126.96.36.199, there are no KUidContactICCEntry in the database. I am looking for an example in which I read contacts from the SIM card.
Comment: According to the official documentation, RPhoneBookSession and phbksyncsvr.lib are not part of the S60 5th Edition SDK. How do I get that? Is there a way to get BAK these days?
Comment: I am not familiar with ADK. Are you referring to ADT - Application Development Toolkit? If so, can you point me to the directory where the library is placed?
As of the Application Development SDK for the first Symbian Foundation platform - Symbian^1 - this is a copy of the S60 5th Edition SDK v1.0 which does not contain the library and the headers.
Comment: I am getting this error on the PDK download page:

"Export Control Error
The Symbian Foundation website is headlong into a limited beta phase now, and over the next few weeks we'll be stress testing our geo-targeting systems. While we do this, some of you, whole countries at a time, might have trouble accessing parts of the site. In fact, if you're seeing this message, it's happening right now."

Thank you for your help so far.
Comment: Works fine from the UK. Very unfortunate. Might be worth trying every day and asking the foundation to have a wiki page to clarify what they can currently export where...
Answer: This isn't possible without a private Nokia API.

Reading SIM contacts on Symbian S60


Octave installation error on Mac - vecLibFort error

Question: I am trying to install Octave by following the instructions given in the wiki - http://wiki.octave.org/Octave_for_MacOS_X, now I am getting the error below not sure what it is and how to go about solving it.
<code>==> Installing dependencies for octave: veclibfort, arpack, fftw, glpk, c
==> Installing octave dependency: veclibfort
==> Using Homebrew-provided fortran compiler.
This may be changed by setting the FC environment variable.
==> Downloading https://github.com/mcg1969/vecLibFort/archive/0.3.0.tar.gz
Already downloaded: /Library/Caches/Homebrew/veclibfort-0.3.0.tar.gz
==> make all
1 error generated.
make: *** [libvecLibFortI.dylib] Error 1
make: *** Waiting for unfinished jobs....
1 error generated.
make: *** [vecLibFort.o] Error 1

READ THIS: https://github.com/Homebrew/homebrew/wiki/troubleshooting
If reporting this issue please do so at (not Homebrew/homebrew):
  https://github.com/homebrew/homebrew-science/issues
</code>
Comment: brew should have downloaded and installed all dependencies required for the build of Octave and it failed. The last message suggests that you report this bug to `homebrew-science`. Have you done that?
Answer: In the end I just installed Octave using the binary installer from source forge
http://sourceforge.net/projects/octave/files/Octave%20MacOSX%20Binary/


differential forms proving degree can't be greater than dimention and 1-forms are linearly independent.

Question: Every differential form w, say of degree k on an open set in R^n,
can be written uniquely as
 $w = \sum_I a_I (x)dx^I$ ,
where the sum is over all possible lists $I$ of $k$ increasing indices, say
$I = (i_1, i_2, . . . , i_k)$ ,
with each of the indices $i_1 < i_2 < · · · < i_k$ being an integer from 1 to $n$.
Problem: If $k > n$, prove that the only k-form on any open subset of $\mathbb{R}^n$ is
the one that vanishes everywhere: $w = 0$.
Also suppose that $a_1, a_2, . . . , a_p$ are 1-forms on $\mathbb{R}^n$. Prove that they
are linearly independent at every point of $\mathbb{R}^n$ just when $0 \neq a_1 \wedge a_2 \wedge \ldots \wedge a_p$.
Answer: This is pretty much a linear algebra question.
Let $\omega$ be an alternating $k$-form on vector space $\mathbb{R}^n$ and $k>n$. Then because of linearity, for $k$ vectors $\vec{v_k} = \sum_{i=1}^n \alpha_{i,k} \vec{e_i}$ (where $\vec{e_i}$ are basis vectors), $\omega(v_1,\dots,v_k)$ is a sum of terms of the form $\alpha \omega(\vec{e_{i_1}}, \dots, \vec{e_{i_k}})$ where $\alpha \in \mathbb{R}$ is a scalar. Since $k>n$, we can always find indexes $p$ and $q$, $p \neq q$, such that $\vec{e_{i_p}} = \vec{e_{i_q}}$ and because of that $\omega = 0$.
For the second part of the question, if it were $a_2 = \alpha a_1$ then $a_1 \wedge a_2 \wedge \dots \wedge a_p = \alpha a_1 \wedge a_1 \wedge \dots \wedge a_p = 0$.
On the other hand, if $1$-forms $a_1, a_2, \dots, a_p$ were linearly independent, we could extend this set to a basis $a_1, \dots, a_p, a_{p+1}, \dots, a_n$ of the dual space $(\mathbb{R}^{n})^*$. It is known that the space $\Lambda^n \mathbb{R}^n$ of alternating $n$-forms is one-dimensional. Suppose $a_1 \wedge \dots \wedge a_n = 0$. Let $\omega = b_1 \wedge \dots \wedge b_n$ be an alternating $n$-form and $b_i = A a_i$. Then $\omega = A a_1 \wedge \dots \wedge A a_n = \det(A) a_1 \wedge \dots \wedge a_n = 0$. It follows that every alternating $n$-linear form is equal to $0$ which is a contradiction.
"Finite-dimensional Vector Spaces" by Halmös has a nicely written chapter about multilinear forms.


Different definition of subsequences in Kelley's General Topology

Question: I have a question that may seem trivial.
I am studying Kelley's General Topology. I was reading Chapter 2 when I came across an unusual definition. Tipically, I define a subsequence as follows:

a subsequence of the sequence $(a_n)_{n \in \mathbf{N}}$  is any
sequence of the form $(a_{n_k})_{k \in \mathbf{N}}$  where $(n_k)_{k
> \in \mathbf{N}}$ is a strictly increasing sequence of positive
integers.

Whereas in the book, it says that:

$T$ is a subsequence of a sequence $S$ iff there is a sequence $N$ of
non-negative integers such that $T = S \circ N$ (equivalently, $T_i =
> S_{N_i}$ for each $i$) and for each integer $m$ there is an integer
$n$ such that $N_i \geq m$ whenever $i \geq n$.

I can deduce that this two definitions are not the same and it may seem that one definition implies the other. Am I right or wrong? Can someone formally explain me the difference and how these two are related?
Thank you :)
Comment: The definition of subsequence in Kelley's book is indeed more general than the usual case.
Comment: They're equivalent.    The point of view in the second is that a sequence is just a function out of the naturals.
Comment: Fortunately the natural numbers are well-ordered, so given a subsequence of the second kind you can form a subsequence of the first kind of it by discarding all intermediate indices that drop below previous index.
Answer: The first definition in your question is the usual one. Kelley's definition would agree with it if $N$ were required to be a strictly increasing sequence, but Kelley's requirement is weaker than that. So any subsequence in the usual sense is also a subsequence in Kelley's sense, but the converse is not true.
I think that Kelley uses his unusual definition in order to agree with the treatment of nets and subnets (a sort of generalized sequence, important in general topology) later in the book. The definition of "subnet" is the same as Kelley's definition of "subsequence" with the index set $\mathbb N$ for sequences replaced by more general ("directed") partially ordered sets.


Implementing multiple interfaces with Java - is there a way to delegate?

Question: I need to create a base class that implements several interfaces with lots of methods, example below.
Is there an easier way to delegate these method calls without having to create a horde of duplicate methods?
public class MultipleInterfaces implements InterFaceOne, InterFaceTwo {

    private InterFaceOne if1;
    private InterFaceTwo if2;

    public MultipleInterfaces() {
      if1 = new ImplementingClassOne();
      if2 = new ImplementingClassTwo();
    }

    @Override
    public void classOneMethodOne { if1.methodOne(); }
    @Override
    public void classOneMethodTwo { if1.methodTwo(); }
    /** Etc. */

    @Override
    public void classTwoMethodOne { if2.methodOne(); }
    @Override
    public void classTwoMethodTwo { if2.methodTwo(); }
    /** Etc. */

}

Answer: As said, there's no way. However, a bit decent IDE can autogenerate delegate methods. For example Eclipse can do. First setup a template:
public class MultipleInterfaces implements InterFaceOne, InterFaceTwo {
    private InterFaceOne if1;
    private InterFaceTwo if2;
}

then rightclick, choose Source > Generate Delegate Methods and tick the both if1 and if2 fields and click OK.
See also the following screens:
Comment: Thanks to BalusC and Lukas for such quick and useful answers. My project is based in Eclipse, so I was able to use BalusC's answer in near real-time ! Worked like a charm, and saved me several hours of frustrating work. As a new user of this forum, I am suprised and delighted at the quality of the participants here.
Comment: Great hint! I didn't know that and will save 100's of hours in the future :) The good thing about stackoverflow: you'll also learn from questions you didn't ask yourself!
Answer: There is one way to implement multiple interface.
Just extend one interface from another or create interface that extends predefined interface
Ex:
public interface PlnRow_CallBack extends OnDateSetListener {
    public void Plan_Removed();
    public BaseDB getDB();
}

now we have interface that extends another interface to use in out class just use this new interface who implements two or more interfaces
public class Calculator extends FragmentActivity implements PlnRow_CallBack {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

    }

    @Override
    public void Plan_Removed() {

    }

    @Override
    public BaseDB getDB() {

    }
}

hope this helps
Answer: Unfortunately: NO.
We're all eagerly awaiting the Java support for extension methods
Answer: There's no pretty way. You might be able to use a proxy with the handler having the target methods and delegating everything else to them. Of course you'll have to use a factory because there'll be no constructor.


Algoritmo para calcular tempo de vida em dias

Question: Queria saber quantos dias eu já vivi, entre a data que nasci até ao dia de hoje, incluindo os anos bissextos. Estou fazendo a seguinte forma, porém não sei como terminar:
<code>#include<stdio.h>
#include<locale.h>

int main(){
setlocale(LC_ALL, "portuguese");
 int dia,diaatual,mes,mesatual,ano,anoatual,totaldias,i;

printf("Digite o dia que você nasceu:\n");
scanf("%d",&dia);
printf("Digite o mes que você nasceu:\n");
scanf("%d",&mes);
printf("Digite o ano que você nasceu:\n");
scanf("%d",&ano);
printf("Digite o dia (data de hoje):\n");
scanf("%d",&diaatual);
printf("Digite o mês (data de hoje):\n");
scanf("%d",&mesatual);
printf("Digite o ano (data de hoje):\n");
scanf("%d",&anoatual);

    for(int i = ano; i < anoatual; i++){

        // verifica se ano é bissexto ou não
        if(i % 4 == 0){
            totaldias += 366;
        } else {
            totaldias += 365;
        }
    }

    printf("Dias: %d",totaldias);

    return 0;
}
</code>
Comment: Melhore sua pergunta. Esta ocorrendo algum erro? Qual sua dúvida? não Realizou a pergunta...
Comment: Sou iniciante, não estou conseguindo a logica certa pra fazer, quero saber quantos dias eu ja vivi entre a data que nasci e a data de hoje incluindo os anos bissextos ps: em linguagem C ( Se possivel sem usar vetor ou matriz)
Comment: Relacionados: http://pt.stackoverflow.com/a/182280/132 e http://pt.stackoverflow.com/a/70604/132
Answer: Escrevi essa resposta com base nesta minha outra resposta (lá eu explico isso em maiores detalhes). Apenas traduzi a parte pertinente do algoritmo para C.
<code>#include <stdio.h>
#include <locale.h>

int restoSemSinal(int a, int b) {
    return (a >= 0L
            ? a % b // Positivo.
            : (b + (a % b)) % b); // Negativo.
}

int divisaoSemSinal(int a, int b) {
    return a >= 0L
            ? a / b // Positivo.
            : (a / b) - (a % b == 0 ? 0 : 1); // Negativo.
}

int contarDiasDesde1970(int dia, int mes, int ano) {
    // Passo 1.
    int anosDesde1970 = ano - 1970;

    // Passo 2.
    int periodosDe400Anos = divisaoSemSinal(anosDesde1970, 400);
    int anoNoPeriodoDe400Anos = restoSemSinal(anosDesde1970, 400);

    // Passo 3.
    int periodosDe4AnosNos400 = anoNoPeriodoDe400Anos / 4;
    int anoNoPeriodoDe4Anos = anoNoPeriodoDe400Anos % 4;

    // Passo 4.
    int diasNosAnosAnterioresDoPeriodoDe4Anos = 365 * anoNoPeriodoDe4Anos + (anoNoPeriodoDe4Anos == 3 ? 1 : 0);

    // Passo 5.
    int diasNoAno = dia - 1;
    int tabelaDeMeses[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int i;
    for (i = 0; i < mes - 1; i++) {
        diasNoAno += tabelaDeMeses[i];
    }

    // Passo 6.
    int dias = diasNoAno
            + diasNosAnosAnterioresDoPeriodoDe4Anos
            + periodosDe4AnosNos400 * 1461
            + periodosDe400Anos * 146097;

    // Passo 7.
    if (anoNoPeriodoDe4Anos == 2 && mes > 2) dias++;
    if (anoNoPeriodoDe400Anos > 130 || (anoNoPeriodoDe400Anos == 130 && mes > 2)) dias--;
    if (anoNoPeriodoDe400Anos > 230 || (anoNoPeriodoDe400Anos == 230 && mes > 2)) dias--;
    if (anoNoPeriodoDe400Anos > 330 || (anoNoPeriodoDe400Anos == 330 && mes > 2)) dias--;

    return dias;
}

int main() {
    setlocale(LC_ALL, "portuguese");
    int diaNascimento, diaHoje, mesNascimento, mesHoje, anoNascimento, anoHoje;

    printf("Digite o dia que você nasceu:\n");
    scanf("%d", &diaNascimento);
    printf("Digite o mês que você nasceu:\n");
    scanf("%d", &mesNascimento);
    printf("Digite o ano que você nasceu:\n");
    scanf("%d", &anoNascimento);
    printf("Digite o dia (data de hoje):\n");
    scanf("%d", &diaHoje);
    printf("Digite o mês (data de hoje):\n");
    scanf("%d", &mesHoje);
    printf("Digite o ano (data de hoje):\n");
    scanf("%d", &anoHoje);

    int nascimento = contarDiasDesde1970(diaNascimento, mesNascimento, anoNascimento);
    int hoje = contarDiasDesde1970(diaHoje, mesHoje, anoHoje);
    int diasDeVida = hoje - nascimento;

    printf("Dias: %d", diasDeVida);

    return 0;
}
</code>
Embora esse algoritmo use como ponto de referência o ano de 1970, ele funciona para qualquer data a partir de 15 de outubro de 1582. Ele poderia utilizar qualquer outro ano completo da era gregoriana (a partir de 1583) como ponto de referência com apenas alguns pequenos ajustes, mas decidi manter 1970 porque é isso que estava no algoritmo original.
Para datas anteriores à reforma do calendário realizada em 1582 (que instituiu o calendário gregoriano), o algoritmo produzirá resultados errados.
Comment: +1 Continua extenso, mas não deixa de ser boa.
Answer: Seria isso?
Qualquer dúvida comente...
<code>#include<stdio.h>
#include<locale.h>

int main(){
setlocale(LC_ALL, "portuguese");
 int dia,diaatual,mes,mesatual,ano,anoatual,totaldias;
int anos, meses, dias, diaano, diames;

printf("Digite o dia que você nasceu:\n");
scanf("%d",&dia);
printf("Digite o mes que você nasceu:\n");
scanf("%d",&mes);
printf("Digite o ano que você nasceu:\n");
scanf("%d",&ano);
printf("Digite o dia (data de hoje):\n");
scanf("%d",&diaatual);
printf("Digite o mês (data de hoje):\n");
scanf("%d",&mesatual);
printf("Digite o ano (data de hoje):\n");
scanf("%d",&anoatual);
//total de anos vividos
anos=anoatual-ano;
// diaano é os anos multiplicados por 365 dias, mais os dias dos anos bissextos, obtido pelo resto a divisao por 4
diaano=(anos%4)+(anos*365);

if(mesatual>mes){
meses=mesatual-mes;
}
else {
meses=mes-mesatual;
}
// meses convertido em dias
diames=meses*30;

if(diaatual>dia){
dias=diaatual-dia;
}
else {
dias=dia-diaatual;
}
totaldias=diames+diaano+dias;
printf("Voce viveu: %d Dias",totaldias);
}
</code>
Comment: Você sabia que há meses que não têm 30 dias?
Comment: @VictorStafusa  Sabia, mas nao queria dar o código completo... passei uma lógica. E como é algoritmo de iniciante, provavelmente adotem 30 dias como padrão.
Comment: Obrigada, é basicamente isso que eu quero, vou tentar colocar as condições para os meses de dias diferentes
Comment: @AmandaSilva se solucionar, marque como resposta e complemente se quiser... Prazer Ajudar :)


Is it pointless to use Bagging with nearest neighbor classifiers?

Question: In page 485 of the book [1], it is noted that "it is pointless to bag nearest-neighbor classifiers because their output changes very little if the training data is perturbed by sampling". This is strange to me because I think the KNN method has high variance when $K$ is small (such as for nearest neighbor method where $K$ is equal to one), and that makes it perfect for bagging. What is wrong with this intuition?
[1] Witten, Ian H., et al. Data Mining: Practical machine learning tools and techniques. Morgan Kaufmann, 2016.
Comment: @StephanKolassa Not yet. But I think it is typical to use bagging with KNN since there are some papers for it such as http://www.jmlr.org/papers/volume11/biau10a/biau10a.pdf
Comment: Good question. Have you tried a few simulations?
Answer: In the original paper about bagging, Breiman refers to this point.
He explains that unstable learners are likely to give different prediction for modified datasets and likely to benefit from bagging. On the other hand, stable learners (take to the extreme a constant), will give quite similar predictions anyway so bagging won't help.
He also refer to specific algorithms stability:

Unstability was studied in Breiman [1994] where it was pointed
  out that neural nets, classication and regression trees, and subset selection
  in linear regression were unstable,while k-nearest neighbor methods were
  stable.

Breiman [1994] is "Breiman,L.(1994)Heuristics of instability in model selection,Technical
Report, Statistics Department, University of California at Berkeley."
I think the Breiman extended the technical report into Heuristics of Instability and Stabilization in Model Selection but he hardly refers to knn there.
I your intuition is correct. The lower k the more unstable the model will be. The more we modify the dataset, the higher probability the use a different set of neighbors. If you take k=1 and modify the dataset enough so the probability of getting the same neighbor is less then 80%, bagging should help.
I think the the use case Breiman had in mind is a higher k and more delicate modifications. If you have k of 10 and probability of having the same neighbour of 99%, the results will be quite stable.
Comment: Thanks for your answer and references. In the Witten's book, the "nearest-neighbor" classifiers are mentioned, which as I know, are the KNN classifiers with K=1. So, it is still not obvious to me why they think 1NN is a stable classifier.
Comment: Being stable is a function of the classifier and the data set. If all items in the same area behave the same 1-nn will be as stable as 10-nn. In the family of k-nn, 1-nn is indeed the least stable.
Comment: Yes, and this is exactly my question that why Witten et. al think 1NN is a stable classifier, while in general it is the least stable KNN classifier.
Comment: I guess that they are used to stable data sets but this is a shot in the dark.


Como inserir âncoras para minha página?

Question: Tenho uma pagina chamada de noticias.html com várias notícias divididas em vários artigos, mas só falta os links dessa parte que ta escrita "CONTINUE LENDO..." que eu gostaria de fazer com que ao clicar nessa parte a notícia abrisse toda com o restante  das informações
Meu código é esse:

section {
  width: 80%;
  margin: 0 auto;
  background-color: #dedede;
}

article {
  width: 200px;
  height: 200px;
  background-color: yellow;
  display: inline-block;
  margin-left: 10px;
}

a {
  display: block;
  width: 100%;
  height: 10px;
  border-radius: 7px;
  text-decoration: none;
  background-color: red;
  display: table;
  position: relative;
  top: 150px;
}

h2 {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

Notícia 01
    continue lendo...

Notícia 02
    continue lendo...

Notícia 03
    continue lendo...

Notícia 04
    continue lendo...

Comment: `CONTINUE LENDO...`
Comment: Quando você diz "a notícia abrisse toda", você quer dizer que deseja que esse contêiner expanda o seu tamanho, ou você quer que a notícia seja aberta em outra página?
Comment: acho que ela abrir em outra pagina seria melhor  ...
Comment: @GustavoSampaio gostaria de uma  ajuda  nessa parte .
eu vejo em muitos sites de notícias  mais  não sei  como e que funciona isso
alguém me ajudem por favor
Comment: qual o padrão usado pelo os sites de notícias ?
Comment: tipo esse
http://valemaisnoticias.com.br/category/mutuipe/  ?
Comment: @Sam como eu faço para abrir a noticia em uma nova pagina mais com um tamanho que não ocupe 100% da pagina ?
Comment: @hugocsl  como eu faço para abrir a noticia em uma nova pagina mais com um tamanho que não ocupe 100% da pagina ?
Comment: @jonassouza isso seria uma "nova pergunta" e não seria possível te responder tudo em um comentário. Te sugiro abrir uma Nova Pergunta, ai vc coloca o código de como vc vai querer apresentar a noticia e só assim vai dar pra te ajudar de uma forma correta e que vai te atender 100%
Answer: Se seu botão CONTINUE LENDO... for um elemento , é só adicionar o atributohref, direcionando para a página da notícia em questão, conforme o que o @hugocsl falou. Já se for um elemento <button>, você pode adicionar o atributo onclick, para que quando o botão for clicado, a página da notícia em questão seja aberta, através da declaração exemplificada pelo @OtavioCapel, ou através do método open, também pertencente ao objeto window, da seguinte forma:
Abre a notícia em outra guia
window.open('link_da_noticia');

ou
Abre a notícia na mesma guia
window.open('link_da_noticia', '_self');

Isso tudo considerando que você quer abrir a notícia em uma outra página.

Qual o padrão usado pelos sites de notícias?

Contando o exemplo que você forneceu, com mais outros dois exemplos que procurei, acho que o padrão deles é abrir a notícia em outra página, porém na mesma guia.

Como inserir âncoras para minha página?


Distribution of $\frac{X}{X+Y}$, exponential

Question: On this site the distribution of $\frac{X}{X+Y}$ has been derived. Suppose $X$ and $Y$ are independently distributed exponential random variables with mean $1$. This means $f_X(x)=e^{-x}=P(X\geq x)$.
Then it starts with
For $t\in (0,1)$
$$P\left(\frac{X}{X+Y}\leq t\right)=P\left(\frac{X+Y}{X}\leq \frac1t\right)$$
$$=P(Y\geq X(\frac1t-1))$$
So far so good. But the next step I really don´t understand.
$$=\int_0^{\infty} f_X(x)\cdot P(Y\geq x(\frac1t-1)) \, dx$$
It is obvious that $X \in (0, \infty)$. But the rest is unclear to me. I hope somebody can explain me why the two latter lines are equal.
Thanks for your time
calculus
Answer: This is (one way) how we compute the expectation of a function of a random variable.  We write
$$
E[g(X)] = \int_{x=0}^\infty f_X(x) g(x) \, dx
$$
where $f_X(x)$ is the PDF of $X$.  This is assuming that $X$ ranges from $0$ to $\infty$; adjust the limits of integration accordingly if it's otherwise.
Some intuition for this expression might be obtained by considering the discrete case.  Suppose a random variable $X$ takes on values $1$, $2$, and $3$ with probabilities $p_1 = 1/2, p_2 = 1/3, p_3 = 1/6$.  What is $E(X^2)$?  We would write
$$
E(X^2) = \sum_{k=1}^3 p_k k^2 = \frac{10}{3}
$$
and in general,
$$
E[g(X)] = \sum_{k=1}^3 p_k g(k)
$$
Well, the continuous case is much the same thing, except that instead of $p_k$, we have $f_X(x)\, dx$.  But otherwise, the principle is the same.
Comment: Thanks for your answer. But I don´t understand in which way the expaction is involved here.
Comment: @BruceET I still don´t know from where the expectation comes. It is not mentioned on the site.
Comment: @BruceET My question is: How can we deal the expectation although in the second line or somewhere else the expactation (operator) is not mentioned in the article.
Answer: In my opinion, this is simply an application/extension of the law of total probability for sets, i.e., $$P(A) = \sum_i P(B_i) \times P(A | B_i)$$ where $\{B_i\}$ is a disjoint of partition of the sample space.
If you thought about the joint pdf analogous to $P(A \, \text{and} \, B)$, marginal and conditional PDF's in the obviously analogous way, one can see that $$ \iint f(x,y) \, dx \, dy = \int f_X(x) \, f_{Y|X}(y|x) dx$$
Keep that in the background. Now dealing with $P(Y \geq X(1/t - 1))$ you are dealing with two random variables $X$ and $Y$ simultaneously. A way to approach it (from the total law of probability perspective) is to condition on one of them ($X$ in this case, which allows to handle that random variable $X$ as a real number $x$), multiply the expression by probability of $X$ being approximately that $x$ (this is loosely speaking the density of $X$), then integrate across all possible values of $x$. This is really an application of the law of total probability.
Comment: well, to flush out the details, one has to be a bit more careful. The probability you are starting with is a double integral of the joint pdf over a specific region in $\mathcal{R}^2$. So some nuances get in the way. Hand waving over those (for the sake of clarity), I am saying $$P(Y \geq X \, c) = \int P(Y \geq X \, c \, | \, X) f_X(x) dx $$
Comment: So you mean that $f_{Y|X}(y|x)=P(Y|Y\geq x(\frac{1}t -1))$ ?
Comment: ... Then in the probability inside the integrand on the right, the $X$ (a random variable) can be replaced with $x$ (a real number)
Comment: ...essentially (again with some hand waving) one is dealing with the 2-d integral by slicing across "each $x$ coordinate" (which is technically not kosher because $\mathcal{R}$ is not countable).
Comment: I think I get it. Thanks for your additional comments.


How can I make entityQuery('commerce_order') return completed orders?

Question: Under Drupal Commerce 8.x-2.13 I find that the query
Drupal::entityQuery('commerce_order')

with no conditions attached returns ONLY incomplete orders (when called in the context of an API endpoint) - and if I apply any parameters exclusive of incomplete orders such as
$query->condition('state', 'completed');

it returns nothing. How can entityQuery be made to retrieve data on completed orders?
Answer: The solution is apparently to add $query->accessCheck(FALSE);.


table id is not passing from view to controller in ASP.NET MVC5

Question: I am using asp.net mvc5 app and I have partialView which I am using for both add and delete operations and I have separate actionResult to deal each requested according that is fire by jQuery Ajax functions.... I got figure problem when I try to edit record. it pick right record and display in screen in HttpGet actionResult but when I submit record with updated field, it doesn't update that in database and is because it doesn't send recordID {PK} back to action in controller unless I use hidden value for primary key in view... however with this I can't create new record!
partial View
@model DatabaseLayer.TableMappings.FeeZone

@using (Html.BeginForm())
{
 @Html.AntiForgeryToken()

FeeZone

    @Html.ValidationSummary(true)

        @Html.LabelFor(model => model.FeeZoneDescription, new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.FeeZoneDescription)
            @Html.ValidationMessageFor(model => model.FeeZoneDescription)

            <input type="submit" value="Save" class="btn btn-default">
            <input type="button" value="Cancel" class="btn btn-default" onclick="CancelPage();" />

}

controller Method
    [HttpGet]
    public ActionResult EditFreeZoneByID(string FreeZoneID)
    {
        int numID = Convert.ToInt32(FreeZoneID);
        return PartialView("Partial_CreateNewFreeZone", Q_UOF.GetFreeZoneByID(numID));
    }

    [HttpPost]
    public ActionResult EditFreeZoneByID(FeeZone obj)
    {
        try
        {
            if (ModelState.IsValid)
            {

                Q_UOF.EditSubject(obj);

            }
        }
        catch (DataException)
        {
            ModelState.AddModelError("FeeZone", "Unable to Save Changes.");
        }

        return RedirectToAction("FreeZone");
    }

Comment: why you can not create new record ? explain
Comment: if i use hidden record ID (refer to partial page code) then it can't... all i want to edit record using above partial view without putting hidden record ID
Comment: @toxic If you want to update an existing record then you have to send back the id, and to do that you need to have it in the page (hidden field)
Answer: You need to send the Primary Key value from your form to your Action method so that it can update the proper record. For this you definitly need to keep the ID in the form in a hidden field.
I am not sure what you mean by "You can not create new record if you keep the hidden variable". I do not think it is going to be a problem. You can use the same HttpPost action method to save New record and update an existing record. You may simply check the value of your primary key property and If it is 0, Add a new record , else update existing record
[HttpPost]
public ActionResult EditFreeZoneByID(FeeZone obj)
{
  if(obj.FreeZoneID==0)
  {
    //This is a new record. Save it

  }
  else
  {
    //Update an existing record now.
  }
  // to do : Return somethign valid or redirect
}

Comment: i prefer to keep separate two business concern but same time i don't want alot of crud operation related pages!


Add text to a label which already has a text C#

Question: Well I'd like to add a string to a Label which already has a text. It means that I want to append a text and not to overwrite the existing text.
label2.Content = string.Join("\n", customer);

I used string.Join but this does not work.
Comment: If its C# then you just add more text to it like ```label2.Text = label2.Text + "more text";```
Answer: Assuming customer is a string, you can concat the strings like that:
label2.Content = label2.Content + /*" " + */ customer;

Or simply:
label2.Content += customer;

If not a string:
label2.Content = customer.ToString();

If you want to append as a new line:
label2.Content += Environment.NewLine + customer;

Answer: label2.Content += "whatever"

Answer: What string.Join does is take an array of strings, and a separator, and returns a new string that joins all the elements by adding the separator:
e.g:
string[] customers = new string[] { "Customer A", "Customer B", "Customer C" };
string joinedString = string.Join("\n", customers);
//Output:
Customer A
Customer B
Custoemr C

What I think you want is to append some string joined by newlines, to an existing label.
For that you'll need to append this joinedString to the existing content of the label as
label2.Content += joinedString;

Image: WPF Joined String Label
Answer: I think this will solve your problem, I am thinking you have a customer class such as below
   public class Customer {
      public string FirstName {get; set;}
      public string LastName {get; set;}
      public string Description {get; set;}
   }

and again thinking you want to use your customer object as a string. So you should override ToString() method for your object.
Firstly override to string in your class like below:
   public class Customer {
      public string FirstName {get; set;}
      public string LastName {get; set;}
      public string Description {get; set;}

      //overriding
      public override string ToString()
      {
        return FirstName + " " + LastName + ", Desc: " + Description;
      }
   }

And now, you can use your customer object as a String easily,
label2.Content += customer.ToString();


Energy from Power

Question: I am working in MATLAB and I have 2 arrays. Current and Voltage flowing in a capacitance when I connect and disconnect it from the voltage. Of course I have a time_stamp vector in which there are all the samples of time at which I made the measurements.
I want to plot the power and energy associated to those arrays.
For the power I just need to do:
z1 = plot(time_stamp_ms,measured_voltage.*current,'-b','LineWidth',1);

Right?
Instead, how can I do to plot the energy?
Thanks for your time.
Answer: I think your power looks right. For energy, it's just power multiplied by time right so:
dt = diff(time_stamp_ms);
power = measured_voltage.*current;
energy = dt.*power(2:end);

well this gives the energy used between each time step. If you wanted the cumulative energy then:
energy_cum = cumsum(energy)

Comment: So to plot the energy I have to make first a for loop right, to store all the values of energy.
Comment: Yep . I did it now ;) Thanks for the help. I understood it.

Energy from Power


I am not able to increment string contains integer value?

Question: how to increment last string based on last integer ?For eg."foo" = "f001",
"foo9" = "foo10", "foo99" = "foo100","foo001" = "foo002"
Comment: Not entirely sure what you mean but it looks like you will have to parse the integer out of the string, do the logic and then reconstruct the string somehow.
Comment: yes i want to reconstruct the string after the increment of integer that is present in last as you can see in example.
Answer: One way you could do this...
<code>def increment_string(string)
  old_digits = string.scan(/\d+$/).first || ''
  string.sub(/\d+$/,'') + (old_digits.to_i+1).to_s.rjust(old_digits.size, '0')
end

p increment_string("beep")
=> "beep1"

p increment_string("beep5")
=> "beep6"

p increment_string("beep99")
=> "beep100"

p increment_string("beep004")
=> "beep005"
</code>


htaccess add language part to existing redirect rules

Question: I have quite a complex .htaccess with 30 redirect rules. Now the client wants to add language specific parts to the beginning of the urls.
Example: http://example.eu/sale should be http://example.eu/de/sale where "de" is the language code for one of the 5 languages.
I've found this:
RewriteRule ^(en|de|fr|ja|ru)/(.*)$  $2?language=$1 [L,QSA]

Is there a simple way to add this feature to existing rules? (Below is some of the existing rules)
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.eu$ [NC]
RewriteRule (.*) http://example.eu/$1 [R=301,L]

RewriteRule ^sale sale.php [NC]
RewriteRule ^brands/([^/]+) /designer.php?idnr=$1 [NC]
RewriteRule ^product/([^/]+)/([^/]+) /product.php?pid=$1&fsite=$2 [NC]

Answer:
Make sure all your R rules are at the top.
RIght after R rules you should have your new rule:
RewriteRule ^(en|de|fr|ja|ru)/(.*)$  $2?language=$1 [L,QSA]

Rest of internal rewrite rules should always end with these flags:
[L,QSA,NC]


Persistir JSON criando Objetos da Lista

Question: Boa tarde pessoal,
Estou com uma dúvida, tento persistir um JSON pela API:
<code>{
 ...
        "Analise": [{
            "nProcAnalitic": "SR-000446/2015",
            ...
        }]
...
}
</code>
E o serviço me responde 200:
<code>...
  "Analise": [
    {
      "id": null,
      "lotEntity": null,
      "nProcAnalitic": "SR-000446/2015"
...
</code>
Porem sem criar o objeto da listagem, somente o objeto pai.
Mapeamento:
@JsonProperty("Analise")
@OneToMany(mappedBy = "lotEntity")
private List analysis;
...
@ManyToOne
@JoinColumn(name = "id_lot")
private LotEntity lotEntity;
Answer: Acho que só falta você especificar a propriedade cascade=ALL na annotation oneToMany, assim o JPA vai persistir/alterar/excluir os objetos filhos em cascata.
Comment: Realmente, faltava o cascade.ALL, porem o objeto de referencia do pai dentro da listagem não gravou o id, ficando null...

...
  "Analise": [
    {
      "id": 3,
      "lotEntity": null,
Comment: Você deve setar a entidade pai na entidade filha manualmente. Eu aconselho você a usar a anotação @postPersist em um método na classe pai, assim que o JPA inserir a entidade pai, e antes de inserir os filhos, ele vai invocar esse método e você pode setar o objeto pai (this) no objeto filho (analise).
Comment: Opa, deu certo:     @PostPersist
    public void setObject() {
        this.analysis.forEach(a -> a.setLotEntity(this));
    } Obrigado

Persistir JSON criando Objetos da Lista