Ignoring default value for missed elements instead of setting nil with RestKit

Question: Im trying to send a response without certain fields, and RestKit still keeps setting the values to nil even after i have disabled this option using:
infoMapping.assignsDefaultValueForMissingAttributes = NO;

Full mapping code:
RKEntityMapping *infoMapping = [RKEntityMapping mappingForEntityForName:@"IndexInfo" inManagedObjectStore:managedObjectStore];
    //userMapping.identificationAttributes = @[@"id"];
    [infoMapping addAttributeMappingsFromDictionary:@{
                                                      @"first" : @"first",
                                                      @"last" : @"last"
                                                      }];

    infoMapping.assignsDefaultValueForMissingAttributes = NO;

RKResponseDescriptor *infoResponseDescriptor =
    [RKResponseDescriptor responseDescriptorWithMapping:infoMapping
                                                 method:RKRequestMethodGET
                                            pathPattern:@"/core/feed.json"
                                                keyPath:@"info"
                                            statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)

I really need to be able to respond with partial data, if this is a bug is there another way around it to hook the mapping to disable it manually?
Answer: It turns out that it was creating new entity's each time for my infoMapping.
So a workaround iv included an id attribute to the response, mapped this addition and used it as the identificationAttribute. This probably isn't the best solution but it works for now. (So my id is always 0 in my response)
I also included some validations within my IndexInfo model.
infoMapping.identificationAttributes = @[@"id"];
    [infoMapping addAttributeMappingsFromDictionary:@{
                                                      @"id" : @"id",
                                                      @"first" : @"first",
                                                      @"last" : @"last"
                                                      }];

