What happens if you anchor your pinkie and how do you avoid it?

Question: Beginner at Ukulele and thinking of doing guitar someday.
I've read some places where it's a bad habit to leave your pinkie resting on the surface of a guitar...
I tend to leave my pinkie in the air, not actually resting it. I'm not sure if that would be considered anchoring.
Still wondering how it'll affect my hand in both ways.
Answer: As a beginner, I wouldn't worry too much about this. There are good players who play with all kinds of techniques that others might find less than ideal. This is the kind of thing that you will revisit and change as you continue to play and develop.
That said, there are a few reasons not to anchor your pinky on the soundboard. I have heard some claims that anchoring the pinky to the top changes the sound of the instrument. This would probably only be significant on an acoustic instrument, and I am a little skeptical of this as a compelling reason to avoid such anchoring. Maybe on a classical guitar. But there are better reasons.
If you are using a pick when you play, anchoring the pinky may reduce mobility in your picking hand, or you may find that you have to switch your hand position when changing from picking single notes to freer rhythmic comping. Note that different tones can be achieved by picking closer to the bridge, or closer to the neck, but this requires mobility in the picking hand.
If you are playing in a finger-picking style, anchoring the pinky also removes one finger from the pool of fingers available for picking notes. That is, by anchoring you have three fingers and a thumb instead of four fingers and a thumb to play with. If you do try to use all four fingers when anchoring, you first have to pick up your pinky to get it into action, changing your hand position. Sometimes players use a pick, but also use the fingers occasionally to pluck individual strings, and you almost have to pick up an anchored pinky to play in this way.
The main advantage to anchoring the pinky seems to be that it provides a sort of reference to help you pick strings accurately. Some people allow the pinky to lightly touch the top of the instrument instead of firmly anchoring it. In this way the pinky can sort of slide around as the picking hand moves, improving mobility, and some feedback is provided to help keep picking accurate. This still has the disadvantage of requiring you to pick up the pinky and reposition the hand when you want to actually use your pinky to play. The best solution, in my opinion, is to avoid anchoring completely by allowing the picking hand to float over the strings. The palm or the heel of the hand can lightly brush the lower strings which aren't played (providing a palm mute), at the same time providing some feedback to help with picking accuracy.
Unrelated to pinky anchoring, but related to pinkies, often new players don't control the pinky on the fretting hand very well, allowing it to snap away from the fretboard when not in use. This means that when the pinky is needed to fret a note, it must move a further distance than it really needs to, and quickly, making accuracy more difficult. It is good to get into the habit of keeping all of the fretting fingers close to the strings so that they only need to move a short distance when they are needed.
Comment: Most folks who fingerpick rarely use pinkie if ever.  Many finger picking guitarist I know only use Thumb index and middle finger.  Anchoring with pinkie is common in fingerpicking for a variety of reasons including anchoring the picking hand to provide a stable reference point thus improving accuracy finding intended strings to pick/pluck.  I often anchor with pinky if I am playing with a plectrum but picking individual strings as opposed to strumming.  When strumming I never anchor with pinkie.
Comment: @RockinCowboy -- agree that many do anchor with the pinky, and that it is possible to play this way and do just fine (as I tried to indicate at the beginning of my answer). But there are good reasons to _not_ do this, too. It does all come down to individual playing goals and style. I do use my pinky often when I am fingerpicking, especially when I want to pluck five strings simultaneously. OP didn't mention fingerpicking vs plectrum, which is why I addressed both, but I have seem many plectrum players who do at least semi-anchor the pinky.


How is Cross validation used with non-machine learning problems?

Question: I am fairly new in the field of Information retrieval. I have basic knowledge about machine learning. I understand the purpose of CV in the context of Machine learning. However, I've become a bit confused when I saw CV used in the context of Information retrieval.
Here, in this paper the authors said: "values of the free parameters are set using leave-one-out cross validation performed over queries, where MAP serves as the optimization criterion."
How to perform CV over queries?
Here is what I am thinking, we should split the queries (in the test collection) into 10-folds,
For i in 10:

Using the training 90% part, we optimize the free parameter p
    (whatever the parameter is) for MAP (chose p that yield to the best
    MAP over queries)
Test the chosen K against the testing part.

The Question is: After 10 iterations, we end up with 10 different values of P, what value should I use?
Answer: A very typical method to set parameters of a model is through maximum likelihood estimation; i.e., set the parameters to values that maximizes the likelihood of the observed data.
I presume that when the authors say they set the parameters of the model through cross-validation, they chose the values of the parameters (or, more likely given that the discuss using MAP estimation, the hyper-parameters) that the minimizes the estimated out-of-sample error during cross-validation, for some given loss function.
So I would guess that the authors are using cross-validation to the pick the hyper-parameters and then fitting the full data using those hyper parameters selected by cross-validation.
Answer: Fine tunning in information retrieval is a way to report the optimized performance of your model with free parameters.
I cite Learning Information Retrieval Functions and Parameters on Unlabeled Collections,

After k folds, the average of the performance of M on all the subsets is reported.

In this case,
$MAP_{opt} = \frac{1}{10}\sum_{i=1}^{10}MAP_i$,
where $MAP_i$ is the $MAP$ value in the $K_i$ test set with the optimal $P_i$.
But, if you need one "optimal" $P$  you can choose the $P_i$ most frecuent as Probabilistic and machine learning-based retrieval approaches for biomedical dataset retrieval.


Proving that a Finite Field Over Its Prime Field Is Galois

Question:

In the above, I don't understand why the author needs to use another theorem to show that $f$ is separable.  Theorem 3.4.5 says that in a finite field, say $F$, the Frobenius automorphism gives us $F = F^p$, entailing that every irreducible polynomial in $F[x]$ is separable.  My thinking is, if $E$ exhausts all possible $p^n$ distinct roots of $f$, then $f$ just cannot have repeated roots.  This is pretty much the last statement in the paragraph.  So, was the author being redundant?
Comment: Books are written by living breathing human beings, not by machines. Accordingly, we may find inefficiencies and infelicities, and even (gasp) errors in books, even highly regarded ones.
Comment: Why can $f$ not have repeated roots if all $p^n$ elements of $E$ are roots of $f$? I don't see how these two are related...
Comment: I agree with Andy Tam: Lagrange shows that $f$ has $p^n$ distinct roots in $E$ and its degree is $p^n$. Hence it must be separable.
Answer: You're correct. This is not really needed and you know right away that f is separable. In general, the idea you have outlined is a common and excellent way to show that a polynomial is separable.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/524197)
Comment: How does this fail to provide an answer? They asked if they could shortcut the proof, and I said yes.
Comment: I don't remember making this review. Galois theory is not among my favorite subjects neither... Maybe your answer got mixed up with something because it is too short, like a comment.
Comment: Ok, TY .... Just making sure.


Get sum of radio button value using javascript function in table

Question: I am looking to get the sum of these 4 different values without query through a the radio buttons.
Here my javascript and html, once I click on submit, 0 appears in the total field, thank you for your help!
  <!DOCTYPE html>

                            noRisk
                            lowRisk
                            mediumRisk
                            HighRisk

How old are you?

                            <input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="0"checked>1-25
                            <input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="5">26-40
                            <input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="8">41-60
                            <input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="10">1-25

What is you BMI?

                            <input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="0" checked>0-25
                            <input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="0">26-30
                            <input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="9">31-35
                            <input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="10">35+

Does anybody in your family have diabetes?

                            <input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="0" checked>No
                            <input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="7">Grandparent
                            <input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="15">Sibling
                            <input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="15">Parent

How would you describe your diabete

                            <input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="0" checked >Low sugar
                            <input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="0">Normal sugar
                            <input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="7">Quite high sugar
                            <input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="10">High sugar

                     <input type="button" name="Sumbit" value="Submit" onclick="javascript:addNumbers()"/>
                     Total  = <input type="text" id="answer" name="answer" value=""/>

Comment: `id` attributes must be unique within an HTML document. There are also other shortcomings in your code, too many to list here in fact.
Answer: You have to specify that you only want the value of the checked checkboxes. You now select all the checkboxes. Try this instead:
function addNumbers()
{
    var val1 = parseInt(document.querySelector('input[name = "selectedAge"]:checked').value);
    var val2 = parseInt(document.querySelector('input[name = "selectedBmi"]:checked').value);
    var val3 = parseInt(document.querySelector('input[name = "selectedDiabete"]:checked').value);
    var val4 = parseInt(document.querySelector('input[name = "description"]:checked').value);
    var ansD = document.getElementById("answer");

    ansD.value = val1 + val2 + val3 + val4;
}

Answer: Here is working example.
Basically:

var sum = function(a, b) {
    return a + b;
};
var getPollResult = function() {
    var checkedRadioButtons = document.querySelectorAll('table input[type="radio"]:checked');
    return Array.prototype.map.call(checkedRadioButtons, function(radio) { return parseInt(radio.value, 10); }).reduce(sum, 0);
};
document.getElementById("submit").addEventListener('click', function() {
    document.getElementById("answer").value = getPollResult();
});


Prevenir ou remediar?

Question: Ultimamente tenho me preocupado demais em prevenir erros no código.
Contudo fiquei com essa duvida:

É melhor verificar (prevenir) ou remediar (Garantir existência)?

Digamos que se tenha :
$var = array(
    'name' => 'Guilherme',
    'lastName' => 'Lautert'
);

Qual o ideal verificar se o índice existe ou garantir que ele exista?
Verificar
if(isset($var['name'])){
    # code ...
}

Garantir
$default = array(
    'name' => null,
    'lastName' => null,
);

$var = array(
    'name' => 'Guilherme',
);

$var = array_merge($default, $var);

$lastName = $var['lastName'];

Edição
Como comentado pode ficas baseado em opinião, então supondo uma situação :
jQuery.ajax({
    url: APP + "/"+CONTROLADOR_ATUAL+"/jsonGetResposta",
    data: { cd : cd},
    dataType: 'json',
    async: false,
    success: function(msg){
        jQuery('#vl_total').val(msg.dados.vlTotal);
        jQuery('#nr_total').val(msg.dados.nrTotal);
    }
});

Qual o ideal, garantir que o índice existe no PHP, ou verificar se dados, vlTotal/nrTotal, existe no JS?
Comment: Depende do caso. Os dois códigos não são equivalentes, então é difícil compará-los.
Comment: Votei pra fechar por achar que é baseada em opiniões. Já tem uma resposta que começa com "particularmente prefiro...."
Comment: Desculpe me pelo, particularmente, digo isso pois seguindo os padrões de usabilidade deve se sempre que possível retornar um feedback para o usuário, mas não sei onde pretende empregar o código. Creio que devem avaliar melhor antes de julgar uma pergunta. Obrigado.
Comment: `$var += ['nome' => 'Wallace de Souza']`
Comment: @bigown dependendo do caso, ele pode usar os dois.
Answer: A pergunta pode ser interpretada como baseada em opniões, pois, como diria um amigo meu: Tudo depende.
Você necessariamente precisa que os dados existam?
Então é necessário que os mesmos sejam avaliados devidamente.
Você quer tratá-los como valores opcionais? Então, utilize os valores padrões.
implementações existentes
Em relação essa forma de utilizar esse default values(valores padrão), a utilização da mesma geralmente se dá quando um argumento ou um valor é opcional.
Nesse casos, é poderíamos nos lembrar dos parâmetros opcionais dados para algumas funções. Um valor callable por exemplo que pode ter o valor null por padrão.
Eu já vi alguns frameworks, como o CakePHP 2, que utilizam-se desse "valores padrões" para tratar um array como se fosse um argumento  nomeado. Vou mostrar um exemplo clássico em casos onde precisaria por exemplo de salvar dados de uma model, onde a data de criação é inserida automaticamente se a mesma não for passada.
Exemplo:
function saveData(array $data)
{
     $data += ['created_at' => new DateTime;];

}