validation:
- (BOOL)validateFirst:(id *)ioValue error:(NSError **)outError { ....

I also needed:
infoMapping.performsKeyValueValidation = YES;
infoMapping.discardsInvalidObjectsOnInsert = YES;

Instead of
//    infoMapping.assignsDefaultValueForMissingAttributes = NO;

The id is not ever used so I'l figure out a more elegant way and update answer.


Building out an OpenStack lab and want fault tolerance

Question: I want to move away from VMware and onto OpenStack for our development lab. This mini project is meant to be an opportunity to learn about OpenStack as part of a larger strategic move for the company that will be happening in 2025/2026.
One thing important to the DEV lab is that I want VMs to be fault-tolerant. Meaning, if a host were to go offline, I want VMs to fail over to one of the other running hosts. Is this possible to do without having a shared NAS/SAN? Is there a way we can have 3x separate hosts but have data stores replicate to each host?
Comment: Of course. Clustered filesystem, network shares, there are multiple possibilities. Recommendations are however off topic.
Answer: You can create a Hyperconverged Infrastructure on OpenStack. This means that Ceph nodes are deployed on the Compute nodes. You can configure to use the Controllers as Compute nodes too.
Comment: Would you happen to have any articles you can point me towards?
Comment: https://thenewstack.io/openstack-and-ceph-for-distributed-hyperconverged-edge-deployments/
Comment: Red Hat doc: https://access.redhat.com/documentation/en-us/red_hat_openstack_platform/17.1/html/deploying_a_hyperconverged_infrastructure/index


Basic Git branching

Question: I am fairly new with Git and using Git on my windows machine through the command prompt.
Currently I only have got one master branch and I want to create a new branch (current). I'm a bit confused with some of the commands.
Can someone give me some instructions to follow? I don't find git references very useful. I am not new to source control, just new to Git. Thanks.
Comment: http://git-scm.com/book this is an excellent resource
Comment: or read gitready.com, which is a really good tutorial site.
Answer: This book will give you good introduction. It explains the commands in very detail and some with graphs to let you know the work process of git.
http://git-scm.com/book
You can give create a branch with command like this:
git checkout -b branch_name

Answer: I recommend reading the git pro book - it's not a long read, and its free. It will teach you all the important concepts and would be much better than just giving you the branching syntax.
http://www.git-scm.com/book
However, to branch try:
git checkout -b <name>

Which will create a new branch and switch to it.
Answer: Please read the Pro Git book.
To make a branch in the same place as you are in history:
git branch branch_name

to switch to that branch use
git checkout branch_name

you can do both of those at the same time with:
git checkout -b branch_name

to keep alternating between the last 2 branches use
git checkout -

(this is the similar to the behaviour of cd -)
Once you get better with the syntax of git, use a good branching strategy and stick with it. I use Branch per Feature.
Answer: This tutorial is the best interactive tutorial available online if you would like to clear your concepts of git branching.
http://pcottle.github.io/learnGitBranching/index.html?demo
Answer: to create a branch
$ git checkout -b your_branch
to add to staging area and commit changes - all(shortcut)
$ git commit -a -m "your message"
to push to hithub(only if you already have a repo)
$ git push origin your_branch
Comment: the question is about branches - not committing or pushing. Please keep answers on topic.

Basic Git branching


How to receive hover events on QGraphicsItems during drop?

Question: I use two different QGraphicView's and do drag'n'drop between them. The dragdrop does work very well so far. In one of my QGraphicView's I have items that receive hover events so that they are lighted when the mouse moves on them. The problem is that during drops and also during moves on items, the hover events won't get called. Is it possible to overcome this behaviour somehow? The hover events mark the places the drop can occur in my view and the items then have to be dropped at the right places accordingly (they can only be inserted at specific places and the user should get some feedback).
I hope I could describe my problem...I posted no code for now, because I do not know if this is even possible.
Thanks!
Answer: I'm not too familiar with the graphics view framework yet, but you'll probably need to subclass QGraphicsView (if you haven't already) and override QWidget::DragEnterEvent. Depending on how you coded your objects, they might also have a DragEnterEvent that you can use.
In either case you'd accept the QDragEnterEvent and have it trigger the hover event. Hope that points you in the right direction.


one subclass does not inherit methods of the superclass but the other does. How to do it?

Question: I have a SuperClass Named Vehicle which among other fields have a field/method called Chain. Now I have 2 Subclasses as Car and Bike. Now we know that Bike needs the Chain but the Car doesn't. So How in Java, we ensure that the Chain Attribute is only inherited in the Bike CLass but not in the Car Class?? Now I also have other classes like Bicycle which also needs the Chain attribute.... So how to do it?
Comment: you can't, your model is broken.  why don't you just declare Chain inside of Bike
Comment: Now I also have other classes like Bicycle which also needs the Chain attribute.... So how to do it? In that case for every class that needs Chain, I have to declare it inside every class?????
Answer: You split it up
Vehicle
  * Other fields

MotorizedVehicle extends Vehicle
  * Specialized fields

NotMotorizedVehicle extends Vehicle
  * Chain

Car extends MotorizedVehicle

Bike extends NotMotorizedVehicle

Comment: I would used ChainDriveVehicle rather than NotMotorizedVehicle. Consider a horse drawn carriage, a dog sled, and a penny-farthing bicycle.
Comment: Yeah I didn't really put much thought in the same, just wanted to make the meaning somewhat clear. ChainDrive is definitely a lot better.
Answer:
So how do we ensure that the Chain attribute is only inherited in the Bike class but not in the Car class

You can't.
Every subclass inherits all public fields and methods of its superclass.  If it didn't then Java would not be properly implementing subtyping / the Liskov substitution principle which is at the core of Object Oriented Programming.
The correct solution is to not make the Chain attribute of Vehicle.

In the case of a method, Java does offer you an alternative; e.g.
  public class Tram extends Vehicle {
      ...
      public SteeringWheel getSteeringWheel() {
          throw new UnsupportedOperationException(
                  "A tram has no steering wheel");
      }
  }

... but it is poor design, and you should avoid it if possible.
Answer: Declare the Chain member field inside of Bike, where it belongs.  What you are asking for is not possible, nor is it really necessary.
Comment: Now I also have other classes like Bicycle which also needs the Chain attribute.... So how to do it? In that case for every class that needs Chain, I have to declare it inside every class?????
Comment: No, make a common Parent class of those classes.  That class will be a subclass of vehicle
Answer: If your Vehicle class has Chain attribute then all the classes extending Vehicle will inherit chain attribute.  There is no exception in that because that is what Inheritance is in OOP. You can opt out not using chain property in Car class and in Bike you can use it.
Also as Jeroen pointed out you can implement the class design like that also, which is I would generally do in such case.
Answer: It is bad design to put chain member in Vehicle class, because not all Vehicles have chain.
It is bad design to put members where they shall not be because of code re-usability.
If you really need to avoid code duplicates define an abstract class named ChainedVehicle extends Vehicle and add chain member to that, now you have a proper superclass for chained-vehicles.
Answer: If your vehicles can be organized as a hierarchy, use Jeroen Vannevel's answer. If you need more flexibility, consider a set of interfaces representing vehicle features.
HasChain would be implemented by any chain drive vehicle, including Bicycle.
HasWheels would be implemented by MotorBike, Bicycle, Car, and HorseDrawnCarriage, but not by DogSled.
Motorized would be implemented by MotorBike and Car.
AnimalDrawn would be implemented by HorseDrawCarriage and DogSled.


Question about convergence of sequences

Question: Given a sequence $x_n$ = $\sqrt{1}$ , $-\sqrt{1}$,$\sqrt{2}$,$-\sqrt{2}$...
If $$y_n = \frac{x_1 + x_2 + x_3 + x_4 + \ldots +x_n}{n} $$
Then sequence $y_n$  is
1.Monotonic
2.NOT bounded
3.bounded but not convergent
4.convergent
From first observation i thought of using cauchy first theorem on limits of sequence .For that i need to evaluate limit of sequence$ x_n $ .But that limit doesnot exist as two subsequence co verge to different limit but answer is given by option 3 .I would like to know where i went wrong and what can be done here .Thanks
Comment: We have $y_{2n} = 0$ and $y_{2n+1} > 0$ for every $n,$ so $y_n$ isn't monotonic.
Comment: Moreover remark that $y_{2n+1}=\sqrt{n+1}/(2n+1)$ and squeeze.
Comment: @Tom-Tom but when i use cauchy first t
Comment: What do you call Cauchy first theorem ?
Comment: @Tom-Tom sorry i see now my mistake
Answer: If n is even, $y_{n}=0$.
If n is odd, let $n=2k+1$, then $y_{n}=\frac{x_n}{n}=\frac{\sqrt{k+1}}{2k+1}$.
Therefore the sequence converges to $0$.
Answer: I think the answer is 4. convergent
$y_{2n} = 0, y_{2n+1} = \frac{\sqrt{n+1}}{2n+1}$. It's clear that sequence is not monotonic and it is bounded by 1. The subsequence $y_{2n+1}$ converges to $0$ and the subsequence $y_{2n}$ is identically $0$. Hence, the sequence $y_n$ converges to $0$.
Comment: When i use cauchy 1st theorem limit doesnt seem toexist
Comment: No, it's not contradiction to Cauchy 1st theorem. The theorem makes hypothesis that - $x_n$ converges - but $x_n$ doesn't converge here. Its a special case where $x_n$ might not have limit but $y_n$ does. There are many such examples.
Comment: Oh i was applying converse part of theorem
Comment: The converse is not true!
Comment: Yes yes sorry for blunder
Comment: You can apply the theorem only when $x_n$ converges or you can use the contrapositive statement - if $y_n$ does not converge then $x_n$ does not converge.
Comment: How you came up with expression for odd terms
Comment: You can verify by inspection!

Question about convergence of sequences


Problema com acentuação e caracteres especial deixar termo do autocomplete em negrito

Question: Tenho esse script que faz um busca usando ao autocomplete do Jquery.

$( function($) {
    $.ui.autocomplete.prototype._renderItem = function (ul, item) {
        var t = String(item.value).replace(
        new RegExp(this.term, "gi"),
        "$&");
        return $("

")
        .data("item.autocomplete", item)
        .append("" + t + "")
        .appendTo(ul);
    };

    $( "#p" ).autocomplete({
        source: "php/search_palavras.php?id_cidade=<?php echo $id_cidade; ?>",
        minLength: 2,

        select: function( event, ui ) {
            // Set autocomplete element to display the label
            this.value = ui.item.label;

            // Store value in hidden field
            $('#hidden_p').val(ui.item.id);

            // Prevent default behaviour
            return false;
        }
    });

    $( "#p" ).click(function() {
        $('#hidden_p').val(0);
        $('#p').val('');
    });
});

Quase tudo está perfeito.
O único problema que estou tendo, não sei se é o PHP ou o Jquery, mas, se eu começar uma procura com "aco", vem as respostas:
Açougues
Sacolões Hortifrutigrangeiros
Centrais de Informações Turísticas
Atacado e Fabricação de Sacos plásticos
Tentei de todas as formas, mas não consigo destacar o "aço" ou "açõ" que estão com cedilha e acentos.
Seria possível destacar esses itens também?
Comment: Você esta apenas esta enviando o texto para seu servidor, que deve tratar os resultados que deve retornar, desta forma creio que seu problema não seja nem com PHP nem jQuery e sim banco. Ex.: `Mysql  collation utf8_general_ci`, se ele esta setado assim ele não faz distinção entre acentuadas ou não.
Comment: Na tabela que faço a pesquisa, o campo está com utf8_general_ci. Na página de busca do PHP, coloquei um mysqli_set_charset($config,"utf8"); para não ter problemas com acentuação, mas mesmo assim, não destaca a acentuação.
Comment: Para ajudar: https://alistapart.com/article/accent-folding-for-auto-complete
Answer: Eu não tenho certeza se é isso que você quer, mas tenho um solução. Use a função htmlspecialchars() na saída dos dados.
Comment: Fiz isso, mas continua a mesma coisa.


href to an element in the same page in HTML Mail

Question: Im trying to add a link to an element in the same page:

         .
         .
         .

which works fine. but when the page is being send in mail message, the link is being open in a new tab in the browser, and doesn't simply jump to the element in the html mail message.
I tried with the quotes (of the id name) and without. I tried to give a full path to the element, nothing works.
any suggestion?
thanks.
Comment: try ``
Comment: Can you try putting target = "_self" in the anchor tag and see if that works?
Comment: Inherently depends on which mail client the recipient is using. Thus, not a programming question; voting to close.
Comment: I tried on gmail, gmail app on iphone, hotmail, outlook, I don't think its the client as all client behave the same here. don't you agree?
Answer: You can use anchor
Link to your element

to link to id

or name
...

it's possible but not working everywhere http://www.campaignmonitor.com/blog/post/3322/the-trouble-with-anchor-links-in-email-newsletters/
Comment: no, still doesn't work. It works fine in the web page, but when im sending the page as html (Ctrl+c to the page into the mail message and send it to a client), the link is being open in a new tab in chrome. what im doing wrong?
Comment: @adiohaion look at this : http://www.campaignmonitor.com/blog/post/3322/the-trouble-with-anchor-links-in-email-newsletters/


Is there a correct order to learning maths properly?

Question: I am a high school student but I would like to self-learn higher level maths so is there a correct order to do that?
I have learnt pre-calculus, calculus, algebra, series and sequences, combinatorics, complex numbers, polynomials and geometry all at high school level.
Where should I go from here? Some people recommended that I learn how to prove things properly, is that a good idea? What textbooks do you recommend?
Comment: There are many routes that lead to many places.  Calculus is a useful analytical tool, but it is not a "crowning achievement".
Comment: Given that your name is "Alexander Jones", it is hard to resist recommending that you study knots and/or polynomials.
Comment: What do you mean?
Comment: $@$Alexander: It was (supposed to be) a joke.  See http://en.wikipedia.org/wiki/Alexander_polynomial and http://en.wikipedia.org/wiki/Jones_polynomial.
Comment: I don't know that many maths-related jokes haha :)
Comment: You probably want an *efficient* order. There is no *correct* order for acquiring true statements, because they integrate without conflicting with each other, but knowledge consists of a graph of dependencies which sometimes work better when navigated in certain directions.
Comment: @PeteL.Clark I thought of the connection when I made my Vaughn J. post below. Was wondering if it would be caught.
Answer: I'm not mathematician. I hold degree in management both bachelor's and master's degree. Anyway, to my knowledge, if you want to learn math from scratch, the order will be
college algebra, algebra & trigonometry, precalculus, calculus, linear algebra, differential equation, intro to analysis (or advanced calculus), functional analysis, real analysis, probability theory
There're some books I recommend

College Algebra by Henry Burchard Fine
Fundamentals of Algebra & Trigonometry by Earl Swokowski
Precalculus by Sheldon Axler
Calculus vol.1&2 by Tom M. Apostol
Introduction to Linear Algebra by Gilbert Strang
Mathematical Analysis by Tom M. Apostol
Introductory Functional Analysis with Applications by Erwin Kreyszig

Supplement: How to Prove It by Daniel J. Velleman. You need this book to learn how to do rigorous proofs for mathematical theorems.
Answer: One general approach is to select a college, and start working through topics that an undergraduate mathematician would see.
It is a good idea to know proper techniques of proof, but that can also be picked up by reading lots of "good" proofs.  If you feel comfortable with proving some basic things (e.g. the sum of two odd numbers is even) on your own, then I'd suggest just picking up proper methods of proof by reading other people's more advanced proofs.
From looking at what you've done, it seems that Linear Algebra could be a good next step, or perhaps a multivariable calculus course (if you haven't done that already).
Comment: @PeteL.Clark Sorry.  bad choice of words.  I meant to pick some college (preferably a good one) to get an idea of what's required for a math degree (e.g. Abstract algebra, real analysis, etc), and also to get an idea of in what order they are typically taught.  I figure that it doesn't really matter what school you model your self-teaching after, so long as it's a "real" school.  Of course, you should pick the college that you enroll en carefully.
Comment: What does "pick a college at random" mean?  Not to randomly choose an undergraduate institution in which to enroll, I hope??
Comment: I will see if I can find the undergrad course structure for uni of sydney, that is the best uni in sydney and I will most likely go there (although it is ranked 50th in the world lol).
Answer: Quite often the transition to higher, pure math is real analysis. Here proofs really become relevant. I would suggest this free set of down-loadable notes from a class given at Berkeley by Fields medal winner (math analog of Noble Prize) Vaughan Jones.
https://sites.google.com/site/math104sp2011/lecture-notes
They are virtually verbatim and complete as a text. They build gradually so you can get a good base. The material is Prof. Jones's own treatment and the proofs are quite accessible and beautiful.
You might just give it a try and see if it works for you.


How to create a NodeJS + LoopBack Application using WebStorm?

Question: I am using WebStorm v 9.0.3. I would like to create a Strongloop/Loopback Application + NodeJS Application. Is there a way to create it directly through WebStorm IDE or should we manually do it using commandline.
Currently I can see only NodeJS Express App provision during project creation in WebStorm.
I am using Ubuntu 14.04 LTS System.
Kindly help me do it.
Answer: Creating makes not too much sense as all generators are command line tools. You can of course run the generators from your webstorm console. For debugging you can create a node run configuration:
Comment: Very useful screenshot. For me the path was: `/usr/local/lib/node_modules/strongloop/bin/slc`
Answer: Use the command slc loopback and follow the menus with what you need. Then just drag the folder to webstorm.
For creating the models it is easy with the terminal too. Every model or stuff you create it will be reflected in WebStorm then you can easily edit there.
For running also it is easy with the command slc run.
There is no way with WebStorm IDE. At least yet...
Answer: There is no way to scaffold the app in Webstorm directly ATM (if you want to see this feature, please read https://github.com/strongloop/loopback/wiki/Issues and submit a feature request)
That said, you can scaffold the project using the command line via slc loopback then simply open the project in WebStorm.


Solving an equation of terms containing a variable in their denominator

Question: I am having issues solving the following equation:
$$\frac{x}{2x-3} - \frac{1}{2x} = \frac{3}{4x-6}$$
The resolution of this is 1.
It is in the section of parabolas and it should be pretty easy to solve.
My steps are as follows:
$$\frac{x}{2x-3} - \frac{1}{2x} = \frac{3}{4x-6}$$
Multiply by $2x(4x-6)$
$$4x^2 -1(4x-6) = 6x$$
gets me here, remove $6x$
$$4x^2 - 10x + 6 = 0$$
Solving this with the parabola formula I ended up getting $\{4,6\}$.
Comment: You've misapplied the quadratic formula; if you try substituting 4 and 6 into your original equation, you do not have an equality. Post what you did with the quadratic formula and maybe we can debug from there.
Comment: @J.M.: He divided by $2$ instead of $2a$ (that is, instead of $8$, or instead of $4$ if he first divided the whole equation by $2$).
Comment: Shaharyar, you might want to post that as an answer and accept it so we have less unanswered questions in this site. :)
Comment: Done, will have to wait 2 days to be allowed to accept it :)
Answer: HINT $\rm\displaystyle\quad \frac{1}{2\ x}\ =\ \frac{2\ x}{4\ x-6} - \frac{3}{4\ x-6}\ =\ \frac{1}2\ \ \Rightarrow\ \ x\ =\ \ldots\quad$ Note: no quadratic formula needed.
Answer: @J. M. :
After checking out the formula I found out that I dividing by $2$ instead of $4a$/$8$
$$\frac{10 \pm \sqrt{100-96}}{2}$$
With the fixed form I get the results $1.5$ and $1$ of which $1$ is matching result.
Thanks for the kind support!
Comment: And do you see why you need to discard the solution $x=\frac{3}{2}$?
Comment: Yup, evil division by $0$ of doom.


Is there any difference between the size of memory allocated for the following types of declaration:

Question: i) static int a, b, c;
ii) int a; int b; int c;
I am not sure as to how will the memory be allocated for these types of declaration. And if these declarations are different then how much memory is allocated for each declaration?
Comment: Several good answers already discuss the "where" of the allocations, so I won't rehash that, and no need for another separate answer. But, I wanted to note, that the memory *used* by each `int` will be exactly the same, but it's entirely possible that alignment or other issues *might* dictate that the actual memory allocated to make room for those variables could be somewhat more than what is actually used for the variables.
Answer: static int a,b,c;

will allocate three ints (probably 32bits each, or 4 bytes) in the DATA section of your program. They will always be there as long as your program runs.
int a; int b; int c;

will allocate three ints on the STACK. They will be gone when they go out of scope.
Comment: One caveat - the second case assumes they are declared inside of a function.  If they are declared globally, I think they will go in the DATA section as well.
Comment: To be strictly pedantic, few operating systems will put them in a data section. They will most likely go into bss. And if they are in a function, the non-static ones might not get any memory allocated to them at all if there are enough registers.
Comment: @Claudio Daffra a global variable, even without the specifier 'static' will be initialized at program start. C11 220.127.116.11.
Comment: Thanks. This seems helpful :)
Comment: with keyword static variabile will be assigned 0
Answer: There is no difference between the size of memory for
static int a,b,c;
int a;int b;int c;

Differences occur in the lifetime, location, scope & initialization.
Lifetime: Were these were declare globally, both a,b,c sets would exist for the lifetime of the program.  Were they both in a function,  the static ones would exist for the program lifetime, but the other would exist only for the duration of the function.  Further, should the function be called recursively or re-entrant, multiple sets of the non-static a,b,c, would exists.
Location: A common, thought not required by C, is to have a DATA section and STACK section of memory.  Global variables tend to go in DATA as well as functional static ones.  The non-static version of a,b,c in a function would typically go on in STACK.
Scope: Simple view: Functionally declared variables (static or not) are scoped within the function.  Global variables declared static have file scope.  Global variables not declared static have the scope of the entire program.
Initialization: follows along the same track as lifetime.  Globally declared a,b,c, static or not, are both initialized at program start.  If a,b,c are in a function, only static ones are initialized (at program start).  Functional non-static a,b,c are not initialized.
Optimization may affect location, especially for the functional non-static a,b,c which could readily be saved in registers.  Optimization may also determine that the variable is not used and optimizing it out, thus taking 0 bytes.
Answer: The variables that are defined as static will allocated in data segment at compile time. The same is true for global variables even though they are not static. Non-static variables defined within a block are allocated on the stack when the block is entered at runtime and are deallocted when th block is exited.
The amount of memory allocated is implementation dependent. The standard requires that an int is large enough to hold a 16-bit (2 byte) valued, but is can be larger. Most compilers you are likely to use now adays use 32-bit ints.
Answer: If we assume that 2nd declaration is inside function, than As Bard and Nashant already said these will be allocated in different memory sections (OS and compilers dependent).
But though variable size will be of the same size, they CAN consume different amount of memory.  If function (from 2nd declaration) is called recursively for example, there will be multiple instances of variables from 2nd declaration.


Series sum of Fractional Fibonacci Series

Question: Please help me proving that
$\sum_{n=1}^{\infty} F(n)/(10^{-(n+1)}) = 0.011235955...$
Where F(n) are the Fibonacci Numbers
Comment: I find an exactly same question on another site: https://artofproblemsolving.com/community/c6h1783319p11761653 (searched from [Approach0](https://approach0.xyz/search/?q=%24F%5Cleft(n%5Cright)%5Ctimes10%5E%7B-%5Cleft(n%2B1%5Cright)%7D%24%2C%20Fibonacci&p=1)). Hope it helps you.
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be put on hold. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: Did you really mean to have that $/$? If so, the answer is $\infty$.
Comment: There is an explicit formula for the Fibonacci numbers.
Comment: Work out $\sum_{n=1}^\infty 10^{-n}F(n)$ and then divide by $10$.
Comment: Multiply the sum by 10, then add it to the sum.
Comment: @WeiZhong: this is *not* the same question ! There is a very significant difference.
Comment: @YvesDaoust where is the difference?
Comment: @WeiZhong: see my answer. I claim that the OP didn't ask the right question.
Answer: The first terms of the summation are
$$0.01+0.001+0.0002+0.00003+0.000005+0.0000008+0.00000013+0.000000021+0.0000000034+0.00000000055+0.000000000089+0.0000000000144+0.00000000000233=\color{green}{0.011235955}05573.$$
Then it is no more possible to have a carry on the last digit $5$ and the nine first decimals are exact.

For rigor, we can check that $F_n<2^n$. Indeed by induction
$$F_{n+2}=F_{n+1}+F_n<2^n+2^{n+1}<2^{n+2}$$
and $F_0<2^0$.
So the error in the above evaluation is less than
$$\frac4{5^{13}}=6.6\cdot10^{-10}.$$


What equipment do I need to listen to a synthesizer?

Question: I was just given a used Arturia Mini Brute to mess around with. What basic equipment do I need to amplify/hear the sound produced? I have already purchased headphones. If it is not obvious, I have almost no experience with electronics.
Comment: Headphones are all you need. Is there something else you are trying to do where the headphones don't let you do that?
Comment: Note that if you want to clarify your question, the way to do that is log on to the site and then click the grey "edit" button in the lower left corner of the question. Then you can change or add to your question and everyone will be able to see the changes and provide better answers.
Comment: I do have headphones, but what about being able to listen/compose in an open space? I don't want to broadcast to a large audience, but maybe a small group...
Answer: According to the "main features" information at the bottom of https://www.arturia.com/products/hardware-synths/minibrute/overview it has a 1/4" audio output, and a 1/4" headphone output.
Most "consumer quality" headphones have a smaller 3.5mm plug, which is the standard size on cellphones, etc. If that is what you have, you need a "3.5mm socket to 6.35mm jack plug audio stereo adaptor" like this (1/4 inch is the same size as 6.35mm).

These are very widely available, and cheap. As usual, you get what you pay for - the very cheapest ones may not be very durable.
Note, if you buy one by mail order, make sure you are ordering exactly what it says above - you don't want one has a 3.5mm plug and a 1.4" socket, which would let you plug "professional quality" headphones into a cellphone!
Comment: The cheapest aren't very durable, but in my experience even those tend to get lost before they stop working...
Answer: Just plug in your headphones and let the fun begin.
Comment: Normally we like more involved answers here, and at the same time, it does seem like the asker already has what they need. This is normally a job for a comment to clarify what the asker is really talking about. We understand that you are not yet able to comment. As you can see, I have commented asking for more detail about the question. I think once we get more details, we will be able to answer with a complete, high quality answer. Right now, this answer has been flagged as being short and having little information. I'm not recommending deletion, but please be slower to answer in the future.


Adding custom designed product to cart in drupal commerce

Question: Hi I am developing a site for T-shirt designing. I have a custom UI where all the T-shirt products in my site are loaded. customer can design the T-shirt according to their needs like changing color,adding text/image etc using my UI. At the end of UI I have a buy button where user can buy the custom product. How can I add this product to my Drupal cart when user clicks buy button? I have the product id and price loaded in my hand and am using Drupal commerce module in my site.
This is my button form
<code><button type="submit" class="btn btn-primary"  name="button">
                                Buy Now! </button>
</code>
Answer: I think you can done it using commerce_cart_product_add(). Pass product id and line item as parameters. For details please check here.Hope this will help you..


How can I use mutate() with a string column?

Question: I have a tibble something like
data <- tibble(string = c("A", "B", "C"), number = c(1,2,3))
Then I defined a function
foo <- function(string, number){
  result <- paste(replicate(number, string), collapse = "")
  return(result)
}

so that foo("A", 3) = "AAA". Now what I want to do is to add a new column new where the value for each row is foo(s, n), given that s and n are the values of string and number for the same row. I tried to do this by doing something like
mutate(data, new = foo(string, number))
but I failed and don't know why.
Comment: There is a dedicated function to do this `strrep(string, number)`.
Comment: The function `foo()` was defined like above for explanatory purpose. The actual function I defined does NOT look like that. It is a function that takes string and double as arguments. And still, I don't get  the reason why `mutate()` works for `strrep()` and doesn't work for `foo()`.
Comment: I get ```Error: Problem with `mutate()` input `new`.
x invalid 'length' argument
i Input `new` is `foo(string, number)`.```
Answer: Try rowwise, therefore foo is calculated for each row.
data %>%
  rowwise() %>%
  mutate(new = foo(string, number))

Output:
# A tibble: 3 x 3
# Rowwise:
  string number new
  <chr>   <dbl> <chr>
1 A           1 A
2 B           2 BB
3 C           3 CCC

The problem might be that foo cant handle vectors. Like in this examples.
So a rowwise apprach is needed.
foo(c("A", "B"), c(1,2))
# Error in integer(n) : invalid 'length' argument

foo(data$string, data$number)
# Error in integer(n) : invalid 'length' argument

Answer: In this scenario, there is no need to define a new function.  This will work-
data %>% mutate(new = strrep(string, number))

# A tibble: 3 x 3
  string number new
  <chr>   <dbl> <chr>
1 A           1 A
2 B           2 BB
3 C           3 CCC


Erro: Access-Control-Allow-Origin, para uma requisição ajax