Esses exemplo permitem fazer:
saveData(['name' => 'Wallace', 'created_at' => new DateTime('-1 day')]

ou
saveData(['name' => 'Wallace']);

Ainda falando sobre os argumentos nomeados, podemos ainda "misturar" o "previnir" com o "remediar".
Por exemplo:
 saveData(array $data)
 {
        $data += ['data' => new DateTime];

        if (! isset($data['name']) {
            throw new BadCallMethodException('É necessário passar "name"');
        }
 }

Então, há casos onde você vai ter que "previnir" (validar), e outros que vai querer "remediar" (tornar opcional).

Prevenir ou remediar?


PostgreSQL ActiveRecord Query Optimization

Question: I'm new to RoR and I need a query that returns the same instances as the following definition of queue :
@all = User.all
@membersOfActivity = User.where(id: User.joins(:memberships).where("activity_id = ?", session[:current_activity_id]))
@usersIAlreadyLiked = User.where(id: User.joins(:likes).where("activity_id = ? AND activity_likes_user IS NOT NULL", session[:current_activity_id]))
@notWanted = @membersOfActivity + @usersIAlreadyLiked
@queue = @all - @notWanted

However, I understand how inefficient the query I just wrote is for it downloads all the Users first to then select the complement. Do you have any idea on how to make it more efficient and directly select the complement of @notWanted? I tried several queries but none of those worked.
If you think you have a better solutions please let me know! Thanks!
EDIT :
Each user has many memberships, that connect a user with an activity. So each activity has also many membership. Each membership has a user_id and an activity_id.
Each user has many likes, and each like connects a user and an activity. Therefore each activity has also many likes. A like has a user_id, activity_id, user_liked_activity, and activity_liked_user.
user_liked_activity is NULL if the user did not express an opinion about the activity, TRUE is the user liked the activity, and FALSE if the user disliked the activity. Viceversa for activity_liked_user.
Comment: Pertinent question, I apologize! You'll find a brief explanation on the edit. @moveson
Answer: Here's a Rails 5 solution, using not syntax. At first glance, this appears to be similar to your original solution, but this runs only one query, built from the separate excludable categories (members and already_liked).
class User < ApplicationRecord
  has_many :likes
  has_many :memberships

  def self.queue(current_activity_id)
    members = User.joins(:memberships).where(memberships: {activity_id: current_activity_id})
    already_liked = User.joins(:likes).where(likes: {activity_id: current_activity_id, activity_liked_user: [true, false]})

    where.not(id: members).where.not(id: already_liked)
  end
end

You will call this from your controller like so:
@queue = User.queue(session[:current_activity_id])

As I understand the problem, for the current session activity, we want a query that will return all users except those that belong to one of two categories: (1) Those who are members of the activity, represented by users having a membership linked to the current activity, and (2) those who already have a "liked" rating from the activity, represented by users having a "like" linked to the current activity for which activity_likes_user is either true or false (but not nil).
We establish ActiveRecord relations for each category, but we don't call anything that would actually trigger a query. Category 1 is members, and Category 2 is already_liked.
Now we build a query on the User model (this is implied, because we are calling from within a class method on the User class) asking for users where id is not one of the members and is not one of the already_liked.
There may be a more elegant solution, but this does work, and I believe it handles edge cases properly, though you should build tests to verify this.
Comment: I've completely revamped the solution. I built a Rails 5 app and tested it, and it appears now to be working properly.
Comment: That's actually what I tried initially but I get the following error :
"Relation passed to #or must be structurally compatible. Incompatible values: [:includes, :references]"
Comment: I get 'PG::UndefinedColumn: ERROR:  column activities.activity_likes_user does not exist', I think it is from the last part : 'activities: {activity_likes_user: true}'. Thank you for your answer though, I'm still trying to understand the syntax and what your query actually does so I'm having some problems debugging it :/ @moveson
Comment: That works, except for we also don't want the users where activity_likes_user: false (we only want the ones that are null) so maybe we do need the or?@moveson
Comment: Your understanding of what the query is almost correct, expect (2) should include also the ones that have been disliked by the activity (activity_likes_user = false). Now does [true, false] the syntax for "or" (true or false)? The query seems right to me but it's not returning the right values, it's returning different values from the one in my question. Thanks again for the help so far!
Comment: Could the problem be that there aren't always records for each like (if the user didn't like the activity, and the activity didn't like the user -> there is no record) so when it goes to look for the values on the second part of the query it doesn't find any record and it returns no users? Because that is what is happening, it's returning no users :/ @moveson


git stash pop prints "deleted by us" for file that was never created on master

Question: I am relatively new to git (coming from svn).
I perform the following steps which are mainly that I edit a file on a branch, perform a stash and then try to apply the stash to the master (which does not have this file).:
user1:~/gittest$ ls
user1:~/gittest$ git init
Initialized empty Git repository in /home/user1/gittest/.git/

user1:~/gittest$ touch file1
user1:~/gittest$ git add file1
user1:~/gittest$ git commit -m "committing file1"
[master (root-commit) 7c29335] committing file1
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 file1

user1:~/gittest$ git checkout -b br1
Switched to a new branch 'br1'

user1:~/gittest$ touch file2
user1:~/gittest$ git add file2
user1:~/gittest$ git commit -m "committing file2"
[br1 b565401] committing file2
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 file2

user1:~/gittest$ echo "updated.." >> file2
user1:~/gittest$ git add file2
user1:~/gittest$ git stash
Saved working directory and index state WIP on br1: b565401 committing file2
HEAD is now at b565401 committing file2

user1:~/gittest$ git checkout master
Switched to branch 'master'

user1:~/gittest$ git stash pop
CONFLICT (modify/delete): file2 deleted in Updated upstream and modified in Stashed changes. Version Stashed changes of file2 left in tree.

user1:~/gittest$ git status
On branch master
Unmerged paths:
  (use "git reset HEAD <file>..." to unstage)
  (use "git add/rm <file>..." as appropriate to mark resolution)

        deleted by us:   file2

no changes added to commit (use "git add" and/or "git commit -a")

My question is why does git print the message "deleted by us" since file2 was never created on master and thus never deleted.
Is this a misleading message, or am I missing something about the way git works.
Answer: It's just a misleading message; it's saying deleted, but it was just never there, it doesn't make a distinction between files that were there before and are now deleted, or files that were never there at all, if you look at it from a 'branch perspective'.
file2 is actually a known file in your git repository, so in some sense it got deleted when you checked out master.
Comment: But is this behavior unavoidable? Would it be impossible to fix it, due to the way merging is performed in git (e.g. it has no way to know whether this file was there or not)?
Comment: I would assume it can be fixed, and maybe it is for more recent version of git, but I'm not familiar with the git source code...


Geolocation in Flash

Question: I'm building a small web app in Flash. Is there a solution to get the geo-location of a user?
Answer: The easiest way is to interface with a JavaScript function.
In your HTML:
<code>    <script>
        function getGEO()
        {
            // First check if your browser supports the geolocation API
            if (navigator.geolocation)
            {
                //alert("HTML 5 is getting your location");
                // Get the current position
                navigator.geolocation.getCurrentPosition(function(position)
                {
                    lat = position.coords.latitude
                    long = position.coords.longitude;
                    // Pass the coordinates to Flash
                    passGEOToSWF(lat, long);
                });
            } else {
                //alert("Sorry... your browser does not support the HTML5 GeoLocation API");
            }
        }
        function passGEOToSWF(lat,long)
        {
            //alert("HTML 5 is sending your location to Flash");
            // Pass the coordinates to mySWF using ExternalInterface
            document.getElementById("index").passGEOToSWF(lat,long);
        }
    </script>
</code>
Then, in your Application, once your map is ready, put this in a function:
<code>     //for getting a user's location
            if (ExternalInterface.available)
            {
                //check if external interface is available
                try
                {
                    // add Callback for the passGEOToSWF Javascript function
                    ExternalInterface.addCallback("passGEOToSWF", onPassGEOToSWF);
                }
                catch (error:SecurityError)
                {
                    // Alert the user of a SecurityError
                }
                catch (error:Error)
                {
                    // Alert the user of an Error
                }
            }
</code>
Finally, have a private function ready to catch the callback.
<code>    private function onPassGEOToSWF(lat:*,long:*):void
    {
        userLoc = new LatLng(lat,long);
        map.setCenter(userLoc);

    }
</code>
Comment: Awesome! Thank you. Do you have an idea how to get the geolocation from an Adobe Air desktop app also?
Comment: Damn, I thought there would be a workaround available. Thanks though.
Comment: I meant to say that *I* have never worked with Air, so I don't know how to do it. Sorry about the poor wording.

Geolocation in Flash


Why smoothCon gives different estimates of smooths than mgcv?

Question: I am learning gam by myself. I tried to find posts that can help me to finding and understanding smooth functions i.e., basis functions from gam using mgcv. From a post I found I can use smoothCon to estimate basis functions without explicitly from the model. However when I did so, I observed smoothCon and mgcv$smooth doesnt match.
Here an reproducible example of what I did:
library(mgcv)
set.seed(1)
x.1=runif(80)
x.2=runif(80)
fx.1=sin(x.1*.2)
fx.2=cos(x.2)
fx=fx.1+fx.2
y=rbinom(80,1,fx/(1+exp(fx)))

gam.m= gam(y~s(x.1,bs="cr",k=4)+s(x.2,bs="cr",k=4), family=binomial, method="REML")

Now, I extracted basis functions
smooth.mgcv= predict.gam(gam.m,type="lpmatrix")
smooth.x.1= smooth.mgcv[,2:4]  #basis functions of x.1#

then from smooth.Con
smooth.create=smoothCon(s(x.1,bs='cr',k=4),data=data.frame(x.1=x.1),knots=NULL)

, but this two are giving different output. How do this basis functions work?
Answer: smoothCon() only creates the basis functions for the requested smooth, and by default it doesn't apply identifiability constraints. gam() estimates the coefficients for each basis function.
The specific source of the difference here is the most likely due to the first feature; by default absorb.con is set to FALSE in smoothCon(), which means that the constant function (in this case) is in the span of the basis. If you apply the same identifiability constraint that was applied when fitting via gam(), the basis functions evaluated at the same data point should match whether you use "lpmatrix" in the predict() call or smoothCon().
More correctly, you should use PredictMat() to evaluate the basis functions at specific locations.
Here's an example using some utilities from my gratia package to make this a little easier
library("mgcv")
library("gratia")

# simulate data
df <-  data_sim("eg1", n = 2000, dist = "binary", seed = 42)
m <- gam(y ~ s(x0, bs = "cr") + s(x1, bs = "cr") + s(x2, bs = "cr") +
             s(x3, bs = "cr"),
         data = df, family = binomial, method = "REML")

# generate data to evaluate the basis functions at
ds <- data_slice(m, x0 = evenly(x0, n = 10))

# create the basis expansion as `gam()` would do it
sm <- smoothCon(s(x0, bs = "cr"), data = df, absorb.cons = TRUE)[[1]]
# evaluate this basis at the 10 evenly spaced values of x0
p1 <- PredictMat(sm, data = ds)

# compute the lp matrix at the same set of points
p2 <- predict(m, newdata = ds, type = "lpmatrix")
# pop off the intercept to aid comparison
p2 <- p2[, -1]

# compare
identical(p1[, 1], unname(p2[, 1]))

but extracting the smooth model matrix from the object created by smoothCon() also works
Also, don't use predict.gam(); this function is an S3 method and you should really only be calling predict().


(Exponential) Growth of Operator Norm of Uncentered Maximal Function

Question: Define the uncentered Hardy-Littlewood maximal operator $M$ by
$$Mf(x):=\sup_{x\in B}\dfrac{1}{\left|B\right|}\int_{B}\left|f\right|,$$
where we the supremum is taken over all (open) balls $B$ containing the point $x\in\mathbb{R}^{n}$. Let $f_{0}$ denote the characteristic function of the unit ball. I am trying to show that for $1<p<\infty$,

$$\lim_{n\rightarrow\infty}\dfrac{\left\|Mf_{0}\right\|_{L^{p}}}{\left\|f_{0}\right\|_{L^{p}}}=\infty
> \tag{1}$$

by following the suggestion in Exercise 2.1.8 of L. Grafakos, Classical Fourier Analysis (Third Edition). Actually, I would like to show that the growth of the $L^{p}\rightarrow L^{p}$ is exponential in the dimension $n$, but I'll settle for the above.
Let $B_{0}$ denote the unit ball, and for $\left|x\right|>1$, let $B_{x}$ be the ball with center $c$ and radius $r$ given by
$$c=\dfrac{(\left|x\right|-\left|x\right|^{-1})}{2}\dfrac{x}{\left|x\right|},\quad r=\dfrac{(\left|x\right|+\left|x\right|^{-1})}{2}$$
Observe that $x\in B_{x}$, so
$$Mf(x)\geq\dfrac{1}{\left|B_{x}\right|}\int_{B_{x}}\left|f_{0}\right|=\dfrac{2^{n}}{(\left|x\right|+\left|x\right|^{-1})^{n}\left|B_{0}\right|}\left|B_{x}\cap B_{0}\right|$$
Since
\begin{align*}
\dfrac{1}{4}\left(\left|x\right|-\left|x\right|^{-1}\right)^{2}+1&=\dfrac{\left|x\right|^{2}}{4}+\dfrac{\left|x\right|^{-2}}{4}+\dfrac{1}{2}=\left(\dfrac{\left|x\right|+\left|x\right|^{-1}}{2}\right)^{2},
\end{align*}
we see that $B_{x}\cap B_{0}$ contains $B_{x}\cap B_{0}$ contains a "half-ball" of $B_{1}(0)$and a hyperspherical cap of height $\left|x\right|^{-1}$ and radius $(\left|x\right|+\left|x\right|^{-1})/2$, which we denote by $C_{x}$. In particular,
$$\left|B_{x}\cap B_{0}\right|\geq\dfrac{1}{2}\left|B_{0}\right|+\left|C_{x}\right|$$
My initial thought was to simplify things and ignore the term $\left|C_{x}\right|$ to get the lower bound
$$Mf(x)\geq\dfrac{2^{n-1}}{(\left|x\right|+\left|x\right|^{-1})^{n}},\quad\forall \left|x\right|>1$$
Thus,
\begin{align*}
\dfrac{\left\|Mf\right\|_{L^{p}}}{\left\|f_{0}\right\|_{L^{p}}}&\geq\dfrac{2^{n-1}}{(n^{-1}\omega_{n-1})^{1/p}}\left(\int_{\left|x\right|>1}\dfrac{1}{(\left|x\right|+\left|x\right|^{-1})^{np}}dx\right)^{1/p}\\
&=\dfrac{2^{n-1}}{(n^{-1}\omega_{n-1})^{1/p}}\left(\int_{1}^{\infty}\dfrac{r^{n-1}}{(r+r^{-1})^{np}}dr\int_{S^{n-1}}d\theta dr\right)^{1/p}\\
&=2^{n-1}n^{1/p}\left(\int_{1}^{\infty}\dfrac{r^{n-1}}{(r+r^{-1})^{np}}dr\right)^{1/p}
\end{align*}
I'm having trouble giving a useful asymptotic for the integral factor above. Perhaps, I errored in ignoring $\left|C_{x}\right|$. I would greatly appreciate any suggestions in how to proceed.
Edit 1: Plugging in some special values of $p$ into Wolfram Alpha, it looks like hypergeometric functions might be relevant here.
Comment: You can use the Laplace method to get an asymptotic for the integral. Doing so with the help of a computer I get (assuming no typos) $$2^{n-1}n^{1/p}\left(\int_{1}^{\infty}\dfrac{r^{n-1}}{(r+r^{-1})^{np}}dr\right)^{1/p} \sim \frac{1}{2} \left[ \frac{\pi p n}{p^2-1} \left(\frac{(p+1) (p^2-1)^p}{p^{2p} (p-1)}\right)^n \,\right]^{1/(2p)}.$$ Then it's just a matter of showing that the quantity within the parentheses is positive, which seems to be true.
Comment: Er, I meant "greater than $1$", not positive.
Comment: @AntonioVargas: I was not familiar with Laplace's method until your comment. many thanks; a quantity of the type on the RHS was for what I was looking.
Comment: @AntonioVargas: I computed the derivative of the quantity within the parentheses and it is strictly negative for $p>1$. As $p\rightarrow 1^{+}$, the quantity tends to $4$. And as $p\rightarrow \infty$, the quantity tends to $1$.
Answer: I've met this question recently. Yet I solved it by the same means:
$$||\tilde M||_p^p\geq \frac{\int(\tilde{M}f_0(x))^pdx}{\int f_0(x)^pdx}\geq\frac{2^{p(n-1)}}{V_n}\int_{x\geq 1}(|x|+|x|^{-1})^{-pn}dx=I$$
The only question is to estimate the integral. To this end, we need it to take a "suitable" form:
$$I=n2^{p(n-1)}\int_{r\geq1}\frac{r^{pn+n-1}}{(1+r^2)^{pn}}dr\\=n2^{p(n-1)}\int_{\pi/4}^{\pi/2}(\cos\theta)^{pn-n-1}(\sin\theta)^{pn+n-1} d\theta\\=n2^{1-p}\int_{\frac{\pi}{4}}^{\frac{\pi}{2}} (2\sin \theta \cos \theta)^{pn-1}(\tan \theta)^nd\theta.$$
Observing that $\tan\theta\geq1$ and $\sin2\theta=2\sin \theta\cos\theta$, we obtain
$$I\geq n2^{-p}\int_{0}^{\frac{\pi}{2}} (\sin u)^{pn-1} du.$$
So $||\tilde{M}||_p\rightarrow \infty$ as $n\rightarrow \infty$ due to Wallis formula, and the growth is much slower than "exponential".
Comment: Welcome to MSE. It is in your best interest that you type your posts (using [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)) instead of posting links to pictures.


Python reverse sort wrong answer?

Question: I'm solving a problem at Codility and at one step I needed to reverse sort a list of chars of digits. But python returned a very surprising result (at least for me)
Here is code:
N = 231
result = [str(x) for x in str(N)]
result.reverse()
print(result)
And print result is:

['1', '3', '2']

But when I used result.sort() before result.reverse() it returns correct result? Does anyone has any idea ?
Comment: `reverse` means reverse, not "sort in reverse order".
Comment: Ok, ok  sorry and thank you :D
Answer: .reverse() reverses the list. It does not sort it in reverse. Use result.sort(reverse=True).

Python reverse sort wrong answer?


Binding a host address to localhost in Linux

Question: How to bind the example.com address to the local box?
I'm enhancing a website, which is written so that 'example.com' is hard coded as its host. How do I do a loop back in Firefox in response to a 'example.com' request?
Answer: Add '127.0.0.1 example.com' to the /etc/hosts file:
<code>sudo bash -c 'echo 127.0.0.1    example.com >> /etc/hosts'
</code>
This will be system wide, not just for firefox.
Comment: life saving trick. for windows users, you can edit windows\system32\drivers\etc\hosts to get same result.


Simplify $(xy^{-1})/(y^2/x^3)^{-1}$

Question: Need to simplify this equation:
$$(xy^{-1})/(y^2/x^3)^{-1}$$
So far I have
$= \frac{x/y}{1/(y^2/x^3)}$
But don't know what to do next. Any help much appreciated
Comment: Please make sure I edited your question correctly
Comment: Can you explain how you got there? Just so that we know what techniques you are (and aren't) familiar with.
Answer: We have $$(xy^{-1})/(y^2/x^3)^{-1}=(xy^{-1})\times\left(\frac{y^2}{x^3}\right)^{+1}=\frac{x}{y}\times\frac{y^2}{x^3}=\frac{y}{x^2}$$ provided $$x\ne0, y\ne0$$
Comment: ;-) $+^++^++^++$
Comment: @amWhy: It is very kind of you considering my small attempts here. Thank you. :)
Answer: Hint: Use $x^a x^b = x^{a+b}$ and $1/x^a = x^{-a}$ to simplify equation to form something like $x^a y^b$.

Simplify $(xy^{-1})/(y^2/x^3)^{-1}$


open sets in affine space are not affine varieties - easy proof

Question: In a previous post, I have defined a generalized principal open set:
$$D_{f_1,\dots,f_n}=\mathbb{C}^m\setminus \{f_1 = \dots = f_n =0\}$$
where $f_1,\dots,f_n$ are polynomials in $m$ variables. This is clearly a quasi-protective variety, and the question is when is it affine. (As mentioned below, these are just zariski-open sub-spaces of $\mathbb{C}^n$; The definition was a bit more general in the previous post).
In the previous post, in one of the solutions it was claimed that in non-degenerate cases (like $f_1 = \dots = f_n$) this is not an affine variety; the proof uses a vast theorem, that I do not want to use.
$$\\$$
Here I give the precise proposition, including an easy proof:

if $\gcd(f_1,\dots,f_n)=1$ then $D_{f_1,\dots,f_n}$ is not an affine variety

Proof:
We prove that if $\gcd(f_1,\dots,f_n)=1$ then $D_{f_1,\dots,f_n}$ is not an affine variety. On the contrary, Assume $D_{f_1,\dots,f_n}$ is affine.
Look at the inclusion map $i:D_{f_1,\dots,f_n} \to \mathbb{C}^m$: this induces a map $i_*:\mathbb{C}[\mathbb{C}^m]\to \mathbb{C}[D_{f_1,\dots,f_n}]$, where $\mathbb{C}[\cdot]$ is the coordinate ring.
Let $\frac{p}{q} \in \mathbb{C}[D_{f_1,\dots,f_n}]$; Thus $q$ is nonzero on $D_{f_1,\dots,f_n}$, that is
$$\{q=0\} \subseteq \{f_1 = \dots = f_n=0\}$$
This assertion turns out to be not that trivial - since $p,q$ may have common zeros, and thus we must look at all the representation of the form $\frac {p'}{q'}$, with $p',q'$ coprime and such that $p'q=pq'$ on $V$ - but by the Identity theorem it is also true on $\mathbb{C}^n$. Since the polynomial ring is a UFD, we have that each prime factor $q_i$ of $q$ divides pq', and can not divide $p$ so must divide $q'$, and thus $q|q'$. Similarly $q'|q$. so $q=\alpha q'$ with $\alpha\in \mathbb{C}$, which means they have the same zeros.
Thus
$$\langle q \rangle \supseteq \langle f_1,\dots,f_n \rangle$$
So each $f_i$ can be divided by $q$, thus $q \mid \gcd(f_1,\dots,f_n)=1$ so $q$ is constant, meaning $\frac{p}{q}$ is a polynomial, so is defined on the whole $\mathbb{C}^m$, and thus
$$\mathbb{C}[D_{f_1,\dots,f_n}] = \mathbb{C}[\lambda_1,\dots,\lambda_m]$$
Thus the map $i_*:\mathbb{C}[\lambda_1,\dots,\lambda_m] \to \mathbb{C}[\lambda_1,\dots,\lambda_m]$ is the identity, and since the functor $f \mapsto f_*$ is a $1-1$ bijection (since $D_{f_1,\dots,f_n}$ is affine), we get that $i:D_{f_1,\dots,f_n} \to \mathbb{C}^m$ should be an isomorphism, but is not onto.
Is this proof true?
Comment: One basic issue here. You write $p/q\in \mathbb{C}[V_{f_1,f_2,\ldots}$ and then say $q$ has no zeroes on this open set. While correct (am assuming that $p/q$ is in reduced form) you still need to say a bit more. For example, wherever $q$ has a zero in this open set, $p$ may also have a zero and they may cancel each other (as often happens in such situations).  So, you have to say how UFD properties are used.
Comment: Your notation  clashes  with the standard notatation used in  in **every** book $V(f_1,  \dots,f_n )=\{f_1 = \dots = f_n =0\}$. You should write $D(f_1,  \dots,= f_n)=\mathbb C^n\setminus V(f_1,  \dots,f_n )$.
Comment: "Generalised principal open set" is a funny name for this. As it turns out, every Zariski open set is of this form.
Comment: @ZhenLin Sure, this is the definition. Is the proof true?
Comment: @ZhenLin Yes, maybe it's better to just call it an open set :)
Comment: Maybe it's okay because you're working in affine space? Everything should live in the function field $k(x_1, \dots, x_n)$ and because you haven't taken a quotient maybe the question of whether a given representative actually "evaluates" to the function is not so difficult.
Comment: Slight nitpick: you might have to worry about taking the radical of $(q) $ (just removing multiple factors) right? I don't think it affects the proof much.
Answer: Your highlighted "precise proposition" is unfortunately not true.
For example $D(zx,zy)=\mathbb C^3\setminus \{zx=zy=0\}$ is not affine although $\gcd (zx,zy)=z\neq 1$.
Comment: You are right; the direction I have regarded as the easy one turns to be flase. I have edited the post - Is this direction true? And what can be said about the other direction - can an explicit degenerecy condition be given?
Comment: Yes, the new highlighted statement is correct, unless $D(f_1,...,f_n)$ is empty (and thus affine!). However I didn't check your proof.
Comment: I have edited the proof so I hope it is true now. Can you go over it? Thanks


Select Banco Oracle - Constraint

Question: Bom dia pessoal, se alguém puder me ajudar, preciso de uma consulta que me retorne as constraints de uma tabela e seus tipos de dados. Estou tentando montar um gerador de procedure para facilitar, demora muito para ficar criando procedures. Neste select não me traz o tipo de dados.

SELECT DISTINCT SYS.USER_CONS_COLUMNS.COLUMN_NAME FROM USER_CONSTRAINTS NATURAL JOIN SYS.USER_CONS_COLUMNS WHERE TABLE_NAME = 'PRODSERV';
Comment: Algo do tipo? http://stackoverflow.com/questions/1729996/list-of-foreign-keys-and-the-tables-they-reference
Comment: Me parece que nenhuma delas me trouxe ou que eu preciso, por exemplo eu preciso do campo tipo COD_UNID e o seu tipo de dado por exemplo NUMBER, para que eu possa criar os parâmetros da procedure. create or replace procedure sp(SP_CODI_UNID number).....
Comment: o type da coluna se tem em USER_TAB_COLUMNS  SELECT USER_CONS_COLUMNS.COLUMN_NAME , USER_TAB_COLUMNS.DATA_TYPE
FROM USER_CONS_COLUMNS, USER_TAB_COLUMNS
WHERE USER_CONS_COLUMNS.TABLE_NAME =  USER_TAB_COLUMNS.TABLE_NAME
AND USER_CONS_COLUMNS.COLUMN_NAME =  USER_TAB_COLUMNS.COLUMN_NAME
Comment: Pessoal utilizei da forma que eu tinha imaginado mesmo, que e a mesma ideia do Reginaldo Rigo, utilizei duas consultas e um for duplo, criando uma nova lista apenas com as constraints...
Comment: Ulisses, o site funciona diferente de um fórum, o nosso "resolvido" é quando você marca uma resposta como aceita, como você já fez, isso já marca a pergunta como "resolvida" :)
Comment: Tudo bem, obrigado.
Answer: Numa consulta unica não é possível, mas em duas ou mais seria assim:
select COLUMN_NAME, DATA_TYPE from
all_tab_columns where table_name = 'TABELA'

SELECT constraint_name, constraint_type
from user_constraints where table_name = 'TABELA'

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = 'TABELA'

Select Banco Oracle - Constraint


API segura depende inteiramente do desenvolvedor ou plataforma?

Question: Quais os desafios que o programador encontra para tornar sua API totalmente segura? Quando falo de segurança me refiro diretamente se a aplicação expõe as informações do cliente ou mesmo deixa sua aplicação fácil de ser penetrada.
Depende inteiramente do programador ou da plataforma? (Android ou Iphone).
Comment: Faro. Você poderia definir o que é "seguro"? Note que nada é *totalmente seguro*, entretanto, se especificar alguns requisitos mínimos pode-se chegar a um conceito *razoável*.
Comment: Quando falo de segurança me refiro diretamente se a aplicação expõe as informações do cliente ou mesmo deixa sua aplicação fácil de ser penetrada.
Answer: Se entendi bem, depende de ambos.
A API muitas vezes é o diferencial de cada linguagem: eu, por exemplo, acho o C++ superior ao Java como linguagem. Mas a API do Java é extensivamente mais prática que a Biblioteca Padrão do C++. Por isso, se eu tivesse que escolher entre as duas para um projeto comercial, provavelmente escolheria Java.
Semelhantemente acontece com as APIs de sistemas: Depende de quem desenvolveu a API e de quem a consome. Mas depende principalmente de quem a desenvolveu.
Se a API foi desenvolvida bem seguramente mas o cliente a usa de mal modo, esse problema é exclusivo do cliente. O cliente poderá expor mal seus dados, mas isso não afetará de modo algum o servidor.
Já se a API foi desenvolvida com brechas de segurança, até o mais cuidadoso dos clientes pode ter sua segurança afetada. Ele não pode fazer mudanças de segurança no servidor; ele depende daquela API ruim. O máximo que ele pode fazer é ser cuidadoso em sua aplicação e torcer pra que ninguém tente usar o servidor mal-desenvolvido para prejudicá-lo.
Resumindo: Depende de ambos, mas principalmente de quem desenvolveu a API -- e não de quem a consome.
Answer: Totalmente segura não existe. A primeira pergunta que você deve fazer é: Seguro a que tipo de ataques?
Quando eu ouço a palavra API, eu entendo que a pessoa esteja fazendo alguma biblioteca para fazer algo. Para melhorar a API do Android, a gente tem que codar para a API do Android. Agora, se quer melhorar um determinado software, depende do que você quer fazer. Meu sistema vai fazer transações financeiras. Beleza, aí você tem que tomar várias medidas. Usar um teclado próprio para não haver keylogger. Verificar se o celular está rooteado. Fazer requisições https. Para se ter segurança, é preciso pensar como atacante
Answer: A segurança de informações em sistemas depende quase inteiramente do desenvolvedor. Não importa quantas configurações e quantos padrões de segurança uma aplicação use, você não terá segurança se:

Concatenar valores em queries.
Listar dados confidenciais numa tela ou relatório por algum equívoco.
Permitir ao usuário administrador gerenciar o Controle de Acesso e este dar permissão desnecessária para os usuários
Não proteger a rede adequadamente
Não proteger o servidor de banco de dados adequadamente

Enfim, independentemente da API, se a implementação dá acesso legítimo a dados que alguém não poderia acessar, de nada adianta colocar várias camadas de segurança.
O que poderia diferenciar uma API da outra pode ser a facilidade e flexibilidade para declarar as permissões necessárias.
Obviamente, não considerei possíveis bugs nas APIs, por isso a sugestão é usar as que já estão consolidadas e são bastante usadas, de forma que possíveis brechas são identificadas pela comunidade de desenvolvimento.
Answer: Os aspectos de segurança residem sobre o seu servidor e não sobre o Android ou iOS, ambas as plataformas são robustas e estão maduras em termos de segurança.
Sugiro fazer em cima de um bom firewall e servidor de aplicação consolidade pois eles já passaram por um crivo de segurança grande no passado, se você optar por fazer um ambiente servidor em nodejs vai estar sujeito à muitos problemas de vunerabilidades.


How to analyze BRFSS survey data in R? How to set `id`?

Question: I am trying to analyze BRFSS in R with weights for complex survey design using the survey package. I am confused as to what to set id to. The BRFSS manual says to set id to 1 but I found other code online that recommends setting id to psu. When I run both to look at a single variable, I got the same answer so perhaps they are no different.
Could you please explain if there is a difference between setting the id to 1 or setting it to psu?
My current code looks as follows:
# Set options for allowing a single observation per stratum options
options(survey.lonely.psu = "adjust")
# Create survey design
brfssdsgn <- svydesign(
    id=~1,
    strata = ~ststr,
    weights = ~llcpwt,
    data = BRFSS)

brfss_design <-
    svydesign(
        id = ~ xpsu ,
        strata = ~ xststr ,
        data = brfss_df ,
        weight = ~ xllcpwt ,
        nest = TRUE)

Answer: set it to psu.  there's a mistake in the R code shown in
https://www.cdc.gov/brfss/annual_data/2017/pdf/Complex-Smple-Weights-Prep-Module-Data-Analysis-2017-508.pdf
their sas code and R code will not give the same results.  the sas code looks correct, and has the psu specified.
quoting from their text
In all cases, the variable _STSTR should be used for stratification,
and the variable _PSU should be used for clustering, in complex sampling analyses


asp.net mvc index action is called automatically after ajax

Question: I have an action that creates a record in the database:
 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Name,Description")] SampleViewModel sampleVM)
    {
        try
        {
            _service.Add(sampleVM);
            this.ShowMessage(new ToastMessage(ToastType.Success, "Record Added", ToastrDisplayType.TopLeft));
        }
        catch (Exception ex)
        {
            this.ShowMessage(new ToastMessage(ToastType.Error, ex.Message, ToastrDisplayType.TopLeft));
            return Json("failed");
        }

        return Json("success");
    }

this Action is called by AJAX:
 $().ready(function () {
        $("#btnSave").click(function () {
            var serviceURL = '';

            var sample = {
                "Id": $('#hdnId').val(),
                "Name": $("#txtName").val(),
                "Description": $("#txtDescription").val(),
            };

            if (save_method == 'add') {
                serviceURL = '@Url.Action("Create", "Samples")';
            }
            else if (save_method == 'edit') {
                serviceURL = '@Url.Action("Edit", "Samples")';
            }

            $.ajax({
                type: "POST",
                url: serviceURL,
                data: addRequestVerificationToken(sample),
                success: function (data, textStatus, jqXHR) {
                    handleAjaxMessages();
                },

            });
        });
    });

The problem is that the Index Action is called automatically after the Create Action:
[HttpGet]
    public ActionResult Index()
    {
        return View();
    }

Fiddler snapshot
The Toast message is not displayed because the Index Action is called, How can I call the Create Action only (without calling the Index Action)?
Comment: show the HTML for btnSave please
Comment: whatever you have posted seems fine. Can you see that if create action is being called at all or not?
Comment: Yes it is called, I have put a break point.
Comment: then your toast message should also be called. After which line of code, does the control actually passes to the index method
Comment: I used this for toast messages http://stackoverflow.com/questions/18474035/displaying-errors-and-exceptions-in-toastr-or-similar-method-using-mvc4-and-en  . the html for save button is @Resources.Captions.Save  .  when i hit save the Index action is called then the create action.
Answer: So your "#btnSave" is a <button type="submit" /> button. The browser will do the following in order:

Invoke your own click handler, that you have shown in your code.
Post the <form> that your button is in to the server and reload the page with the answer that it gives.

You have two options: either you remove the form and have a regular <button> (without type="submit"), or you modify your click handler a little:
$("#btnSave").click(function (event) {
        event.preventDefault(); // notice this line
        var serviceURL = '';


Django -I need to implement drag and drop to upload file

Question: I am using django to develop a small project and i want to implement drag and drop to upload file .I have already implemented basic file upload from choose file and it is working fine .
Please help me
I have tried below code for simple file uploading but i need drag and drop and i dont know how to implement the same .
{% block content %}

  {% csrf_token %}
  <input type="file" name="myfile">

  <input type="submit" value="upload">

{% endblock %}

Views.py

def simple_upload(request):
    if request.method == 'POST' and request.FILES['myfile']:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage(location="test/uploadedmedia")
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)
        return render(request, 'upload.html', {'uploaded_file_url': uploaded_file_url,"fileupload":"File uploaded successfully"})
    return render(request, 'upload.html')

I need file to be dragged and gets uploaded.

    <meta charset="utf-8">

    <title>Drag @drop</title>

Drop files here

{% load static %}
{% block content %}
  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="myfile" >
    <button type="submit" id="butto">Upload</button>
  </form>

  {% if uploaded_file_url %}

File uploaded at: {{ uploaded_file_url }}

  {% endif %}
{% endblock %}

Comment: Hi, welcome to SO. Drag'n'drop has nothing to do with Django, per se. You should search tutorials for javascript drag'n'drop to upload file first and then come back here if you can't make it posting what code you tried.
Comment: Hi ,Thanks for helping hand ,I have tried below code but that is still not working out please help me out .
Comment: You shouldn't add it as an answer but edit your question to include the javascript code.
Comment: Tell us also how it behaves with that javascript code. What does it show in the Network tab of your browsers debugging view?
Comment: When i drop file it is displaying filelist in console tab and nothing in network tab.I have below code for dropzone.I just need to call my upload button when the file is dropped.

    dropzone.ondrop=function(e){
    e.preventDefault();
    this.className='dropzone';

    x=e.dataTransfer.files
    console.log(x)
Comment: and just to mention here ,i am able to upload file by using choose file to upload button for which i provided code above .I just need to use the same input type ="file" name="myfile" while implementing drag and drop.
Comment: Good, you have some HTML and javascript code. Could you add important parts (the form html and dropzone js) to the question? I think your dropzone code is just missing the form submit button and adding the files to the form.
Comment: I Have added full JavaScript code and Views.py code .Please help me with the solution.
Comment: Just to add - When i am dropping file in my console tab it is showing properly file details .

FileList {0: File(3748), length: 1}
0: File(3748) {name: "img2.png", lastModified: 1544678696275, lastModifiedDate: Thu Dec 13 2018 10:54:56 GMT+0530 (India Standard Time), webkitRelativePath: "", size: 3748, …}
length: 1
__proto__: FileList
item: ƒ item()
length: (...)
constructor: ƒ FileList()
Symbol(Symbol.iterator): ƒ values()
Symbol(Symbol.toStringTag): "FileList"
get length: ƒ length()
__proto__: Object
Answer: I found out the solution -
In your drop zone just add this below code-
  var dropzone=document.getElementById('dropzone');

    dropzone.ondrop=function(e){
    fileinput.files=e.dataTransfer.files
    e.preventDefault();

Comment: hi your code is not allowing to drop file please  help


Any way to get a Recursive function from its closed form?

Question: For an exercise, the goal is to find a recursive definition for a certain function.
the function itself is as follows: f(a,b) is the # of binary strings of length a and with b more 1s than 0s.
eg: f(4,0) = 6 (because 1100, 1010, 1001, 0101, 0011, 0110)
So far all I've figured out is a closed form:
I'm just wondering if there's a good way to get a recursive definition for this.
Edit: I forgot to mention that this closed form function only works when a and b are BOTH either ODD or EVEN. This is due to the definition producing 0 strings otherwise.
Many thanks in advance.
Comment: I'm not sure if your closed form is valid. What if $\frac{a-b}{2}$ isn't an integer?
Comment: @ZubinMukerjee If $a$ and $b$ don't have the same parity then the answer is 0.  One tiny simplification you can make: $\frac{a-2}{2}+b$ is just $\frac{a+b}{2}$... or, even more suggestively, $a-\left(\frac{a-b}{2}\right)$...
Comment: Oops! That makes sense; it's impossible for a string of $3$ ones and zeroes to have $2$ more ones than zeroes.
Comment: "suggestively" - suggestive of $\binom{a}{(a-b)/2}$?
Answer: You can't (easily) get a recursive function from the closed form, but you can get one from the problem description.  First of all, it's obviously impossible for the difference between ones and zeroes to be greater than the total number of digits, so $f(a,b) = 0$ if $b\gt a$; similarly, $f(a,b)=0$ if $-b\gt a$.
There are two different ways of looking at the next step.  The simpler one to understand is that there's exactly one sequence — '1' — with one symbol and 1 more 1s than 0s, and one sequence with one symbol and -1 more 1s than 0s — and no sequences with one symbol and the same number of 1s and 0s; in other words, $f(1,1) = f(1,-1) = 1$ and $f(1,0)=0$.  But the more fruitful one is to realize that there's exactly one sequence with zero symbols, and 0 more 1s than 0s, namely the empty sequence ''; in other words, $f(0,0)=1$.
Once you have the base case(s) of your recursive definition in place, you can start thinking about the recursive case.  In this case, the easiest way to think of it is to consider how your sequence starts.  Suppose you've got a sequence of length $n\gt 0$ with $m$ more ones than zeroes; then the first symbol is either a 0 or a 1.  If it's a zero, what can you say about the rest of the sequence?  What about if it's a one?
Once you piece all this together, you should have a valid recursive definition for your function.  As a check, you can try using it to compute $f(4,0)$ since that's a value you already know.
Comment: Thank's a lot for the hint. For now I've defined a function g(x,y) on its own, x holding # of spaces available and y holding # of ONES available and then iterating through until one of the numbers becomes 0. It's not exactly what I need but I feel like I'm close.
Comment: Nevermind I got it. Life is good. You're a hero.


Variable error in function

Question: I wanted to make a number guesser game, and I wrote this code:
from random import randint as rand

number=rand(-1,1001)
tries=0
def numguess():
    guess=int(input("The chosen number is between 0 to 1000.\nEnter your guess : "))
    tries=tries+1
numguess()

while True:
    if number==guess:
        print ("You won. My number was effectively" ,number,". \n It took you ",tries, "to guess the number.")
        break

    elif number<guess:
        print ("The number I chose is lower than your guess")
        numguess()

    else:
        print ("The number I chose is higher than your guess")
        numguess()

When I run it, it asks me for input then raises a UnboundLocalError. Is there something I am doing wrong? I tried searching but I don't understand. Thank you.
Answer: your tries variable is treated locally - since you assign value to it, use:
global tries
tries = tries +1

in your function

Variable error in function


What type of neural network has feedback loops?

Question: The arrows in neural networks (see wikipedia image here) always seem to go from left to right.
Is there a type of neural network where the hidden layer outputs connect to hidden layers inputs that are farther upstream?
Comment: The title of the question is confusing: it mentions feedback loops (In which case the answer is straightforward - you are looking for RNN) , but then in the text of the post what you describe is something different from feedback loops, and it seems like you are looking for ELM or ESN networks (Hopfiled might fit the bill as well).
Answer: Yes, networks with skip-connections do that. But that's not a feedback loop, mind you, because it does not form a loop at all.
Here's the example from Wiki's article on Residual Neural Networks

See that 'Layer I-2' outputs are transmitted to 'Layer I' directly.
Answer: As a concrete example, imagine we have an input layer $I$, and layers $[I,Y]\rightarrow X\rightarrow Y\rightarrow X,Z$. In other words to compute $X$ we need both the input and the values from $Y$. As written, this is impossible to do since you do not yet have a value for $Y$ to plug into $X$. What you can do instead is use a placeholder of $0s$ (so if $Y$'s output is 100 dimensional, you'd have $(0,0,\cdots,0)$ 100 times) for $Y$ at the initial state, then compute $X$ and $Y$, and then recompute $X$ with a fresh value of $Y$.
This is effectively the same structure as a recurrent neural network module $R$ that operates on the same input $X$, where $Y$ is the hidden state, e.g.:
$$Y\rightarrow R \rightarrow R\rightarrow R\rightarrow \cdots$$
$$\quad\mbox{ }\mbox{ }\mbox{ }\uparrow \quad\mbox{ }\uparrow\quad\mbox{ }\uparrow\cdots\quad$$
$$\mbox{ }\mbox{ }\mbox{ }I \quad\mbox{ }\mbox{ }\mbox{ }I\quad \mbox{ }\mbox{ }\mbox{ }\mbox{ } I \mbox{ }\cdots$$
The question now becomes when to stop, as technically you'd have to keep recomputing $X$. So the compromise here would be to set a maximum recurrence number, say 10, after which you stop the cycle and move onto $Z$ with your value of $Y$.


Bounded and compact sets using Heine-Borel, distance to a set

Question: The distance between a point $x \in \mathbb{R}^n $ and a set $E \subset \mathbb{R}^n$ is defined as $d(x,E)=\inf\{\ d(x,e) : e\in E \} $, where $d(x,e)=\|x-e\|$.
If $E \subset \mathbb{R}^n$ is bounded, I need to prove that $E_a = \{\ x \in \mathbb{R}^n : d(x,E) \leq a  \}$ is compact.
I'm approaching this problem using the Heine-Borel Theorem, i.e., I'm trying to prove that $E_a$ is bounded and closed. I've already proven that $E_a$ is closed, but I'm having some trouble with the bounded part, I'm trying to find $x_0 \in \mathbb{R}^n $ and $r>0$ such that $d(y,x_0) < r $ for al $y \in E_a$.
Comment: Hint: You don't really need $x_0$. Let $M=\sup_{x\in E}|x|$. Could you possibly find some $y\in E_a$ with $|y|>M+a$? Use the definition of $E_a$ to figure it out. Oh, and draw a picture!
Answer: You've stated that $E_a$ is closed, but I'll prove it here anyways, for the sake of completeness. If we have a sequence $\{x_n\} \subseteq E_a$ converging to a point $x$, then we can find a corresponding sequence $\{y_n\} \subseteq E_a$ for which $\|x_n - y_n\| \le a + \epsilon$; that is, $y_n$ is "close enough" to $x_n$. There is an $N$ such that
$$\|x_N - x\| < \epsilon$$
Given this, we have that
$$\|x - y_N\| \le a + 2\epsilon$$
from the triangle inequality, implying that $d(x, E) \le a + 2\epsilon$; since $\epsilon$ was arbitrary, we can conclude that $d(x, E) \le a$, so that $x \in E_a$.
Next, some idea of why this set is bounded: The set $E_a$ contains only points close to $E$, and every point in $E$ is close to $0$ (where the degree of closeness depends on just how bounded $E$ is). Draw a picture for this part: If $M$ is a bound for the set $E$, then $E$ lies in a ball of radius $M$ around the origin; since we know nothing about the structure of $E$, we don't really lose much by working with the ball instead. Adding a distance of $a$ only makes the ball a bit bigger, now having radius $M + a$, which is still finite.
To formalize this, notice that if $x \in E_a$, we can choose $y \in E$ so that $\|x - y\| \le a + 1$. Then again using the triangle inequality,
$$\|x\| = \|x - y + y\| \le \|x - y\| + \|y\| \le a + 1 + M$$
for all $x$. In fact, a slight modification to this argument means that you can actually conclude $\|x\| \le a + M$.


Why Does Visual Studio Give the Warning "Relational Expression As Switch Expression"?

Question: I have the following code:
float x = 0.43;
float y = 1.56;
size_t largerValueIndex = 1;
size_t smallerValueIndex = 0;
switch (x > y) {
case 1:
    largerValueIndex = 0;
    smallerValueIndex = 1;
    break;
}

Visual Studio issues the warning "C4144: '>': relational expression as switch statement".
What I'd like to know is why is the warning necessary?  I was under the impression that most switch and if statements are comparisons between two values.  Is this considered bad practice?  And if so, why?
My question has to do with the value being used as the switch expression, not those in the cases.
Comment: (x > y) only has the values true and false.  The normal use of switch is something like `switch (x) { case 1: .....   case 2: ....` -- not a comparison between 2+ variables, it is a list of values for x.   Also, for only 2 values, here true and false, if...else is more clear.
Comment: Speed-wise, probably no difference by the time the compiler's done. But this just looks weird and you'd have folk tripping over it, wondering what the  you were thinking, and possibly inserting bugs in the code during maintenance as a result because that's what confused people do.
Comment: `switch` is often more than two, but the compiler is trying to tell you you have defined `if`-like behaviour in a `switch`, and this is weird-enough that it should be pointed out. More often than not, you'd find this to be a mistake that needs fixing.
Comment: @DaveS The language defines the result of reinterpreting a boolean `true` value as an integer to be equal to 1 for quite some time now. Only extremely old compilers would have a problem.
Comment: [Found it!](https://timsong-cpp.github.io/cppwp/conv.integral#2): *If the destination type is `bool`, see [\[conv.bool\]](https://timsong-cpp.github.io/cppwp/conv.bool). If the source type is `bool`, the value `false` is converted to zero and the `value` true is converted to one.* This goes back at least to C++11.
Comment: Why not just `size_t largerValueIndex = y > x; size_t smallerValueIndex = !largerValueIndex;`
Comment: @DaveS spec says you'll get 1 for true, but I can't find where [conv.integral] got off to in [this monster](https://timsong-cpp.github.io/cppwp/)
Comment: Sorry, I'm not sure that I understand.  Are you saying that an if statement would be more efficient here?
Comment: That's also a good point...
Comment: @paddy - I'd be afraid than boolean true might not be == 1 for some compiler, but I haven't checked C++ language spec to see if it is or not.
Comment: Anyways @Dave S if you post your comment as an answer, I'll mark it as the solution.  Thanks again.
Answer: The expression (x >y) evaluates to boolean true and false, which convert to 0 and 1 as noted by @paddy and @user4581301 (see https://timsong-cpp.github.io/cppwp/conv.integral#2)
While switch ( -relational expression- ) is legal, is is not normally used because there are only two values and if ( expression ) { ...true code... } else { ...false code... } is easier to understand.
switch is normally used for one integer variable or expression to efficiently list the expected values instead of a long chain of if...else if...else if...else
Answer: Although the code is correct,  switch is normally used for scenarios with more than two possible outcomes; a test with only two possible outcomes should be an if.
The compiler warns about this because the unexpected use of switch might indicate a typo or a logic error.


Excel VBA: Create shapes hierarchy from list

Question: I'm trying to loop through an "ordered" list to create several rectangle shapes in hierarchy style (and link them with elbow connectors). Example: on my WBSdata sheet, I have the following
     A              B
1    0.        Box 0. lvl1
2    0.1.      Box 0.1. lvl2
3              Comment 1
4              Comment 2
5    0.1.1.    Box 0.1.1. lvl3
6              Comment 1
7              Comment 2
8              Comment 3
9    0.2.      Box 0.2. lvl2
10   0.2.1.    Box 0.2.1. lvl3
11   0.2.2.    Box O.2.1. lvl3
12             Comment 1
13             Comment 2
14   1.        Box 1. lvl1
15             Comment 1
16             Comment 2
17   1.1.      Box 1.1. lvl2

Would output something like this on the WBS sheet:

Basically, read the "index" in column A, if it's first level (2 characters in column A), draw a blue box and write the corresponding value from column B, then look at the line below, if it's a level 2 box (4 characters), draw it below (a bit shorter on the left side), assign it the value ; same for lvl 3 box. If column A i empty, create a text box below the shape, and add all the comments.
So far (see code below), I managed to create a box (yay), style it and add the text, as well as create a text box (with a line on the side, like in the picture, but i'd need it to be the same "dynamic" height as the text box), but i can't get it to add all the comments. I can't get the magic to understand that it needs to move to the next "level" (go from blue box to green box for example).
I haven't yet tried to connect each box to its "hierarchical superior", but that's another story :)
I'm pretty sure i'm not managing my variables correctly (mainly the counter), making it reset at the right time, etc...
Any tips to send me on the right direction?
Public Sub wbsShape()

Dim wbs, wbsdata As Worksheet
Set wbs = ThisWorkbook.Sheets("WBS")
Set wbsdata = ThisWorkbook.Sheets("WBSdata")

i = 2 'counter, because data starts on line 2
ileft = 100 'initial position from left of sheet
itop = 100 'initial position from top of sheet
lg = 175 'main box width
ht = 50 'main box height
ind = 10 'indent (for lines, or smaller boxes)
impred = RGB(128, 0, 0) 'red
impgreen = RGB(0, 128, 0) 'green
impblue = RGB(0, 0, 128) 'blue
impgrey = RGB(200, 200, 200) 'light grey for border
black = RGB(0, 0, 0)
white = RGB(255, 255, 255)

Do While Not IsEmpty(wbsdata.Cells(i, "A").Value)

With wbs.Shapes.AddShape(msoShapeRectangle, ileft, itop, lg, ht)
    .Fill.ForeColor.RGB = impblue
    .Line.ForeColor.RGB = impgrey
    .Line.Weight = 1
    .Name = wbsdata.Cells(i, "B").Value
    With .TextFrame
            With .Characters
                    .Text = UCase(wbsdata.Cells(i, "B").Value)
                    With .Font
                            .Color = white
                            .Name = "Arial"
                            .Size = 14
                            .FontStyle = "Bold"
                    End With
            End With
                 .HorizontalAlignment = xlHAlignCenter
                 .VerticalAlignment = xlVAlignCenter
      End With

   End With

i = i + 1

    If IsEmpty(wbsdata.Cells(i, "A").Value) Then
    wbs.Shapes.AddLine(ileft + ind, itop + ht, ileft + ind, itop + ht + 100).Line.ForeColor.RGB = RGB(10, 10, 10)
        With wbs.Shapes.AddTextbox(msoTextOrientationHorizontal, ileft + 2 * ind, itop + ht, lg - ind, 30)
             .Line.Visible = msoFalse
             .Fill.Transparency = 1
            With .TextFrame.Characters
                .Font.Name = "Arial"
                .Text = wbsdata.Cells(i, "B").Value
            End With
    End With

End If

itop = itop + ht + 20

Loop

End Sub

Comment: @SJR Or at least use the "Smart Art" tool available in Office - it's designed for this kind of graphic.
Comment: Not exactly sure where you are stuck. If the colour depends on the length of column A use len or use Split to find the number of dots and base the colour etc on that. Assign the boxes to variables and then you can refer to them in later code or write a function with some parameters to do the drawing.
Comment: Tbh though, not sure if Excel is the best tool for this!
Comment: @CindyMeister - good point, it even has a Heirarchy category.
Comment: Thanks for the input! However, the hierarchy SmartShape has limited "functionality"... Can I rephrase my question then? how would you go about saying (in vba) : "hey, read A1, draw the rectangle with the text inside, then read A2: if it has more characters, make another rectangle 1 "lvl" lower, if it is empty, create a text box below the initial rectangle". Thanks in advance!
Answer: I think this is going to be a lot of work (I've stripped out a lot of your formatting), but perhaps this will start you off in the right direction.
Sub x()

Dim r As Range, v, s As Shape
ileft = 100 'initial position from left of sheet
itop = 100 'initial position from top of sheet
lg = 175 'main box width
ht = 50 'main box height
ind = 10 'indent (for lines, or smaller boxes)
impred = RGB(128, 0, 0) 'red
impgreen = RGB(0, 128, 0) 'green
impblue = RGB(0, 0, 128) 'blue
impgrey = RGB(200, 200, 200) 'light grey for border
black = RGB(0, 0, 0)
white = RGB(255, 255, 255)

For Each r In Range("A1:A4")
    v = Split(r, ".")
    If UBound(v) = 1 Then
        Set s = ActiveSheet.Shapes.AddShape(msoShapeRectangle, ileft, itop, lg, ht)
        s.Fill.ForeColor.RGB = impblue
        s.TextFrame.Characters.Text = r.Offset(, 1)
        itop = itop + 75
    ElseIf UBound(v) = 2 Then
        Set s = ActiveSheet.Shapes.AddShape(msoShapeRectangle, ileft, itop, lg, ht)
        s.Fill.ForeColor.RGB = impgreen
        s.TextFrame.Characters.Text = r.Offset(, 1)
        itop = itop + 75
    ElseIf r = vbNullString Then
        Set s = ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, ileft + 2 * ind, itop + ht, lg - ind, 30)
        s.Line.Visible = msoFalse
        s.Fill.Transparency = 1
        With s.TextFrame.Characters
            .Font.Name = "Arial"
            .Text = r.Offset(, 1).Value
        End With
        itop = itop + 75
    End If
Next r

End Sub


how to change the contents in the file in perl?

Question: I am trying to open one file read oneline in it at a time then open the another file and try to search for some part of the line read from the first file in the second file and try to replace all instances with the other part of the line read from the first file.When i am executing it its getting executed and i am able to see the result on the console but the files are not getting modified. What could be the mistake. Can some one please suggest this.
use strict;
use warnings;
use autodie; # die if problem reading or writing a file

my $filename = 'compare.txt';
open(my $fh, '+<', $filename) or die "Could not open file '$filename' $!";

while(<$fh>){
    my $readline= "$_";

    print("\n");

    my @arr=split(',',$readline);
    print($arr[0]."\n".$arr[1]);
    replace($arr[0],$arr[1]);

}
close $fh;

sub replace
{
    my $search=shift(@_);
    my $replace=shift(@_);

    my $filename2 = 'replace.txt';
    open(my $fh1, '+<', $filename2) or die "Could not open file '$filename' $!";

    while(<$fh1>)
    {
        my $readline2= "$_";
        $readline2=~s/$search/$replace/g;
        print($readline2);
        print("\n");

   }
   close $fh1;

}

Comment: You never write your replacements to files, but just print to the console.  Need to write a new file (with changes) and then move it over the file which needs to be changed.
Comment: Don't need (and don't use) `+<` mode; just `open my $fh, '<', $file ...` for reading.
Comment: Can do `while (my $readline = <$fh>) { .. }` and `$readline` is assigned the line (what would've been in `$_`) and exists (is seen) in the loop.
Comment: Put `use feature 'say';` at the top and you can print as `say "hi";` where newline gets appended. Then you can use `print` specifically when you don't want a newline, `say` otherwise.
Answer: As a huge fan of the Path::Tiny module, I would do the above as:
use 5.014;
use warnings;
use Path::Tiny;

my %rep = map { split /,/ } path('compare.txt')->lines({chomp => 1});
path("replace.txt")->edit_lines( sub {
    while(my($key,$val) = each(%rep)) {
        s/$key/$val/g;
    }
});

Comment: _Hey, how cool is this?_ And it avoids the complete rewrite of the target file for every single replacement.
Comment: Awesome. +1 for succinctness
Answer: In your sub, when you are iterating the lines in your file, you should write it back to a file. The regex substitute doesn't automatically write it back to file.
use strict;
use warnings;
use autodie; # die if problem reading or writing a file
use File::Copy;
my $filename = 'compare.txt';
open(my $fh, '+<', $filename) or die "Could not open file '$filename' $!";

while(<$fh>){
        my $readline= "$_";

        print("\n");

        my @arr=split(',',$readline);
        print($arr[0]."\n".$arr[1]);
        replace($arr[0],$arr[1]);

}
close $fh;

sub replace
{
        my $search=shift(@_);
        my $replace=shift(@_);

        my $filename2 = 'replace.txt';
        open(my $fh1, '+<', $filename2) or die "Could not open file '$filename' $!";
#open file to write to
        open $newfile, '>', 'replace_tmp.txt';
        while(<$fh1>)
        {
                chomp;
                my $readline2= "$_";
                $readline2=~s/$search/$replace/g;
                print( $newfile, $readline2);
                print($newfile, "\n");
        }
        close($fh1);
        close($newfile);
        move ('replaced.txt', 'replace.txt');
}

This is simple way of doing it. You can use File::Tie to write back to the same file and avoid renaming it, or refer to perldoc


Python how to access subfolder of subfolders

Question: I am new to python and I have trouble accessing the math text-files within the subfolders.

This is the code I have written so far:
import os, sys
for folder, sub_folders, files in os.walk(my_directory):
   for special_file in files:
      if special_file == 'math.txt'
         file_path = os.path.join(folder, special_file)
         with open(file_path, 'r+') as read_file
            counter += 1
            print('Reading math txt file' + str(counter))

            for line in read_file:
               print(line)

I am not able to do print lines of all the math.txt files within all the classes and all the schools and all the zones.
Before I had a version of the script that merged all the files, but some of the log files were extremely large (combined > 16GB).
Comment: Are you getting an error? (besides missing a `:` after the line where you open the file, and after the `special_file` test line)
Comment: Also, `counter` hasn't been initialised to 0.
Comment: What error are you getting? Or what is the output? There are some syntax errors in there, but I'm assuming that is just due to copy paste stuff, yeah?
Comment: jdi, i forgot that-thanks for the catch,RocketDonkey- i was printing the folders instead of the actual files, @MRAB thanks for the catch
Answer: This seems to work for me. Only changes were those that @jdi, @MRAB and I were indicating - missing colons and initializing the counter variable. Since you're on Windows, you may want to make sure that you're properly specifying your directory path.
import os, sys

# Specify directory
# In your case, you may want something like the following
my_directory = 'C:/Users/<user_name>/Documents/ZoneA'

# Define the counter
counter = 1

# Start the loop
for folder, sub_folders, files in os.walk(my_directory):
  for special_file in files:
    if special_file == 'math.txt':
      file_path = os.path.join(folder, special_file)

      # Open and read
      with open(file_path, 'r+') as read_file:
        print('Reading math txt file ' + str(counter))

        # Print the file
        for line in read_file:
           print(line)

        # Increment the counter
        counter += 1

Comment: Just use forward slashes for paths, even on windows.
Comment: @jdi Ha, all this time I was thinking 'There must be a better way'. Thanks for the awesome tip! Fixing now.
Comment: Haha, ya its nice to know its universally handled. +1 now that you have fixed that!
Comment: Haha, thanks man. Stoked about not having to double-slash stuff anymore!
Comment: Yes the forward slashes is very nice for paths...thanks again


Cassandra Counters Double Counting

Question: I am new to Cassandra and am having an issue with counters double counting sometimes.  I am trying to keep track of daily event counts for certain events.  Here is my table structure:
create table pipes.pipe_event_counts (
    count counter,
    pipe_id text,
    event_type text,
    date text,
    PRIMARY KEY ((pipe_id, event_type, date))
);

The driver I am using is the Datastax Java driver, and I am compiling and binding parameters to the following prepared statement:
incrementPipeEventCountStatement =  CassandraClient.getInstance().getSession().prepare(
    QueryBuilder.update("pipes", PIPE_EVENT_COUNT_TABLE_NAME).with(incr("count")).
    where(eq("pipe_id", "?")).and(eq("date", "?")).and(eq("event_type", "?")).
    getQueryString()
);

incrementPipeEventCountStatement.bind(
    event.getAttrubution(Meta.PIPE_ID), dateString, event.getType().toString()
)

The problem is very weird.  Sometimes when I process a single event, the counter increments properly by 1.  However, the majority of the time, it double increments.  I've been looking at my code for some time now and can't find any issues that would cause a second increment.
Is my implementation of counters in Cassandra correct for my use case? I think it is, but I could be losing my mind.  I'm hoping someone can help me confirm so I can focus in the right area to find my problem.
Important edit:  This is the query I'm running to check the count after the event:
select count from pipes.pipe_event_counts where pipe_id = 'homepage' and event_type = 'click' and date = '2015-04-07';

Comment: what version of cassandra? http://www.datastax.com/dev/blog/whats-new-in-cassandra-2-1-a-better-implementation-of-counters
Comment: I'm using 2.1.  Thanks for the link - I'll check it out.
Comment: I still haven't figured out what's causing this, but it's only an issue in my dev environment.  I'm using the Play Framework to host the app, and it's in dev mode locally (as expected).  It's probably related to that.  In either case, not a production issue, so I'll ignore it for now.
Answer: The thing with counters is that they are not idempotent operations so when you retry (and don't know if your original write was successful) you may end up over-counting.
You can also never re-try and undercount.
As Chris chared, there are some issues with the counter implementation pre-2.1 that make the overcounting issue much more severe. There are also performance issues associated with counters so you want to make sure you look into these in detail before you push a counter deployment to production.
Here are the related Jiras to help you make informed decisions:
Counters ++ (major improvement - fixed 2.1) -- https://issues.apache.org/jira/browse/CASSANDRA-6504
Memory / GC issues from large counter workloads, Counter Column (major improvement - fixed 2.1)--https://issues.apache.org/jira/browse/CASSANDRA-6405
Counters into separate cells (final solution - eta 3.1)- https://issues.apache.org/jira/browse/CASSANDRA-6506

Cassandra Counters Double Counting


How to get bin folder in ASP.NET Core 1.0

Question: With asp.net core 1.0 There are lots of functionality added. But there is not way to get Bin Folder path.
Can anyone please know how we can get the bin folder path for asp.net core 1.0 application.
Comment: Why do you want a bin folder?
Comment: @MuqeetKhan One reason would be to retrieve the produced XML documentation file.
Answer: Alternative way (corresponds to the AppDomain.BaseDirectory):
AppContext.BaseDirectory

Answer: This works to retrieve the assembly's directory, from which we can determine the bin location.
var location = System.Reflection.Assembly.GetEntryAssembly().Location;
var directory = System.IO.Path.GetDirectoryName(location);
System.Console.WriteLine(directory);

Output
C:\MyApplication\bin\Debug\netcoreapp1.0

Comment: Works for me on my local environment, but can it work on Azure API Service?
Answer: Well, the bin folder does exists but it is moved to artifacts folder next to the solution file. Since ASP.NET Core RC 1 compiles everything in memory, you will find empty bin folder. But if you set "Produce output on build" option to true (Right click Project file -> Properties and Build tab) then you will find the generated files in bin folder.
I don't think so there is any direct property available as to get the path of this  but you can use the same solution pointed out by @Nikolay Kostov to get application path. And then using System.IO classes jump to bin folder.
Code updated to for ASP.NET Core as mentioned here.
http://www.talkingdotnet.com/get-application-wwwroot-path-aspnet-core-rc2/
public Startup(IHostingEnvironment env, IApplicationEnvironment appenv)
{
     string sAppPath = env.ContentRootPath;
     string sRootPath = Path.GetFullPath(Path.Combine(sAppPath, @"..\..\"));
     string sBinFolderPath = @"artifacts\bin\" + appenv.ApplicationName;
     string sBinPath = Path.Combine(sRootPath, sBinFolderPath);
}

Answer: You can't really get the /bin/ folder since it is not relevant to your project and the ASP.NET environment doesn't know what a /bin/ folder is.
And also there isn't exactly a /bin/ folder. You may want to read this article: http://docs.asp.net/en/latest/conceptual-overview/understanding-aspnet5-apps.html
But you can get the so called ApplicationBasePath which is the directory in which you application runs:
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
     string baseDir = appEnv.ApplicationBasePath;
     // Other startup code
}

Comment: Ancient history now but IApplicationEnvironment has been removed.  https://github.com/aspnet/Announcements/issues/171
Comment: It is giving the folder with src which I don't want
Comment: Well there isn't exactly a `/bin/` folder. You may want to read this article: http://docs.asp.net/en/latest/conceptual-overview/understanding-aspnet5-apps.html so the project root is the place where the code is started
Comment: @JalpeshVadgama: This means you're running in the IDE.
Comment: The `src` folder is for published client script source. Where do you think ASP.NET put's the DLL your project compiles to? If you copy something to output during build, like a SQL script, it is copied to a `bin` folder, and to use that SQL script, you need to know the full disk path to wherever that script file is.
Answer: AppDomain.CurrentDomain.BaseDirectory;


make tabbar button as unselected when clicked on the navigation bar button

Question: i am facing the problem with the tab bar,when i clicked on navigation bar button,the tab bar button is should be unselected,i tried but failed to do that.can any one help me to resolve the issue.
Comment: not clear what you are asking, add some more details.
Comment: @rishi : in one view both navigation bar and tabor is there.fist time in tabbar one button is selected,now i clicked on navigation bar button,now i want to unselect the tabbar button
Comment: Can you add some screen shot showing your exact problem.
Comment: how to put the sreenshot,i am unable to do that here
Answer: If i understood your needs, I guess what you want to do is to select no item at all in your tabbar.
So doing :
<code>[tabBar setSelectedItem:nil];
</code>
should be what you need.
That is only if your tabBar is not handled by a UItabBarController. Else you'll get the following exception.

Directly modifying a tab bar managed by a tab bar controller is not allowed.

This behavior is unfortunately logical if you read the doc on the tabBar property of a UItabBarController : UITabBarController documentation - tabBar

You should never attempt to manipulate the UITabBar object itself stored in this property. If you attempt to do so, the tab bar view throws an exception. To configure the items for your tab bar interface, you should instead assign one or more custom view controllers to the viewControllers property. The tab bar collects the needed tab bar items from the view controllers you specify.

And reading through this page you'll see that UITabBarController gives you no means of selecting an item other than the ones on your tabBar (except the moreNavigationController UITabBarController documentation - moreNavigationController )

EDIT : If you do want to keep your tabBar shown, you can trick the users and make them believe the tab is unselected by applying the "unselected style" to the selected tab. This question should give you everything you need to do that : How to change inactive icon/text color on tab bar?
Comment: but  i am using the tabview controller,so how can i use [tabbar selecteditems=nil];
Comment: From the doc, you can't. All you can do is "hide" the fact that it is selected by applying the unselected style of your item to it's selected state.
Comment: self.tabBarController.selectedIndex=2;    this is working but,selecting the 3 tab,but i don't want to select even one also,i tried with nil but first tabor was selected
Comment: The fact that tab 3 is selected when you do `self.tabBarController.selectedIndex=2` is normal as the indexes start at 0 so selecting index 0 will show the first tab, index1 will show the second tab, index 2 will show the 3rd tab and so on.
Comment: yes i know that,but how to resolve my issue i dont want to select any tab
Comment: As I told you, Apple doc says you can't. As you should not be displaying the tabBar if none of it's tab is selected.
Maybe the view opened from a tap on a button from your navigation bar should not display the tabBar at all since it's a view that is not related to your tabBar.


prove unique existence of a solution of a Cauchy problem

Question: I have the differential equation $y'(t)=t^2 \cos(y(t)+\arctan t)-{1 \over (1+t^2)}$.
I want to prove the unique existence of the solution $y \in C^1(R)$.
$f \in C^0(R^2)$ so the solution exists on $R^2$.
But for the unique?
Answer: Let $z(t) = y(t) + \arctan t$, then $z'(t) = y'(t) + \frac 1{1 + t^2}$, hence
$$ z'(t) = t^2 \cdot \cos z(t) =: g(t, z(t)) \tag+ $$
as $g$ is locally Lipschitz, the solution of $(+)$ is locally unique.
Comment: why g is locally Lipschitz?


Formatting Slack Notification from Grafana

Question: Getting Alerts in slack from Grafana. But it's not in a good format. Is there any way to customize the notification in slack from Grafana?. I am using Node exporter to export the metrics. The dashboard is downloaded from https://grafana.com/grafana/dashboards/1860
How to customize the notification like:
Heading: ALERT CPU LOAD ON SERVER
Instance IP: 192.x.x.x.x
Value: 90% of CPU used
Priority: High
Sample output in slack is attached.
Comment: I want this too - need a way to extract values from the Value: field. The templating tutorials I've tried don't address this.
Comment: I'm struggling as well, but this was a little helpful:

https://www.youtube.com/watch?v=UtmmhLraSnE&t=1531s&ab_channel=ReadyDedisLLC
Answer: So i managed to work it out nicely according to my needs with the help of this guide :
https://community.grafana.com/t/how-to-use-alert-message-templates-in-grafana/67537/3
I will never the less post the config here as well:

Grafana / Contact points / Message template - Create new template called 'myalert'

{{ define "myalert" }}
  [{{.Status}}] {{ .Labels.alertname }}
  {{ .Annotations.AlertValues }}
{{ end }}

Grafana / Contact points - Message template - Create another template for the message called 'mymessage'

{{ define "mymessage" }}
  {{ if gt (len .Alerts.Firing) 0 }}
    {{ len .Alerts.Firing }} firing:
    {{ range .Alerts.Firing }} {{ template "myalert" .}} {{ end }}
  {{ end }}
  {{ if gt (len .Alerts.Resolved) 0 }}
    {{ len .Alerts.Resolved }} resolved:
    {{ range .Alerts.Resolved }} {{ template "myalert" .}} {{ end }}
  {{ end }}
{{ end }}

Grafana / Contact points / Contact points / Slack / Optional Slack settings / Text body - Add the following:

Alert summary:
{{ template "mymessage" . }}

Grafana / Some-Alert / Summary and Annoitations - add a field called 'AlertValues' with the following content:

Alert summary:
{{ with $values }}
{{ range $k, $v := . }}
   Location: {{$v.Labels.device}}
   Variable: {{$v.Labels.instance}}
   Alerting value: {{ $v }}
{{ end }}
{{ end }}

^^ device and instance may vary, based on query returned values(labels)
And the result i get:
    Alert summary:

       1 firing:

     [firing] EKS Storage

      Location: /dev/nvme0n1p1
      Variable: 10.0.112.170:9100
      Alerting value: 24.88013967279807
    ```


nginx won't execute PHP code when redirected from a SEO like URL

Question: Unlike other questions related to nginx not executing PHP files, mine does, the problem comes when I use SEO like urls instead and redirect to a php script, then instead of executing the code it sends the script as plain text to the browser.
Basically what I want is that every request send to the HTTP server for which there's no an actual file, index.php script will be executed and its output returned to the browser. But what is happening is that I'm getting the code inside index.php instead.
This is the section of my configuration file where the redirection is done. It's been actually translated from a former Apache's .htaccess file:
    location / {
        if (!-e $request_filename){
            rewrite ^(.*)$ /index.php break;
        }
    }

These are the PHP related directives, actually these are before the previous one in the configuration file:
    location ~ \.php$ {
        try_files /dd05cf208ebd3d4559f3af75016a1e3d.htm @php;
    }

    location @php {
        try_files $uri =404;
        include /etc/nginx/fastcgi_params;
        fastcgi_pass unix:/var/lib/php7.0-fpm/web4.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors on;
    }

I've been using Apache with mod_php for decades and the equivalent directives just worked out of the box, but I'm new with Nginx and I don't know where to start debugging this.
Comment: So basically you want to redirect every 404 to an index.php?
You can set something like this "error_page 404 /index.php;"
Answer: The correct way to implement front-controller pattern in nginx is the following:
location / {
    try_files $uri $uri/ /index.php;
}

Your PHP location blocks look a bit odd. I guess that your objective with the configuration is to enable nginx to show a maintenance notice in /dd05cf208ebd3d4559f3af75016a1e3d.htm if the file exists.
This configuration looks correct to me, except that the try_files inside your @php block makes requests fail, since it makes nginx look for files with names specified in the URI, and with friendly URLs those files simply do not exist.
There is no reason to include that, so your PHP configuration should look like the following.
location ~ \.php$ {
    try_files /dd05cf208ebd3d4559f3af75016a1e3d.htm @php;
}

location @php {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass unix:/var/lib/php7.0-fpm/web4.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_intercept_errors on;
}

Answer: Your SEO solution is using non-recommended if directive inside location. If Is Evil:

Directive if has problems when used in location context, in some cases
  it doesn't do what you expect but something completely different
  instead. In some cases it even segfaults. It's generally a good idea
  to avoid it if possible.

The correct way to achieve what I believe you want would be try_files, e.g.:
location / {
    try_files $uri $uri/ @missing;
}

location @missing {
    rewrite ^(.*)$ /index.php break;
}

Comment: If you want to go with the `rewrite` way, you can use `rewrite ^ /index.php break;`, it does the same as `^(.*)$`. I don't know if that makes any real difference performance-wise though. At least there is no variable created...
Comment: Your answer is the most straight-forward way of doing this. This only keeps the flexibility, if more complex rewrite pattern is required later, or if a redirect is needed instead. But as we shouldn't predict that, I'll upvote for your answer.
Answer: Into the server location put
error_page 404 =200 /index.php;

to redirect all 404 (not found) pages to your index.php
You don't need all the rewrite and location stuff, if you just want to catch all missing pages.


Attaching Entities to other Entities

Question: I have two custom entities in a D7 site. One is 'additional' data on an entity, and I want to attach that data to the main entity every time it is loaded.
Within Entity/Entity API, how can I do that correctly? attachLoad sounded correct but seems to be Field related, all my data are not fields (yet).
Answer: I've seen modules use attach load as well, which is what you need to get it on the actual entity.
It also depends on your data structure if the base entity has a reference to the additional data entity, you could simply use the entity wrapper along with entity properties. You wouldn't actually have the data on the entity, but have it accessible via the wrapper. The advantage is that you only run extra queries (loading the entity) as required.
In code you would then do
<code> $entity = load_entity_function($foo);
 $enity_wrapper = entity_metadata_wrapper('entity_type', $entity);
 $additional = $enity_wrapper->addition->value();
 $additional_id = $enity_wrapper->addition->id->value();
</code>
In order to have the wrapper do this, you tell it about the additional entity in a hook:
<code>/**
 * Implements hook_entity_property_info().
 */
function module_entity_property_info() {
  $info = array();

  $properties = array();
  $properties['additional'] = array(
    'label' => t('Label'),
    'type' => 'entity_type',
    'description' => t('description.'),
    'getter callback' => 'function_get_entity_id',
    'setter callback' => 'function_set_entity_id',
    'clear' => array('id_of_additional'),
    'schema field' => 'schema_of_additional',
  );

  $info['base_entity']['properties'] = $properties;

  return $info;
}
</code>
You need a function that will get or set the id from the entity. Depending on your naming convention entity modules come with some that you can use.
Answer: I'm not familiar with the inner workings of this, but if you don't get other good answer, here is a patch that does something similar to what you ask. It loads the media edit form on the node edit for to which the media element is attached.
This is "edit", and your usecase sounds like "view", but hopefully it can help you get started.
Answer: Solved: I began using the Field Collection module to facilitate this.

Attaching Entities to other Entities


Implicit Function theorem and Bifurcation points

Question: So let us say we have a function $\dot{x} = f(x,r)$ that has some critical point at $(x_0,r_0)$ such that $f(x_0,r_0)=0$. The question now is: when is this a bifurcation point? I understand that $\frac{\partial{f(x_0,r_0)}}{\partial{x}} = 0$ works in practice, but I have two questions.
1.) Intuitively, why is this the case?
2.) The proof for this appealed to the implicit function theorem and said that if the derivative was non-zero, then there would be a (local) solution $x=X(r)$ such that $X(r_0)=x_0$, which cannot happen if the point is a bifurcation point. This doesn't click with me, why would this be not work if the point was a bifurcation? Also, how is it the case that the Jacobian is zero if only one entry is zero (namely the x-derivative entry)? Shouldn't it be the case that any 2 entries on opposite columns need to be zero?
Thanks
Answer: Well, first of all do you assume $f:\mathbb{R}^n\rightarrow\mathbb{R}$ ? If not, the condition for the application of the theorem is slightly more complicated.
But let's say that $x,r\in\mathbb{R}$ and $f(x,r)=r-x^2$. We want to find the set $\mathbb{X}=\{(x,r)\in\mathbb{R^2}|f(x,r)=0\}$. Implicit function theorem says that most of the times this can be written in the form $x=X(r)$ in a neighbourhood of a point.
So in our case lets choose $(x_a,r_a)=(x_a,x_a^2)$ with $x_a>0$, then in a neighbourhood of this point $\mathbb{X}$ can be written as $x(r)=\sqrt{r}$. If we choose $(x_a,r_a)=(x_a,x_a^2)$ with $x_r<0$, then we get $x(r)=-\sqrt{r}$.
Do you see now why we cannot choose $(0,0)$? There is no neighbourhood of the point in which we can write $x$ as a function of $r$.
So, what's the big deal? We see that given $r_e$, the points for which $f(x,r_e)=0$ are the equilibria of the system. The implicit function theorem in this case says that the equilibria of the system can usually be written as a smooth (depending on f) function of $r$. This actually is very useful because we deduct that the topological properties of the equilibrium are constant and its behaviour changes smoothly with the parameter.
However if the implicit function theorem cannot be applied, we cannot say anything of the above and wild things can happen. We call these things bifurcations.
Also I didn't really understand the last part of your question.