Question: Para a requisição AJAX abaixo:
var url = "minhaurlaqui";
$.ajax({url: url,  success: function (retorno)
}

Tenho o seguinte retorno:

"Access to XMLHttpRequest at 'urlaqui' has been blocked by CORS
  policy: No 'Access-Control-Allow-Origin' header is present on the
  requested resource."

Não consigo ajustar isso em local algum, alguém poderia me dizer o que está faltando fazer na requisição Ajax ?
Comment: Olá Diogo! Pode por favor informar para qual URL está tentando realizar a requisição? Por acaso seria uma URL local?
Comment: Sim, mas abaixo recebi as resposta pra dúvida, que quem bloqueia é browser, de qualquer forma muito obrigado.
Comment: A forma mais rápida: Usando uma extensão. Nunca fiz isso mas achei essa. https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi Se tiver usando alguma lógica nesse teu endpoint fala aqui, pois é possível habilitar isso por ele.
Answer: Não está faltando nada na sua requisição (apesar do callback de sucesso não estar definido).
O navegador que está barrando a resposta por conta da política de origem cruzada. Como você está fazendo uma requisição para uma rota não-local, seu navegador supõe que você pode estar tentando roubar recursos de outro website.
Na resposta do serviço que você está tentando utilizar, é necessário que haja o header Access-Control-Allow-Origin: [seu website] ou Access-Control-Allow-Origin: * para que o navegador entenda que esta resposta do servidor pode de fato ser entregue ao usuário.
Note que o navegador não te impede de enviar a requisição, e tampouco o servidor te responde com um erro, o servidor de fato processou sua requisição e te deu uma resposta, mas o navegador se recusou a exibi-la.
Comment: Entendido, muito obrigado, era bem essa resposta que precisava.


AWS Cli doesn't include specific command switch even though the documentation shows that it should, any idea how to solve it?

Question: AWS have announced 5 days ago that they now support VPC peering over different regions.
Source:
https://aws.amazon.com/about-aws/whats-new/2017/11/announcing-support-for-inter-region-vpc-peering/
In regard to the AWS Cli command which helps you achieve that peering connection, please check this link:
http://docs.aws.amazon.com/cli/latest/reference/ec2/create-vpc-peering-connection.html
You will see that the command has been extended and now can get a new switch "[--peer-region value]" but after upgrading my aws-cli to the latest version, the switch is not included there.
These are the switches I have:
NAME
       describe-vpc-peering-connections -

DESCRIPTION
       Describes one or more of your VPC peering connections.

       See also: AWS API Documentation

SYNOPSIS
            describe-vpc-peering-connections
          [--filters <value>]
          [--dry-run | --no-dry-run]
          [--vpc-peering-connection-ids <value>]
          [--cli-input-json <value>]
          [--generate-cli-skeleton <value>]

The AWS Cli version I have installed is:
aws-cli/1.14.2 Python/2.7.10 Darwin/16.4.0 botocore/1.8.6

The Python 3.6 aws-cli also lacks this switch.
Can it be that the official AWS documentation has been updated but the AWS Cli not?
Anyone else bumped into this issue?
Answer: The command create-vpc-peering-connection has the option --peer-region on my system.
You show the command syntax for describe-vpc-peering-connections. This command does not have the --peer-region option.
Are you confusing the two commands together?


Tem como fazer que o recálculo automático do Excel acione uma rotina em VBA?

Question: Eu tenho um esquema gráfico em Excel que é feito por meio de formatação condicional (ver figura abaixo), ou seja, nas células coloridas não há conteúdo, somente as cores de fundo são alteradas com base em valores de outras células.

A linha azul tracejada é feita por uma rotina em VBA (as conexões são complexas para se fazer também as bordas pela formatação condicional), ocorre que o usuário após lançar os valores quando precisam ser alterados, as figuras são atualizadas dinamicamente pelo próprio Excel, mas a linha tracejada necessita que um botão seja acionado para que o VBA refaça as conexões (o que é natural), ou seja, há discrepância visual entre os dados e os resultados gráficos apresentados até que a rotina seja acionada.
Isto prejudica o próprio lançamento de dados que depende do resultado desejado daquilo que se está analisando graficamente. A figura abaixo mostra esta situação, a desconexão da linha tracejada que não é alterada dinamicamente.

A próxima figura mostra o resultado após a rotina ser acionada por meio do botão.

A rotina refaz as conexões imediatamente sem apresentar tempo de espera. O que não consegui encontrar é uma forma da rotina ser acionada dinamicamente assim que o Excel refaça os cálculos automaticamente para qualquer alteração que for feita na planilha.
O Application.Calculate aciona o cálculo no Excel (idem teclar F9) a partir do VBA, o que preciso é o inverso, o recálculo automático do Excel acionar a rotina em VBA.
É possível?
Answer: Infelizmente não tem uma maneira simples de fazer isso; é necessário quebrar a cabeça e bolar um sistema de liga/desliga do recurso Application.Calculation. Os modos desse recurso são:
Application.Calculation = xlCalculationAutomatic     'Cálculos automáticos
Application.Calculation = xlCalculationManual        'Cálculos automáticos desativados
Application.Calculation = xlCalculationSemiautomatic 'Cálculos automáticos, menos em tabelas

Uma sugestão que eu te dou é aplicar a seguinte ideia no módulo da worksheet que vc altera os dados e exibe o 'gráfico':
Private Sub Worksheet_Activate()
    Application.Calculation = xlCalculationManual
End Sub

Private Sub Worksheet_Deactivate()
    Application.Calculation = xlCalculationAutomatic
End Sub

Assim, quando vc selecionar a planilha com o gráfico, o VBA vai rodar o evento Activate, desligando o cálculo automático, e ele se restaurará automaticamente ao acessar qualquer outra planilha. Para complementar a resposta à sua questão, basta então adicionar uma linha com Calculate no código que roda com seu botão para ver todas as mudanças gráficas simultaneamente ao clique do botão. Coloque no início do código para ter os resultados dos cálculos antes de manusear as bordas tracejadas.
Obviamente, vc pode pensar em outras maneiras de aplicar esse recurso, mas tenha em mente que ele SEMPRE vai se aplicar a todo o Excel (todos os arquivos abertos).
Comment: Submeti uma outra resposta. Veja se essa lhe resolve!
Comment: Tash_Riser, obrigado pela resposta. Para o meu caso isto não resolve, pois todo o trabalho neste gráfico é feito em uma única aba. O que é alterado são valores em células correspondentes ao desenho no esquema gráfico, portanto teria de funcionar a cada recalculo do Exzcel, quando uma célula qualquer tem seu valor alterado.
Answer: Use o evento Calculate para a worksheet em que está o botão e o gráfico, assim:
Private Sub Worksheet_Calculate()

    Call Sub_Usada_no_Botao

End Sub

Assim, toda vez que algum cálculo ocorrer na sua planilha, a Sub será engatilhada.
Comment: Tash_Riser, muito obrigado, funcionou perfeitamente. Eu pesquisei o evento e acabei achando no SO em Inglês como fazer a mesma coisa, mas somente para determinadas células, vale a pena conferir. http://stackoverflow.com/questions/4388279/how-can-i-run-a-vba-code-each-time-a-cell-get-is-value-changed-by-a-formula
Answer: O mesmo pode ser feito para acionar uma rotina somente quando houver alteração em uma ou mais células especificadas em uma Range.
Com base em uma das respostas para a pergunta How can I run a VBA code each time a cell get is value changed by a formula?, encontrei uma forma mais simples para obter o mesmo resultado:
Private Sub Worksheet_Change(ByVal Target As Range)

Dim AlterouNaFaixaDeDados As Range

 'Indique na Range a faixa que queira acionar uma rotina dinamicamente se houver alteração nas suas células
 Set AlterouNaFaixaDeDados = Application.Intersect(Range("B2:E5"), Target)

 'Se houve alteração em uma ou mais células desta Range, a rotina será acionada
 If Not AlterouNaFaixaDeDados Is Nothing Then

   'Coloque aqui a rotina a ser acionada
   Call Sub_Rotina

 End If

End Sub


Get the byte value of a string to replace it in xcode

Question: I want to be able to get a string (for example the letter @"A"), and I want to get what is the byte value (01000001) and change it to another byte value like (01000010) = B. Than convert it in a string again and replace the letter A for the letter B, in objective-c (xcode)
I'm I clear ? (maybe not...) Thanks for any help.
Vincent
Comment: A `char` is indistinguishable from a `byte` so what is your goal?
Comment: check this link....
   http://stackoverflow.com/questions/655792/how-to-convert-nsinteger-to-a-binary-string-value
Comment: My goal is to get the byte value (ex: 00100101) of a string like the letter @"A" and be able to change this byte value (UFC-8 format)
Answer: You can use characterAtIndex to get the character out of the NSString.  (It will return a unichar.)  It's a little tougher to go the other way, though.
It might be best to do getCharacters:range: to get the entire contents of the string, then initWithCharacters:length: to reconstruct the NSString.
Answer: @"foo" is actually an NSString, take a look at the class documentation here:
https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
Strings are immutable so you would need to use something like getCString to copy them to a char * buffer, change them and then create a new NSString using stringWithCString. Depending on the original encoding this may not do what you want.
Answer: I only have some background knowledge in Java, where I would tackle this problem as follows:
String has the methods length() and getCharAt(int index), which could be used in a for block to save each of the letters as a char, for example in an array. char s can be casted into an int:

char a = 'h';
int test = (int) a;

now all you have to do is to find or write a method changeIntegerToBinaryNumber() to get the binary number.
To get a letter from a binary number, the mentioned steps should just be reversed:
find / write a method changeBinaryToInterger(), cast int to char, optionally save the char in an array which again can be build together to a String...


Query webform submissions

Question: I'm attempting to perform a query on webform submissions so I can display all submissions submitted by a specific user. However I'm not sure how to make this query. I made a guess that webform submissions were nodes themselves and performed a query like this
<code>    $query = \Drupal::entityQuery('node')
        ->condition('type', 'webform');
    $nids = $query->execute();
    die(print_r($nids));
</code>
But it produced no results. Is there a way I can perform a query on webform submissions so that I can select all submissions authored by a specific user?
UPDATE: Looking through the webform module, I did see some code querying submissions.
<code>$query = $this->getQuery();
$query->condition('webform_id', $webform->id());
$query->condition('in_draft', FALSE);
$query->range(0, 1);
</code>
This is exactly the kind of query I want to perform but when I try to use getQuery() I get

Call to undefined function Drupal\my_module\my_helper_class\getQuery()

I understand how to start entity queries for nodes like this
<code> \Drupal::entityQuery('node')
</code>
But is there a way to start an entity query without specifying the entity type? Or is there a way to find out what kind of entity type webform queries are?
Comment: You get that error because `getQuery()` is only a method of the class that `$this` is referring to. Could you build a simple view to do this and just feed it a UID argument?
Comment: Unfortunately no, I cannot use a view in this situation since there is a lot more that needs to occur within this module other than just displaying the results.  Displaying the submissions is just a small part of the plugin.
Answer: Webform submissions are content entities, so something like this should work:
<code>$query = \Drupal::entityQuery('webform_submission')
    ->condition('uid', $uid)
    ->accessCheck(FALSE);
$result = $query->execute();
</code>
Comment: It's easy when you know some of the conventions - all entity types live in `Drupal\MODULENAME\Entity`, so I just downloaded the module, looked in src/Entity, found `WebformSubmission`, and checked its ID in the entity type annotation
Comment: Matt, you'd need to query the table directly. See my answer here:  https://drupal.stackexchange.com/a/267306/34673
Comment: Thanks that helps a ton! I'm sure that will help solve a lot of headaches in the future.
Comment: This worked! But how did you figure out that webform_submission was the proper entity name?
Comment: Would it be possible to user fields aside from id, created, and other base field definitions in a query? For instance if I added 'quantity' as a form field, is there a way I can do ->condition('quantity',5)? or ->sort('quantity','desc') I attempted using that syntax but it did not work.
Comment: Is there way to update an custom field in the webform submission by ~sid~
Answer: Remember to include accessCheck(FALSE) or you won't get any result.
<code>$query = \Drupal::entityQuery('webform_submission')
    ->condition('uid', $uid)
    ->accessCheck(FALSE);
$result = $query->execute();
</code>

Query webform submissions


Use fitdist parameters in variables

Question: I'm sure this is a simple problem, but I'm not sure how to search and find the answer. I have a set of parameters that I've estimated using 'fitdist':
Fitting of the distribution ' gamma ' by matching moments
Parameters:
       estimate
shape 0.2018062
rate  3.1255336

Now I want to pull those parameters and store them in variables. But I can't figure out how to separate them. I've tried:
> gamma.fit$estimate
    shape      rate
0.2018062 3.1255336

But how do I pull the specific elements? (e.g. shape = 0.2018062 and rate = 3.1255336)
I've tried using normal data frame tools but I get an 'incorrect number of dimensions' error. Any ideas would be greatly appreciated.
Answer: Using the fitdistr function from MASS, you can access the estimated parameters like I did it below. The same holds for fitdistrplus:::fitdist.
op <- options(digits = 3)
set.seed(123)
x <- rgamma(100, shape = 5, rate = 0.1)
ft <- fitdistr(x, "gamma")
ft$estimate["shape"]
   shape
6.486991
# or
ft$estimate[1]
   shape
6.486991

Same goes for rate.
If you do str(ft$estimate) you will see that this is a named vector. Since it's named, you can call it by name (["shape"]) or by index ([1]).
 Named num [1:2] 6.487 0.137
 - attr(*, "names")= chr [1:2] "shape" "rate"

Answer: In case anyone is still interested: you can just do this:
gamma.fit$estimate['shape']
gamma.fit$estimate['scale']

Answer: Suppose we already did fitdist [in case of library(fitdistrplus) for "nbinom".
To get desired parameters, following can use
SZ = as.numeric(as.vector(data.frame(unlist(fitNB))[1,])) # get size
MU = as.numeric(as.vector(data.frame(unlist(fitNB))[2,])) #get mu

Hope it helps too.
Answer: In case anyone is still interested in this question, you can also do the following.
Assume the dataframe is called foo. The parameters can be called as
 foo[["estimate"]][["shape"]]
 foo[["estimate"]][["rate"]]

If you are using Rstudio and go into the object, mouse down the right-hand side, You will see a little box with a green arrow pointing to the left. If you click on that box, on your row of interest, it will paste the extraction code for the parameter of interest into the console window.
That's a neat little trick I learned today as I was pulling estimates. (What does this little box thing do?)

Use fitdist parameters in variables


Intermediate exercises for sight reading, specifically for reading ahead

Question: I've been practicing violin casually for about 20 years and sight reading for about 10 -- but I'm still quite slow, especially when there are a lot of 16th notes and syncopation.
The problem for me is that I can't read more than one or two beats ahead, and so I stumble when things get intense. I seem to have a very small working memory.
Is there anything I can do to learn to read ahead?
Comment: we all do have a small working memory!
Comment: @ogerard Some more than others :)
Answer: You write

but I'm still quite slow, especially when there are a lot of 16th notes and syncopation.

That's natural. In my experience, it is better to train separately for sight reading and for speed of execution. The primary goal must be continuity of execution and respect of relative duration of notes.
The basic tool to improve this aspect of sight-reading (and it is not limited to music), is to be able to group information in your head in larger and larger patterns. The number of patterns that you can hold in your working memory is not much larger, but the information content and the speed at which you can see ahead are greatly expanded.
When you learn to read in the latin alphabet (but something similar happens for kanjis), you first look at words as heaps of letters, each needing to be deciphered, then gradually are able to recognize specific syllables or small words quickly and consider them as units, then almost any word is a unit, then word groups, quickly scanning punctuation. When you learn to speak in public, be an actor, you develop a sense for learning whole verses and sentences, then whole speeches.
So be warned that sight-reading is partly specific to a given musical style (as it would be for a given language) and can be enhanced by good musical typography. That's one of the challenge of contemporary music. Almost every composer has his/her musical idiom.
Most teachers agree on what kind of activity develop sight-reading abilities, I give you two types of exercices that I find very useful:

Train to quickly memorize a whole bar: glance at it, try to play or sing what you remember of it slowly while looking away (but do not look at your fingers or at your instrument), skip one or two bars, do it again.  Do that with pieces and studies much simpler than your current playing level.  Try to describe/classify each bar in a personal language : "this is all repeated notes", "this is the same that two bars before", "Oh, I know that rhythm, that bowing", "This is a scale fragment", etc. Then make a short break and try to play the whole piece from the start, slowly again and enjoy a certain sense of familiarity.
Develop peripheral, structural vision, prepare for awareness of the score while playing. Try to be aware of your surroundings, of the color and shape of things surrounding the score while playing it, try to be a little farther from the score than you use to be.  Look at a score before trying to sight-read it (always aiming at a difficulty level lower than the difficulty level of works you train for and memorize). Choose one or two target bars, thinking something like "I will recognize you when your time comes".  Try to make for yourself a map of the score : rhythm and volume changes, repetitions, places where you will have to use the G string, pizzicati, double stops, fifth intervals, etc. places where the page and staff layout is awkward in relation to the music.  When you play the piece, try to recall and enhance these deductions. Do not use this awareness to play faster : use it to play better, more in tune, strict rythm, better respect of expressive indications, better placement of hands and body.
Comment: That is one *heck* of a helpful answer. Thanks a lot! I gotta try this out for a few weeks. And you're right; now that I think about it, I do have less trouble reading baroque and early classical than anything else, as that's what I've had the most practice with.
Comment: What Ogerard gracefully explained about the learning process is called Chunking: http://en.wikipedia.org/wiki/Chunking_%28psychology%29
Comment: Reading ahead is pretty tough. Reading a bar, storing in queue memory, playing said queue while memorizing another bar for queue is another thing
Answer: There's an exercise for learning to read ahead that's similar to the first one ogerard mentions only more externalized: as you're sight reading a piece, you cover up the measure you're currently playing, such that you're forced to look ahead to the next measure.
The problem with this exercise is it's difficult to do in solo practice, as you'll probably need a second person to cover up the measures for you.


Create a rule to send confirmation email message after anonymous/authenticated user has created content

Question: I have created a custom content type (CCK) called apply (machine name) and installed the Rules module. How would I go about sending the user an email (they could be anonymous or authenticated) after they have created content. I understand that I have to create a rule of some sort, could someone please walk me through it?
I want to capture the content of field_email_address somehow, as that is the field in which the user will be entering their email address.

This is my rule so far, not sure what to put in the Conditions and Elements section.
Answer:
Rules works with the token module. If you haven't installed it, do so now.
In your "apply" content type ("application" would be a better name), ensure that your email field is required, and set the default to use token [current-user:mail] so that it fills with the current user's details if they're logged in.
"Conditions" is the "if" part of your rule. You use it to narrow down when the rule fires and by whom. Given that you're not needing auth, you can leave this empty. You could test for various node / field properties here e.g. node is published / field has value etc. Because you specified a content type in your "Event", the fields from that content type will become available to the subsequent "Conditions" and "Actions".
"Actions" are what happens when you trigger your rule. This is where you specify the email action. Click "Add an action", and from the supplied dropdown, choose "System > Send mail" or "Send HTML email".
In the "to" field, you can now add a token referencing the user email - probably something like [node:field_email_address]. Click the "Replacement patterns" accordion to see available tokens for each mail param.
It you're wanting to templatize & theme your HTML emails, that's possible through other modules (mimemail + mailsystem) but requires a separate discussion.


Interface não reconhece tipo de classe mesmo com DLL declarada

Question: Criei um projeto Class Library e nele uma classe POCO. Criei uma Interface (tudo isso seguindo o livro do John Sharp). Depois criei meu WS com WCF. Bem, na interface eu declarei um método do tipo da minha classe criada na Class Library e a interface não reconheceu. Adicionei a DLL na referência do projeto e mesmo assim eu não consigo incluir no projeto. O que devo fazer?
Estou tentando de várias maneiras e sem sucesso. Já removi e adicionei a DLL, reiniciei a máquina e mesmo assim, nada. A classe está mapeada com DataContract. O código está assim:
using System.Data.Linq.Mapping;
using System.ServiceModel;
using System.Runtime.Serialization;

namespace SuporteTecnicoContracts
{
    [Table(Name="T_PDV")]
    [DataContract]
    public class TPDV
    {
        [Column]
        [DataMember]
        public int IDPdv { get; set; }
        [Column]
        [DataMember]
        public string CNPJ { get; set; }
        [Column]
        [DataMember]
        public string RazaoSocial { get; set; }
.......

Minha Interface
using System.ServiceModel.Web;
using SuporteTecnicoContracts;

namespace SuporteTecnico.Interface
{
    [ServiceContract]
    public interface ISuporteTecnicoContract
    {
        [OperationContract]
        [WebGet(UriTemplate = "/")]
        TPDV getCnpjParceiro(string _cnpj); ==> Não reconhece TPDV
    }
}

Comment: Só esclarecendo: `TPDV` está em uma DLL e `ISuporteTecnicoContract` está no WS. O WS referencia a DLL. Certo?
Comment: Está assim: Um projeto class library(SuporteTecnicoContracts) que tem o TPDV. Uma interface que está no meu projeto principal, não no class library que tem a DLL do class library. E um svc
Answer: O seguinte. Eu estava com um svc dentro de meu projeto principal. Criei um novo projeto WCF Service Application à parte. Criei e ele criou um projeto a parte, ficando minha solution com 5 projetos. Dessa forma resolveu o problema de reconhecer o tipo citado acima. Esse problema resolveu. Só não entendi porque não reconheceu quando o svc estava no mesmo projeto.


comparing linear and bayesian model

Question: I have two  models that predict a continuous outcome using the same 4 predictor variables.
Currently I am using the RMSE to compare the models so I am comparing the predicted outcome vs. the actual outcome for both models.
Can you advise on this method of model comparison? Are there more popular methods besides RMSe to compare linear vs. bayesian models. I like RMSE because it is interpretable for a lay audience.
Thank you.
Answer: Of course (R)MSE is a good metric for evaluating predictive models. If you are interested in how the models would do predicting out-of-sample cases, then I would recommend K-fold cross-validation to estimate out-of-sample MSE.
If one model is a penalized regression model, then it wouldn't be surprising to see it have higher MSE when predicting in-sample and lower MSE out-of-sample than the non-penalized model due to the non-penalized model over-fitting the data.

comparing linear and bayesian model


VSCode different permissions when opened with CLI versus shortcut (macOS Catalina)

Question: I am using the OmniSharp/Microsoft C# extension with VSCode. When I open my project using the code . command inside my project folder, the extension is able to find the dotnet SDKs just fine and everything is good.
When I open VSCode using the shortcut icon, I get this error output from OmniSharp:
Starting OmniSharp server at 1/13/2020, 8:00:34 PM
    Target: /Users/finley/dev/courses/dotnet/DatingApp

OmniSharp server started.
    Path: /Users/finley/.vscode/extensions/ms-vscode.csharp-1.21.9/.omnisharp/1.34.9/run
    PID: 16347

[info]: OmniSharp.Stdio.Host
        Starting OmniSharp on MacOS 10.15.2 (x64)
[info]: OmniSharp.Services.DotNetCliService
        DotNetPath set to dotnet
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Located 1 MSBuild instance(s)
            1: StandAlone 16.3 - "/Users/finley/.vscode/extensions/ms-vscode.csharp-1.21.9/.omnisharp/1.34.9/omnisharp/.msbuild/Current/Bin"
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        MSBUILD_EXE_PATH environment variable set to '/Users/finley/.vscode/extensions/ms-vscode.csharp-1.21.9/.omnisharp/1.34.9/omnisharp/.msbuild/Current/Bin/MSBuild.dll'
[info]: OmniSharp.MSBuild.Discovery.MSBuildLocator
        Registered MSBuild instance: StandAlone 16.3 - "/Users/finley/.vscode/extensions/ms-vscode.csharp-1.21.9/.omnisharp/1.34.9/omnisharp/.msbuild/Current/Bin"
            CscToolExe = csc.exe
            MSBuildToolsPath = /Users/finley/.vscode/extensions/ms-vscode.csharp-1.21.9/.omnisharp/1.34.9/omnisharp/.msbuild/Current/Bin
            CscToolPath = /Users/finley/.vscode/extensions/ms-vscode.csharp-1.21.9/.omnisharp/1.34.9/omnisharp/.msbuild/Current/Bin/Roslyn
            BypassFrameworkInstallChecks = true
            MSBuildExtensionsPath = /Users/finley/.vscode/extensions/ms-vscode.csharp-1.21.9/.omnisharp/1.34.9/omnisharp/.msbuild
[info]: OmniSharp.Cake.CakeProjectSystem
        Detecting Cake files in '/Users/finley/dev/courses/dotnet/DatingApp'.
[info]: OmniSharp.Cake.CakeProjectSystem
        Could not find any Cake files
[info]: OmniSharp.MSBuild.ProjectSystem
        No solution files found in '/Users/finley/dev/courses/dotnet/DatingApp'
[info]: OmniSharp.MSBuild.ProjectManager
        Queue project update for '/Users/finley/dev/courses/dotnet/DatingApp/DatingApp.API/DatingApp.API.csproj'
[info]: OmniSharp.Script.ScriptProjectSystem
        Detecting CSX files in '/Users/finley/dev/courses/dotnet/DatingApp'.
[info]: OmniSharp.Script.ScriptProjectSystem
        Could not find any CSX files
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.CSharpFormattingWorkspaceOptionsProvider, Order: 0
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.RenameWorkspaceOptionsProvider, Order: 100
[info]: OmniSharp.WorkspaceInitializer
        Invoking Workspace Options Provider: OmniSharp.Roslyn.CSharp.Services.EditorConfigWorkspaceOptionsProvider, Order: 200
[info]: OmniSharp.WorkspaceInitializer
        Configuration finished.
[info]: OmniSharp.Stdio.Host
        Omnisharp server running using Stdio at location '/Users/finley/dev/courses/dotnet/DatingApp' on host 16330.
[info]: OmniSharp.MSBuild.ProjectManager
        Loading project: /Users/finley/dev/courses/dotnet/DatingApp/DatingApp.API/DatingApp.API.csproj
  It was not possible to find any installed .NET Core SDKs
  Did you mean to run .NET Core SDK commands? Install a .NET Core SDK from:
      https://aka.ms/dotnet-download
[warn]: OmniSharp.MSBuild.ProjectManager
        Failed to load project file '/Users/finley/dev/courses/dotnet/DatingApp/DatingApp.API/DatingApp.API.csproj'.
/Users/finley/dev/courses/dotnet/DatingApp/DatingApp.API/DatingApp.API.csproj(1,1)
Microsoft.Build.Exceptions.InvalidProjectFileException: The SDK 'Microsoft.NET.Sdk.Web' specified could not be found.  /Users/finley/dev/courses/dotnet/DatingApp/DatingApp.API/DatingApp.API.csproj
  at Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject (System.String errorSubCategoryResourceName, Microsoft.Build.Shared.IElementLocation elementLocation, System.String resourceName, System.Object[] args) [0x00040] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Shared.ProjectErrorUtilities.VerifyThrowInvalidProject[T1] (System.Boolean condition, System.String errorSubCategoryResourceName, Microsoft.Build.Shared.IElementLocation elementLocation, System.String resourceName, T1 arg0) [0x00003] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject[T1] (Microsoft.Build.Shared.IElementLocation elementLocation, System.String resourceName, T1 arg0) [0x00000] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Evaluator`4[P,I,M,D].ExpandAndLoadImportsFromUnescapedImportExpressionConditioned (System.String directoryOfImportingFile, Microsoft.Build.Construction.ProjectImportElement importElement, System.Collections.Generic.List`1[Microsoft.Build.Construction.ProjectRootElement]& projects, Microsoft.Build.BackEnd.SdkResolution.SdkResult& sdkResult, System.Boolean throwOnFileNotExistsError) [0x00254] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Evaluator`4[P,I,M,D].ExpandAndLoadImports (System.String directoryOfImportingFile, Microsoft.Build.Construction.ProjectImportElement importElement, Microsoft.Build.BackEnd.SdkResolution.SdkResult& sdkResult) [0x00027] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Evaluator`4[P,I,M,D].EvaluateImportElement (System.String directoryOfImportingFile, Microsoft.Build.Construction.ProjectImportElement importElement) [0x0000d] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Evaluator`4[P,I,M,D].PerformDepthFirstPass (Microsoft.Build.Construction.ProjectRootElement currentProjectOrImport) [0x000e6] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Evaluator`4[P,I,M,D].Evaluate (Microsoft.Build.BackEnd.Logging.ILoggingService loggingService, Microsoft.Build.Framework.BuildEventContext buildEventContext) [0x0011c] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Evaluator`4[P,I,M,D].Evaluate (Microsoft.Build.Evaluation.IEvaluatorData`4[P,I,M,D] data, Microsoft.Build.Construction.ProjectRootElement root, Microsoft.Build.Evaluation.ProjectLoadSettings loadSettings, System.Int32 maxNodeCount, Microsoft.Build.Collections.PropertyDictionary`1[T] environmentProperties, Microsoft.Build.BackEnd.Logging.ILoggingService loggingService, Microsoft.Build.Evaluation.IItemFactory`2[S,T] itemFactory, Microsoft.Build.Evaluation.IToolsetProvider toolsetProvider, Microsoft.Build.Evaluation.ProjectRootElementCacheBase projectRootElementCache, Microsoft.Build.Framework.BuildEventContext buildEventContext, Microsoft.Build.BackEnd.SdkResolution.ISdkResolverService sdkResolverService, System.Int32 submissionId, Microsoft.Build.Evaluation.Context.EvaluationContext evaluationContext, System.Boolean interactive) [0x0002f] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Project.Reevaluate (Microsoft.Build.BackEnd.Logging.ILoggingService loggingServiceForEvaluation, Microsoft.Build.Evaluation.ProjectLoadSettings loadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext evaluationContext) [0x0005e] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Project.ReevaluateIfNecessary (Microsoft.Build.BackEnd.Logging.ILoggingService loggingServiceForEvaluation, Microsoft.Build.Evaluation.ProjectLoadSettings loadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext evaluationContext) [0x00035] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Project.ReevaluateIfNecessary (Microsoft.Build.BackEnd.Logging.ILoggingService loggingServiceForEvaluation, Microsoft.Build.Evaluation.Context.EvaluationContext evaluationContext) [0x00000] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Project.ReevaluateIfNecessary (Microsoft.Build.Evaluation.Context.EvaluationContext evaluationContext) [0x00007] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Project.Initialize (System.Collections.Generic.IDictionary`2[TKey,TValue] globalProperties, System.String toolsVersion, System.String subToolsetVersion, Microsoft.Build.Evaluation.ProjectLoadSettings loadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext evaluationContext) [0x00126] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Project..ctor (System.String projectFile, System.Collections.Generic.IDictionary`2[TKey,TValue] globalProperties, System.String toolsVersion, System.String subToolsetVersion, Microsoft.Build.Evaluation.ProjectCollection projectCollection, Microsoft.Build.Evaluation.ProjectLoadSettings loadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext evaluationContext) [0x00093] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Project..ctor (System.String projectFile, System.Collections.Generic.IDictionary`2[TKey,TValue] globalProperties, System.String toolsVersion, System.String subToolsetVersion, Microsoft.Build.Evaluation.ProjectCollection projectCollection, Microsoft.Build.Evaluation.ProjectLoadSettings loadSettings) [0x00000] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Project..ctor (System.String projectFile, System.Collections.Generic.IDictionary`2[TKey,TValue] globalProperties, System.String toolsVersion, Microsoft.Build.Evaluation.ProjectCollection projectCollection, Microsoft.Build.Evaluation.ProjectLoadSettings loadSettings) [0x00000] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.Project..ctor (System.String projectFile, System.Collections.Generic.IDictionary`2[TKey,TValue] globalProperties, System.String toolsVersion, Microsoft.Build.Evaluation.ProjectCollection projectCollection) [0x00000] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.ProjectCollection.LoadProject (System.String fileName, System.Collections.Generic.IDictionary`2[TKey,TValue] globalProperties, System.String toolsVersion) [0x000f7] in <10b73e4bf233421cae439ef765e97ef0>:0
  at Microsoft.Build.Evaluation.ProjectCollection.LoadProject (System.String fileName, System.String toolsVersion) [0x00000] in <10b73e4bf233421cae439ef765e97ef0>:0
  at OmniSharp.MSBuild.ProjectLoader.EvaluateProjectFileCore (System.String filePath) [0x0003f] in <21e2225264e848eb88f797c7e4a5cc78>:0
  at OmniSharp.MSBuild.ProjectLoader.BuildProject (System.String filePath) [0x0000d] in <21e2225264e848eb88f797c7e4a5cc78>:0
  at OmniSharp.MSBuild.ProjectFile.ProjectFileInfo.Load (System.String filePath, OmniSharp.MSBuild.ProjectIdInfo projectIdInfo, OmniSharp.MSBuild.ProjectLoader loader) [0x00015] in <21e2225264e848eb88f797c7e4a5cc78>:0
  at OmniSharp.MSBuild.ProjectManager+<>c__DisplayClass29_0.<LoadProject>b__0 () [0x00000] in <21e2225264e848eb88f797c7e4a5cc78>:0
  at (wrapper delegate-invoke) System.Func`1[System.ValueTuple`3[OmniSharp.MSBuild.ProjectFile.ProjectFileInfo,System.Collections.Immutable.ImmutableArray`1[OmniSharp.MSBuild.Logging.MSBuildDiagnostic],OmniSharp.MSBuild.Notification.ProjectLoadedEventArgs]].invoke_TResult()
  at OmniSharp.MSBuild.ProjectManager.LoadOrReloadProject (System.String projectFilePath, System.Func`1[TResult] loader) [0x0001b] in <21e2225264e848eb88f797c7e4a5cc78>:0

[fail]: OmniSharp.MSBuild.ProjectManager
        Attempted to update project that is not loaded: /Users/finley/dev/courses/dotnet/DatingApp/DatingApp.API/DatingApp.API.csproj

As you can see, it is unable to find my dotnet SDKs, indicating that VSCode was unable to run the dotnet --info command on behalf of the C# extension.
I'm sure the solution to this should be simple, but I am unable to figure it out! Any help would be greatly appreciated! I will provide any other debugging information necessary.
Answer: This appeared to be solved by simply restarting my computer. If you are running into this same issue, I would suggest giving it a try!


Prove that $f$ is a linear combination of $\delta^{(k)}$ for $k=0, 1\ldots, n-1$.

Question: Let $f$ is a tempered distribution such that $x^nf =0$ for an integer $n$. Prove that $f$ is a linear combination of $\delta^{(k)}$ for $k=0, 1\ldots, n-1$.
$\delta$ is Dirac delta function.
Please help me. I have no idea.
Comment: Does this answer your question? [A distribution as a linear combination of Dirac delta and its derivatives](https://math.stackexchange.com/questions/2793021/a-distribution-as-a-linear-combination-of-dirac-delta-and-its-derivatives) (I have found this reference almost at once using the formula searching tool https://approach0.xyz/)
Comment: The support of $f$ is the singleton $\{0\}$ and every distribution with this support is a linear combination of derivatives of the Dirac distribution. This is a standard result proved in every treatment of distribution theory, I would recommend Rudin's *Functional Analysis* or Hörmander's *The Analysis of Linear Partial Differential Operators I*.
Answer: Let $\phi \in \mathcal S(\mathbb R)$ and $P = \sum_{k=0}^{n-1} \frac{\phi^{(k)}(0)}{k!} x^k$ its Taylor polynomial with degree $k-1$ around $0$.
Then, there is a $\mathcal C^{+\infty}$ function $\psi$ such that [see here]:
$$\phi = P + x^n \psi$$
Let $\chi$ be a smooth compactly supported function that is $1$ on a neighborhood of $0$. Then, $\chi P$ and $\chi x^n \psi \in \mathcal S(\mathbb R)$.
Therefore :
\begin{align}
\langle f,\phi\rangle &= \langle f , \chi \phi\rangle \\
&= \langle f, \chi P\rangle +\langle x^n f, \psi\rangle \\
&= \langle f,\chi P\rangle
\end{align}
Therefore $\langle f,\phi\rangle$ only depends (linearly) on $\phi(0), \phi^{(1)}(0),\ldots, \phi^{(n-1)}(0)$, ie $f$ is a linear combination of $\delta_0,\delta^{(1)}_0,\ldots,\delta_0^{(n-1)}$


HDFS write resulting in " CreateSymbolicLink error (1314): A required privilege is not held by the client."

Question: Tried to execute sample map reduce program from Apache Hadoop. Got exception below when map reduce job was running. Tried hdfs dfs -chmod 777 / but that didn't fix the issue.
15/03/10 13:13:10 WARN mapreduce.JobSubmitter: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with
ToolRunner to remedy this.
15/03/10 13:13:10 WARN mapreduce.JobSubmitter: No job jar file set.  User classes may not be found. See Job or Job#setJar(String).
15/03/10 13:13:10 INFO input.FileInputFormat: Total input paths to process : 2
15/03/10 13:13:11 INFO mapreduce.JobSubmitter: number of splits:2
15/03/10 13:13:11 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1425973278169_0001
15/03/10 13:13:12 INFO mapred.YARNRunner: Job jar is not present. Not adding any jar to the list of resources.
15/03/10 13:13:12 INFO impl.YarnClientImpl: Submitted application application_1425973278169_0001
15/03/10 13:13:12 INFO mapreduce.Job: The url to track the job: http://B2ML10803:8088/proxy/application_1425973278169_0001/
15/03/10 13:13:12 INFO mapreduce.Job: Running job: job_1425973278169_0001
15/03/10 13:13:18 INFO mapreduce.Job: Job job_1425973278169_0001 running in uber mode : false
15/03/10 13:13:18 INFO mapreduce.Job:  map 0% reduce 0%
15/03/10 13:13:18 INFO mapreduce.Job: Job job_1425973278169_0001 failed with state FAILED due to: Application application_1425973278169_0001 failed 2 times due
to AM Container for appattempt_1425973278169_0001_000002 exited with  exitCode: 1
For more detailed output, check application tracking page:http://B2ML10803:8088/proxy/application_1425973278169_0001/Then, click on links to logs of each attemp
t.
Diagnostics: Exception from container-launch.
Container id: container_1425973278169_0001_02_000001
Exit code: 1
Exception message: CreateSymbolicLink error (1314): A required privilege is not held by the client.

Stack trace:
ExitCodeException exitCode=1: CreateSymbolicLink error (1314): A required privilege is not held by the client.

    at org.apache.hadoop.util.Shell.runCommand(Shell.java:538)
    at org.apache.hadoop.util.Shell.run(Shell.java:455)
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:715)
    at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:211)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:302)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:82)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Shell output:
1 file(s) moved.

Container exited with a non-zero exit code 1
Failing this attempt. Failing the application.
15/03/10 13:13:18 INFO mapreduce.Job: Counters: 0

Comment: Having the same problem under windows7, I dont think its hdfs problem, more looks like running it under windows causes issue. Made it work under mac os without troubles
Answer: Win 8.1 + hadoop 2.7.0 (build from sources)

run Command Prompt in admin mode
execute etc\hadoop\hadoop-env.cmd
run sbin\start-dfs.cmd
run sbin\start-yarn.cmd
now try to run your job
Comment: Win 10 + hadoop 2.7.3. It works for me. At least the job gets started. But I encounter `Error: java.lang.RuntimeException: Error in configuring object at org.apache.hadoop.xxx`
Comment: Should I run all jobs from under admin prompt?
Comment: Works also for Win 10 + hadoop 3.2.1.
Answer: I recently met exactly the same problem. I tried reformatting namenode but it doesn't work and I believe this cannot solve the problem permanently. With the reference from @aoetalks, I solved this problem on Windows Server 2012 R2 by looking into Local Group Policy.
In conclusion, try the following steps:

open Local Group Policy (press Win+R to open "Run..." - type gpedit.msc)
expand "Computer Configuration" - "Windows Settings" - "Security Settings" - "Local Policies" - "User Rights Assignment"
find "Create symbolic links" on the right, and see whether your user is included. If not, add your user into it.
this will come in effect after logging in next time, so log out and log in.

If this still doesn't work, perhaps it's because you are using a Administrator account. In this case you'll have to disable User Account Control: Run all administrators in Admin Approval Mode in the same directory (i.e. User Rights Assignment in Group Policy) Then restart the computer to make it take effect.
Reference: https://superuser.com/questions/104845/permission-to-make-symbolic-links-in-windows-7
Answer: I encountered the same problem as you. We solved the problem by checking the java environment.

check java version and javac version.
ensure that every computer in the clusters has the same java environment.
Answer: I don't know the cause of error, but reformating NameNode helps me to solve it in Windows 8.

Delete all old logs. Clean folders C:\hadoop\logs and C:\hadoop\logs\userlogs
Clean folders C:\hadoop\data\dfs\datanode and C:\hadoop\data\dfs\namenode. Reformat NameNode with calling command in administrator mode: c:\hadoop\bin>hdfs namenode -format
Answer: See this for a solution and this for an explanation. Basically, symbolic links can be a security risk and the design of UAC prevents users (even users who are part of the Administrators group) from creating symlinks unless they are running in elevated mode.
Long story short, try reformatting your name node and starting Hadoop and all Hadoop jobs from an elevated command prompt.
Answer: In Windows, change the configuration in hdfs-site.xml as
<configuration>
   <property>
       <name>dfs.replication</name>
       <value>1</value>
   </property>
   <property>
       <name>dfs.namenode.name.dir</name>
       <value>file:///C:/hadoop-2.7.2/data/namenode</value>
   </property>
   <property>
       <name>dfs.datanode.data.dir</name>
       <value>file:///C:/hadoop-2.7.2/data/datanode</value>
   </property>
</configuration>

open cmd in admin mode and run the command:-

stop-all.cmd
hdfs namenode –format
start-all.cmd

and then run the final jar in admin mode
hadoop jar C:\Hadoop_Demo\wordCount\target\wordCount-0.0.1-SNAPSHOT.jar file:///C:/Hadoop/input.txt file:///C:/Hadoop/output
Answer: I solved the same problem. Let's "Run as administrator" when you run "Command Prompt".


Unable to start rabbitmq

Question: I am unable to start rabbitmq on Debian 6
it just wont show any error. but wont start..I found the log files.
<code>...

starting database                                                     ...BOOT ERROR: FAILED
Reason: {error,{future_upgrades_found,[exchange_event_serial,
                                       semi_durable_route,trace_exchanges]}}
Stacktrace: [{rabbit_upgrade,'-maybe_upgrade/0-fun-0-',2},
             {rabbit_upgrade,with_upgrade_graph,1},
             {rabbit_mnesia,init_db,2},
             {rabbit_mnesia,init,0},
             {rabbit,'-run_boot_step/1-lc$^1/1-1-',1},
             {rabbit,run_boot_step,1},
             {rabbit,'-start/2-lc$^0/1-0-',1},
             {rabbit,start,2}]
{"Kernel pid terminated",application_controller,"{application_start_failure,rabbit,{bad_return,{{rabbit,start,[normal,[]]},{'EXIT',{rabbit,failure_during_boot}}}}}"}
</code>
Answer: Your error message is right there in what you pasted: "error,{future_upgrades_found".
Typically this is because you upgraded the version of RabbitMQ on your system and then (a) subsequently downgraded but didn't blow away the database, or (b) tried to run an older version of RabbitMQ against the upgraded database.
Re-Create your database (or upgrade to the appropraite version of RabbitMQ that the DB was created with) and the problem will go away.

Unable to start rabbitmq


Prime Factorization: a different approach

Question: I was wondering if any of you experts out there would consider the following to be of any merit.
Given a composite integer, the product of two unique primes (p=nq), an isosceles trapezoid can be constructed where the Area of trapezoid is given as p, the larger base as (p+1)/2, the smaller base as (p-1)/2, with a height of 2. For example, for the trivial composite, p=33, larger base = 17, smaller base=16, height = 2, area = 33.
Such a trapezoid can be manipulated, reducing the size of the two bases while at the same time increasing the height, keeping all angles the same, resulting in a trapezoid with same area, p.
My conjecture (if indeed, it qualifies as a conjecture): There exists only one transformed trapezoid of the same area, p,  where the values of the (reduced) bases are both of integer values, and that these values point to the factorization of p, in that base 1 + base 2 = one prime factor (p), and base 1 - base 2 = the other prime factor (q).
In the example of p=33 above, these reduced bases are 7 and 4, respectively, indicating the prime factors of 33 are 11 and 3.
I guess my question is, should I continue to pursue this line of inquiry, or am I simply stating some identity property? I realize this is basically a difference of squares approach. It's just that I haven't run across any other "geometric" approach to factoring in my research.
FYI, I have played with this conjecture using geogebra© software, constructing and manipulating various "composite" area trapezoids, finding no examples contradicting the conjecture. The limitations of the mentioned software regarding number size, as well as my computer's clock speed have proven the only obstacles to using this method in factoring large composites.
Thanks in advance for your thoughtful replies.
Comment: You're right that it's a difference of squares method; in this case the "square" is a triangle, with your trapezoid figure as the difference of two similar triangles, which of course have the area scaling as the square of the dimensions. Nevertheless interesting.
Answer: If we follow your description and let $a$ denote the longest base and $b$ the shortest base and use $h$ to denote the height, then we have:
$$
h\cdot{a+b \over 2}=n
$$
where
$$
b=a-{h \over 2}
$$
Thus clearly $h\in 2\mathbb N$ for both $a,b$ to be integers. Combining those equations and solving for $a$ we get
$$
a={n\over h}+{h\over4}
$$
from which it follows that
$$
b={n\over h}-{h\over4}
$$
Now since $h/4$ is contained in $\mathbb N/2$ we see that $a,b$ can only be integers if $n/h$ is also contained in $\mathbb N/2$. Hence $h$ divides $2n$. Thus if $n=pq$ we must have $h\in\{2,2p,2q,2n\}$. If $h=2$ we get
$$
a=\frac{n+1}{2},b=\frac{n-1}2
$$
If $h=2q$ we get
$$
a=\frac{p+q}2,b=\frac{p-q}2
$$
and if $h=2p$ then $p,q$ change roles above. But $b$ will only be positive if $h$ equals twice the smallest prime factor of $n$. Similarly $h=2n$ renders $b$ negative. This proves your conjecture to be correct.
Comment: Thanks for your work on this. I suspected I was correct, but was unable to prove it. Your work seems to do so. That being said, it seems likely that research with this methodology might prove useful as a tool for factoring composites. Eg: my current method for manipulating the trapezoids is to decrement the larger base by 1s, knowing the base must be an integer, and examining the smaller base for integerness. A more efficient method, it seems, would be to increment the height of the trapezoid by 2s, since the height must be twice the smallest prime factor, then testing for integerness.
Comment: Noted error in my last sentence (if anyone reads that far). s/b ... the height must be twice the difference between the two prime factors... -my bad.


Typescript async generator, for socket

Question: I am trying to understand TS async generators.
In Node.js, I open a socket, read all data from it, then close it.
I am attempting to make this into an async generator over the chunks of data.
async function* connectAndRead() {
    const socket = net.connect(80, 'localhost');
    socket.on('data', data => ???);
    socket.on('end', socket.close());
}

It is possible to make an async generator for data read from a socket?
Answer: It's possible, something like this should work until Node.js streams implement the async iteration protocol themselves:
import net from "net";

async function* socketIterator(
    host: string, port: number, initialSend?: Buffer | string,
): AsyncIterableIterator<Buffer> {
    let ended: boolean = false;
    let error: Error | undefined;
    let wake: () => void;

    const socket = net.connect(port, host)
        .on("readable", () => { wake(); })
        .on("end", () => { ended = true; wake(); })
        .on("error", (err) => { error = err; wake(); });

    if (initialSend) {
        socket.write(initialSend);
    }

    try {
        for (;;) {
            // wait for next event on socket
            await new Promise<void>((res) => wake = res);
            // yield all data available on socket
            for (let chunk = socket.read(); chunk; chunk = socket.read()) {
                yield chunk;
            }
            if (error) { throw error; }
            if (ended) { break; }
        }
    }
    finally {
        socket.end();
    }
}

async function main(): Promise<void> {
    const iter = socketIterator("httpbin.org", 80, "GET / HTTP/1.0\r\n\r\n");
    for await (const chunk of iter) {
        console.log(chunk.toString());
    }
}

main().catch(console.error);

Comment: Good idea, but doesn't work when events are sent extremely fast. A second event can be received while the socket is finishing reading or the wake promise is being rebuilt.

Typescript async generator, for socket


Jquery Validation & number field with comma

Question: In my form i have this element :
   $form['poidsMin'] = array(
        '#type' => 'number',
        '#title' => $this->t('Poids minimum en gramme'),
        '#default_value' => $frais_port_entity->get('poidsMin'),
        '#description' => $this->t("Poids minimum du produit"),
        '#required' => TRUE,
    );

When i put 10 or 20, all is good but if i put 10.3 or 10,3 drupal 8 jquery validate tell me to insert a value like 10 or 11 with no comma.
My field in mysql is a float, how can i disable this validation for number type field ?
Answer: Browser support may vary, but essentially you want to add an attribute of step="any":
$form['poidsMin'] = array(
    '#type' => 'number',
    '#title' => $this->t('Poids minimum en gramme'),
    '#default_value' => $frais_port_entity->get('poidsMin'),
    '#description' => $this->t("Poids minimum du produit"),
    '#required' => TRUE,
    '#attributes' => ['step' => 'any'],
);

Comment: Browser support for decimal separator in number field is horrible. It really works only for integer. For float use text field and validate yourself.
Comment: Or use `pattern="\d+(\.\d*)?"` or something similar @4k4
Comment: In UK that may work, but most of Europe uses a comma. All versions of IE and Edge can't handle this. Chrome and Firefox are almost there. IOS works perfect.
Comment: That's fine @4k4, the regex was just an example, it can be extended to support regional differences. Not sure where those browser stats have come from, IE10 & 11 support it, as does every other browser barring Opera Mini: http://caniuse.com/#feat=input-pattern. Safari (including iOS Safari) is actually one of the ones with only partial support
Comment: @Clive, I meant support for number fields. Pattern does not help much here. You want to use pattern with a text field?
Comment: Ah ok, yeah that's not so great @4k4. I would say using pattern on a textfield is slightly less evil than making do with a polyfill, yes. But only very slightly, and of course you do lose the step functionality. There's no good answer really


Alterar URL de acesso ao Admin

Question: Galera, é o seguinte: crio diversos sites e sistemas, e a maioria deles existe a área administrativa. Eu faço até então no básico de ser "urldosite.com.br/admin".
Agora, por questão de segurança também, quero começar trocar esses acessos. Exemplo, ao invés de ser "admin" ser "admin0978", mas ai em cada sistema os números serão diferentes.
Como faço isso no CakePHP 3? Como alterar URL de acesso ao Admin no Cakephp 3? Só conseguir até agora precisando alterar todos namespace dos controllers do admin.
Comment: Não precisaria modificar os nomes dos controladores e namespaces.. Basta configurar rotas: http://book.cakephp.org/3.0/en/development/routing.html
Comment: Daniel, vc pode me dá uma luz de como fazer? Obrigado!
Answer: No seu arquivo Project/config/routes.php
<code>...
Router::scope('/', function ($routes) {
    ...
    $routes->connect('/admin0978', ['plugin' => null, 'controller' => 'admin', 'action' => 'index']);
    ...
});
...
</code>
Comment: Eu uso no routes.php assim:

`
Router::prefix('admin', function (RouteBuilder $routes) {
    $routes->connect('/', ['controller' => 'usuarios', 'action' => 'login']);
    $routes->connect('/logout', ['controller' => 'usuarios', 'action' => 'logout']);
}
`

Então esse seu jeito não acredito que irá funcionar.
Comment: Mude o prefix então amigo. Mude para ```Router::prefix('admin0987' ....```. Funciona sim, o cake tem várias formas de fazer isso.
Comment: Mas se eu alterar do jeito que você falou, o cake começa pedi que eu crie a pasta Admin0987 dentro da pasta Controller.

`Error: Create the class UsuariosController below in file: src\Controller\Admin0987\UsuariosController.php`

Alterar URL de acesso ao Admin


Rails: Uninitialized constant - can not access to another class from controller

Question: search_handlers_controller.rb
class SearchHandlersController < ApplicationController
  def match
    @string = 'string'
    @result = case params['search_style']
    when 'match'
      MatchService.call(@string)
      ...

MatchService.rb in /services:
# frozen_string_literal: true
class MatchService < ApplicationService
  ...
  def call(string)
    'Match'
  end
end

Error when calling MatchService from SearchHandlersController#match:
NameError (uninitialized constant SearchHandlersController::MatchService):
app/controllers/search_handlers_controller.rb:18:in `match'

Comment: you named the file is `MatchService.rb`, didn't you?
Comment: Did you tried restarting your server??? whenever the service service file created you have to restart the server.
Answer: First of all, if you named the file MatchService.rb, you should change name of this file into match_service.rb.
If this isn't work in your case, you can always call the service from the root by add :: before the service name like that: ::MatchService.call(@string).
I hope it helps you!


conditional expectation function and residuals

Question: Im struggling to understand the relationsship of the conditional expectation function and the residuals. Im readings mostly harmless econometrics, and in theorem 3.1.1 (i) they prove that E (e I X) is 0, see here: http://econ.lse.ac.uk/staff/spischke/mhe/ex_ch3.pdf
However, later in the book they claim this is only true when the CEF is linear, but not in the more general case. The proof they give, however, seems to pertain to all CEF. Can somebody help me?
Comment: Could you also link to the chapter later in the book in which they make the claim?
Comment: im struggling to find it on the internet, ill just copy the original text later if you care to take a look again then :)
Comment: So, they first state that E(ß^) = ß + E((XX')Xe). Then they go on to write the following: "If the regressors are nonrandom (fixed in repeated samples) the expectation passes through and we have unbiasedness because E(e) = 0. Otherwise, with random regressors, we can iterate expectation and get unbiasedness if E(e I X) = 0. This is true when the CEF is linear, but not in our more general "agnostic regression" framework.

I hope this makes it clearer, thanks for having a look at it :)
Answer: It would be good to acquire the habit of reserving the word "residuals" for the estimated magnitude  of the "error" from, say, a regression.
Now, when in the relation
$$y = m(x) + e$$
we define $m(x)\equiv E(y \mid x)$, then $e$ is the Conditional Expectation Funtion error, which has nothing to do with the usuall "error term" we are talking about in a standard "classical" regression setting. The CEF error is actually and exactly "what is left" after we subtract from $y$ its conditional expectation with respect to $x$.
Then, by construction
$$y = E(y\mid x) + e \implies E(y\mid x) = E[E(y\mid x) \mid x] + E(e\mid x)$$
But by basic properties of the Conditional expectation, $E[E(y\mid x) \mid x] = E(y\mid x)$$ and so we obtain
$$E(y\mid x) = E(y\mid x) + E(e\mid x) \implies E(e\mid x) = 0$$
Always. No matter what functional form does $m(x)$, linear or non-linear.
Reading the OP's comment, what I suspect the authors of the book say "later on" essentially confounds the classical linear regression set up with the Conditional Expectation Function set up, as well as the error term in the classical linear regression model, with the CEF error.