What DNSSec implementations are available, and have they been checked for padding Cryptographic Oracle vulnerabilities?

Question: A cryptographic Oracle is where one can deduce the private key when a error condition is created.
Considering the recent ASP.NET padding Oracle exploit, can anyone tell me if the DNSSec implementations have been protected from similar "Cryptographic Oracle" attacks?
Answer: Is this attack even relevant against DNSSEC?
An oracle in cryptography is a system that gives you hints as you ask questions. This works interactively to reveal the private key in the ASP.NET case. This asking and answering/hinting is done while the private key is online (which is necessary for SSL/TLS to work), so little by little the key is "exposed" as new questions/connections come to it.
DNSSEC was designed to work so that the private key could be kept completely offline (like it is for the root (".") servers), and all data is signed once and can be left alone. The ISC BIND DNS server (for example) uses flat text files to store its zone data, and all records (normal DNS records and the RRSIGs) are simply sent from this/these file/s.
There is no way for an attacker to send the BIND server queries that would make it query the private key for an answer (best practices state that the private key shouldn't even be stored on publicly accessible DNS servers). Every response to a DNS query is taken from static data, and so there is no oracle in the chain to get answers from and/or attack.
Comment: Thank you for explaining this!  I was unaware the private key was offline.


Stochastic orders of summands when sum has fixed distribution

Question: Suppose $X,X',Y,Y'$ are independent random variables. We know that $X+Y \overset{d}{=} X'+Y'\overset{d}=Uniform[0,1]$ and $X\prec X'$ in the sense that $P(X> x)\le P(X'>x)$ for any $x\in \mathbb{R}$. Is it true that $Y'\prec Y$?
Answer: This is an answer to the earlier version of the question where $X+Y$ was not required to have uniform distribution.  This is false. If this implication is true then the following must also be true: $X,X',Y,Y'$ independent, $X+Y \overset {d} =X'+Y'$ and $X\overset {d}=X'$ implies $Y\overset {d}=Y'$. It is well known that there exist characteristic functions $\phi, \phi_1,\phi_2$ such that $\phi (t) \phi_1(t)=\phi (t) \phi_2(t)$ for all $t$ but $\phi_1 \neq \phi_2$. Such an example is available in Volume 2 of Feller's book. [ See Curiosities ii) in Section 2 of the chapter on Characteristic Functions]. Now just consider independent random variables $X,X',Y,Y'$ such that $X$ and $X'$ have characteristic function $\phi $, $Y$ has characteristic function $\phi_1$ and $Y'$ has characteristic function $\phi_2$ to get a contradiction.
Comment: Thanks. The equality $\phi(t)\phi_1(t)=\phi(t)\phi_2(t)$ means that $\phi(t)$ must be zero somewhere. If we know in addition that $X+Y\overset{d}{=}$ Uniform[0,1], would there be a counterexample?


Drupal way of sending push notification to android devices

Question: I am trying to send push notifications to Android, and Apple iOS devices. To store the device tokens, I am using cocoa rest client. For iOS devices that is fine, but I didn't understand how to store RegId and token for the Android devices. as we have only 4 attributes, namely:

token
uid
type
timestamp

Generally, for Android we have to store RegId and device token, but in the table we don't have any attribute to store Regid. I am giving post values as type=android,token=device token.
Will this help me to send push messages to Android devices? Without RegId, I think it is not possible.
I am using the Push Notifications module.
Comment: The question should mention which module/library (if any) is used for iOS/Android push notification as it seems actually related to such module/librairy. Also, the question seems to be about the basic usage of the used module/library, and would probably be better handled in the module/library issues queue/tracker.
Answer: Try the Push Notifications module. I've never done this -- but you're basically asking how do I send X message type to a user (SMS, Email, whatever). I've sent emails and SMS messages before ...
Beyond wanting to send this notification from within drupal/php ... there isn't anything really drupal specific in your question in terms of the drupal API.
If you dont userstand the protocol or APIs you want to talk to I would suggest you research them more as well. I would start by looking at the source code for the PushNotifications module and see how it handles the logic of what you are asking about ...
Comment: I am sorry for not mentioning this, i am using push notification module. with the help of this module i successfully sent notifications to ios devices. but i dint understand how for android.


How to prove that a parametrized linear differential equation solution induces a lipschitz function with respect to the parameter?

Question: Let's consider the following linear differential equation:
$X'_{\lambda}(t) = A_{\lambda}(t) X_{\lambda}(t)$ where: $X_{\lambda}(t) = \begin{pmatrix} x_{\lambda}(t) \\ x'_{\lambda}(t) \end{pmatrix}$ and $A_{\lambda}(t) = \begin{bmatrix} 0 & 1 \\ p(t) - \lambda & 0 \end{bmatrix}$ where $p$ is a continuous real function and $\lambda \in \mathbb{R}$ and $X_{\lambda}(0) = \begin{pmatrix} 0 \\ 1 \end{pmatrix}$.
$\newcommand{\norm}[1]{\lVert #1 \rVert}$
$\newcommand{\abs}[1]{\lvert #1 \rvert}$
Let us assume $\norm{\cdot}$ is the usual norm over vectors and for matrices:
For all matrix $A$ of size $n \times p$ : $\norm{A} = \max\limits_{i \in [[1, n]]} \sum\limits_{j=1}^p \abs{a_{ij}}$.
Let be $R > 0$.
Also, let us define $c = \sup \{ \norm{A_{\lambda}(t)} \mid (t, \lambda) \in [-R, R]^2 \}$.
I am trying to show that: $\norm{X_{\lambda}(t) - X_{\mu}(t)} \leq Re^{2cR} \abs{\lambda - \mu}$ for all $(\lambda, \mu, t) \in [-R, R]^3$.
What I have already done:

For all $t \in [-R, R], \norm{X_\lambda}(t) \leq e^{c\abs{t}}$.
For all $(s, t, \lambda) \in [-R, R]^3, \norm{X_{\lambda}(t) - X_{\lambda}(s)} \leq ce^{cR} \abs{t - s} (*)$.

What I have tried:

Creating a new differential equation which is verified by $X_{\lambda}$ and $X_{\mu}$, but I could not find one.
Using $(*)$ and $X_{\lambda}(0) = X_{\mu}(0)$, but I cannot get $\abs{\lambda - \mu}$ this way in my inequality…
Comment: A hint:  try finding an *integral* inequality satisfied by $\lVert X_\lambda(t)-X_\mu(t)\rVert$ and applying [Grönwall's inequality](https://en.wikipedia.org/wiki/Gr%C3%B6nwall%27s_inequality).
Comment: @user539887 Thank you, it did the job. Do you want me to post the details as the answer, or would you do it?
Comment: Yes, please do it
Answer: Let us denote $M = \begin{bmatrix} 0 & 0 \\ 1 & 0 \end{bmatrix}$.
Let's fix $(\lambda, t, \mu) \in [-R, R]^3$.
We have, by the fundamental theorem of analysis, because $X_{\lambda}$ and $X_{\mu}$ are twice continuously differentiable.$\newcommand{\norm}[1]{\lVert #1 \rVert}\newcommand{\abs}[1]{\lvert #1 \rvert}$
$\begin{align*}
X_{\lambda}(t) - X_{\mu}(t) & = X_{\lambda}(t) - X_{\lambda}(0) - (X_{\mu}(t) - X_{\mu}(0)) \\
& = \int_0^t X'_{\lambda}(s) - X'_{\mu}(s) \textrm{d}s \\
& = \int_0^t A_{\lambda}(s) X_{\lambda}(s) - A_{\mu}(s) X_{\mu}(s) \textrm{d}s \\
& = \int_0^t A_{\lambda}(s)(X_{\lambda}(s) - X_{\mu}(s)) \textrm{d}s + (\lambda - \mu)M\int_0^t X_{\mu}(s) \textrm{d}s
\end{align*}$
By taking norms:
$\begin{align*}
\norm{X_{\lambda}(t) - X_{\mu}(t)} \leq c \int_0^t \norm{X_{\lambda}(s) - X_{\mu}(s)} \textrm{d}s + \abs{\lambda - \mu}R e^{cR}
\end{align*}$
By Gronwall's lemma:
$\begin{equation*}
\norm{X_{\lambda}(t) - X_{\mu}(t)} \leq Re^{cR}e^{cR} \abs{\lambda - \mu} = Re^{2cR} \abs{\lambda - \mu}
\end{equation*}$


Is there a way to disable fetching the entire value set for a column in Hibernate?

Question: In our "Process" table there is a "Type" column. This column's valueset is defined in an enum in our code. However there are obsolete rows in this table. Meaning that there are rows where "type" is a value that is not present in the code's enum. The problem is whenever we acces ANY (not the obsolete ones) of the rows in this table we get an error that there is an unkown value for that column. Is there a way to disable this feature in hibernate as we do not want to delete these rows.
<code>@EqualsAndHashCode(callSuper = true, of = {})
@Table(name = ProcessEntity.TABLE_NAME)
public class ProcessEntity extends BaseEntity implements ValidityHolder {
public static final String TABLE_NAME = "PROCESS";

@OneToMany(mappedBy = "consent", cascade = CascadeType.ALL)
private Set<ConsentAnswerEntity> consentAnswers;

@OneToMany(mappedBy = "consent", cascade = CascadeType.ALL)
private List<ProcessConsentEntity> processConsents;

@OneToMany(mappedBy = "consent", cascade = CascadeType.ALL)
private Set<ProcessTypeConsentEntity> processTypeConsents;

@Enumerated(EnumType.STRING)
@Column(name = "TYPE_ID")
private Type TpyeId;
</code>
Comment: How is the column annotated and how exactly is the column set up in the table?
Comment: @Enumerated(EnumType.STRING)
    @Column(name = "TYPE_ID")
    private Type type;

This is how it is declared in our "Process" table
Comment: That is only the entity, not the actual table
Comment: I updated the post.
Comment: Still missing the table
Answer: If these "obsolete" records no longer fit into your Hibernate data model, then I recommend just moving them to some archive table.  After all, you can't really select them now anyway using Hibernate, so at least at the application level, they serve no purpose.
For a more general way to logically delete a record without physically removing it, look into soft deletion.  Using soft deletion, you would add a single boolean column to the table which, if marked, would indicate that the record is logically no longer there.


Rationale behind Q-learning

Question: I am reading Sutton Barto on Reinforcement Learning. I understand that $TD(\lambda)$ methods propose better performance than Monte Carlo methods, with TD methods combining advantages of Dynamic Programming and Monte Carlo approaches.
The transition to Q-methods : SARSA, Q-Learning, Expected SARSA is unclear to me. Which gaps is filled by Q-methods, what is the rational behind their use rather than TD methods ?
Answer:
The transition to Q-methods : SARSA, Q-Learning, Expected SARSA is unclear to me. Which gaps is filled by Q-methods, what is the rational behind their use rather than TD methods ?

There isn't really such a thing as "Q methods" in the sense that you are using it. All of SARSA, Q-learning and Expected SARSA are TD methods. Specifically they are using TD approach in the context of action values, which is necessary for value based model-free control problems, because if you just used state values $V(s)$ then you have no way to generate your best guess at the optimal policy. Using $Q(s,a)$ immediately gives you $\pi(s) = \text{max}_a Q(s,a)$.
Model-free Monte Carlo control likewise must use estimates of $Q(s,a)$ which is why there is not really a clear class of methods called "Q methods", although it is a matter of convention what all these things are called and they are all inter-related in any case.

Rationale behind Q-learning


Interpretation of SVM accuracy

Question: I use "LIBSVM" library for classification.
If my first class is the same as the second class, for accuracy I will get 50% or 0%.
What does it mean to get 30% or 20% of precision?
Comment: I still fail to understand the experiment you are doing. What do you mean by "the first class is the same as the second class"? If they are same, they should be in one class? From your comment to Harald's answer, ("I ask two subjects to the same movement"), I guess that you have 2 samples from one class. You should at least ask those 2 subjects to make a different movement, then you will have 4 samples from 2 classes. And I don't know what type of features you are using but a dataset of 2 samples is definitely very small.
Comment: it is our experience,  we want to see the resulat between 2 subjects make the same mouvement
Comment: So you are trying to identify people based on their movement patterns? If so, i guess you are right, your classes are the people. In this case, reporting the classification accuracy can make more sense though. Are you sure you need to measure the precision, but not the classification accuracy?
Comment: please can you see me what is the difference between, precision and classification accuracy
Comment: if the problem was image retrieval with classes car, human and boat, and the test image was infact a car image, then your precision would be (the number of car images you returned)/(number of car images in your database). there is also another measure called recall, both are explained [here](https://en.wikipedia.org/wiki/Precision_and_recall).
Comment: when i use !Libsvm, i obtain Accuracy = 50.7937% (64/126) (classification), What does it mean ?!it is a good classifier or it s just classifier by chance
Comment: it means it classified 64 of the 126 samples (again, what are they? and what do their labels mean?) correctly. If this is binary classification, then yes the accuracy is very close to random decision.
Answer: A SVM is a binary classifier. That means, you can distinguish only 2 classes.
If both classes are the same, classification doesn't make sense.
If you have more then 2 classes you need to use different classification methods, such as k-means or neural networks. However, multi-class classification with SVM can still be done by reducing the multi-class decision problem to multiple binary classifications.
Comment: my experience is, I take two set of data generated by two subject that do the same thing,  I get almost the Same data,
Comment: Can you explain your question a little more detailed?
Comment: I classify the movements, I ask two subjects to the same movement.
I get almost the same data, what does it mean to get 50%  of accuracy
Comment: Sorry, I can't help you if you explain yourself this scarce.
Comment: I  want just to understand the meaning of obtaining 50% of preccision with SVM
Comment: Generally, [precision](https://en.wikipedia.org/wiki/Accuracy_and_precision#In_binary_classification) is the ratio of true positives over all positives. Is this what you want to know?
Comment: if i have 2 classes that loke the same, i should obtain 50% or 0% of accuracy
Comment: Precision measures the quality of a classifier by comparing the predictions $Y$ with of the ground truth (i.e true Class $X$). Accuracy is a different metric for a classifier. However, both don't tell you anything about the class distribution, nor how similar the classes are.
Comment: I know but we can guess it, if you have two very different classes Normally the precission will be great.
Comment: Again, can you reformulate your question a little more detailed? What are you interested in?
Comment: my question is easy, how to interpret the precession of svm ?, if you have two classes that look like, the result of 50% is like classification by chance, is  it  right or not
Comment: No its not right. It depends on the class distribution in your data. If 80% of your data is Class $A$ and only 20% Class $B$, your precision is widely different to a distribution with 40% $A$ and 60%$B$. You can't compare data by accuracy or precision. Both values are used to compare classifiers.
Comment: I  take 50% for the first class and 50 % from the second, and i obtain 50% of accuracy
Comment: Accuracy then means that the classifier manages to correctly predict the Class in 50% of the samples **of this one dataset**. Generally precision is different from accuracy!

Interpretation of SVM accuracy


Access Drupal7 Database Nodes without actually having anything installed (simple php + mysql)

Question: The last days I got some trouble with the drupal database schema. I don't know anything about Drupal7 except that database entries are saved in several fields.
I need to read out all the different nodes and their attributes of a mysql server in Drupal Scheme (in the best case without actually using the Drupal environment) with a simple .php page. Is there any chance to do so?
Example: Car Entries - what I need are
field_data_field_speed
field_data_field_weight
and more.
Would be grateful for help!
UPDATE:
Database Drupal relationship between tables,  to get a node schema and node data.
Comment: Welcome to Drupal Answers :) What's your actual question here? It sounds like you're asking if you can export data from a MySQL database without Drupal getting involved, which of course you can do, no-one can stop you, but what you need to know about Drupal isn't clear. Are you hoping someone will write the queries for you? Give you an exhaustive outline of every table and field, and its relationships to other tables? If you could edit the question to clarify that would be great. Please do bear in mind if it's either of the latter, it's going to be much too broad for Q+A
Comment: If you could also confirm why you've tagged this with the "Views module" tag and "Entity Field Query" tags, that would be good. It's hard to imagine how either of those could be involved in what you're asking
Answer: If I'm not wrong you want a 'query' that connect a content type with all its fields.
Each field has it own table.
But you can connect the dots using a few queries ([content_type_name] could be article, car_entry or whatever the name of your content type is):
*Getting all the entries for a content type

SELECT * FROM node WHERE type = '[content_type_name]'
column id would be the [entity_id]

*Getting all fields from a content type

SELECT * FROM field_config_instance WHERE entity_type = 'node' AND bundle = '[content_type_name]'
this table contains column field_id [field_id] and column field_name [field_name]

Now that you have the fields:
*Get the field info using field_id and/or field_name

SELECT * FROM field_config WHERE id=[field_id] AND field_name='[field_name]'

*Get the field data by node

SELECT * FROM field_data_[field_name] WHERE entity_id = [entity_id]

Play around with those queries, so you get a better idea of the columns that each one of those tables contains. Then you can create mysql joins to create the queries that you need.


How to check if Azure IOT Hub sender has stopped using node.js and socket.io

Question: I have two programs, a sender and a receiver. The sender sends some message to device on IOT Hub and receiver in turn receives those messages as long as sender sends them. I am using socket.io to broadcast those messages to connected clients. However when the sender is stopped, the receiver also stops but the last message sent by sender is going to broadcasted infinitely until i close the receiver or the sender starts again and sends new messages. The last message will get duplicated and broadcasted infinitely. How to check if the sender program has stopped?
this is the sender prrogram:
var clientFromConnectionString = require('azure-iot-device-mqtt').clientFromConnectionString;
var Message = require('azure-iot-device').Message;
var connectionString = 'conn_string'
var client = clientFromConnectionString(connectionString);

var avgTemperature = 20;

var printResult = function (err, res) {
    if (err) {
        console.log('send error: ' + err.toString());
        return;
    }
    console.log('send status: ' + res.constructor.name);
};

setInterval(function () {
    var currentTemperature = avgTemperature + (Math.random() * 10) - 2;
    var data = JSON.stringify({
        deviceId: 'test',
        temperature: currentTemperature,
        latitude: 50.286264,
        longitude: 19.104079,
        time: Date.now()
    });
    var message = new Message(data);
    console.log("Sending message: " + message.getData());
    client.sendEvent(message, printResult);
}, 5000);

this is the receiver and the socket.io which broadcasts to the client:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var EventHubClient = require('azure-event-hubs').Client;
var connectionString = 'conn_string'

var printError = function (err) {
    console.log(err.message);
};

var result;

var printMessage = function (message) {
    console.log('Message received: ');
    result = JSON.stringify(message.body);
    console.log('message: ' + result);
    /* io.on('connection', function(socket){

     socket.on('chat message', function(msg){

     io.emit('chat message', result);
  });
}); */

        console.log('');
};

count =0;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log('user connected');
  socket.on('chat message', function(msg){

     io.emit('chat message', result);

  });
  socket.on('disconnect', function(){
    console.log('user disconnected');
      socket.removeAllListeners('disconnect');
      io.removeAllListeners('connection');
  });
});

var client = EventHubClient.fromConnectionString(connectionString);
client.open()
    .then(client.getPartitionIds.bind(client))
    .then(function (partitionIds) {
        return partitionIds.map(function (partitionId) {
            return client.createReceiver('$Default', partitionId, { 'startAfterTime' : Date.now()}).then(function(receiver) {
                console.log('Created partition receiver: ' + partitionId)
                receiver.on('errorReceived', printError);
                receiver.on('message', printMessage);
            });
        });
    })
    .catch(printError);

http.listen(3000, function(){
  console.log('listening on *:3000');
});

Comment: You can use `message.sequenceNumber` to check it is a new message or old one to prevent from the broadcasting duplicated.
Comment: sequence number is not a function of the message. tried it in both sender and receiver and when i print it, im getting undefined.
Comment: It is not a function but a property and access it like this: `message.sequenceNumber` just like you access `message.body`. Its definition is [here](https://github.com/Azure/azure-event-hubs-node/blob/master/send_receive/lib/eventdata.js).
Answer: According to your code. Whenever the sender stops sending, the receiver will not receive the messages and will wait for the sender to send new messages. However, if you still want to check, you can use sequence numbers with sender messages or associate Id with them to check duplicates.


Error after updating

Question: I recently updated to Drupal 8.2.0 from 8.0. Updating was successful, but the Status report page shows this error.

How can I solve it?
Answer: Execute drush entity-updates. As usual, test this on non-production system.

Error after updating


function firing multiple times when scrolling fast

Question: First of all, I'm not very advanced at code and tend to only do this part time so please excuse all terrible/ugly code! I appreciate there are already some solutions out there but I can't seem to make any of them work with my code so would really appreciate some help!
I'm using isotope grid and trying to setup an infinite scroll. I want to load 10 images at a time when the user scrolls to the bottom by taking these images from an array and appending them to a temp div.
This is working perfectly when scrolling slowly, but as soon as you scroll quickly the function seems to fire multiple times, it gets a little glitchy and loads lots of images at once.
$(window).scroll(function() {

var scrollTop = $(window).scrollTop();
var windowHeight = $(window).height();
var docuHeight = $(document).height();

if(scrollTop + windowHeight == docuHeight){

  nextTenImages = imagesData.splice(0,10);
  var content = ""
  for (var i = 0; i < nextTenImages.length; i++) {
      content +=
      "
" +
        "
" +
          "" +
        "
" +
      "
"
  };

  $('body').append('

');
  $('#temp-load > #grid').append(content)

  $('#temp-load > #grid').children().css({
      opacity: 0
  });

  var toAdd = $('#temp-load > #grid').html();

  $container.isotope('insert', $(toAdd), function(){
    $container.children().css({
      opacity: 1
    });
    $('#temp-load').remove();
  });

}

});

Comment: The concept is like asking for extra water to five waiter. Each will bring thinking they were the only one. What is required if you tell 1 waiter, then refrain from telling more till that waiter gets back to you. On a similar note, once your image loader function is triggered, wait for the image to be loaded and the document length to be updated before accepting new trigger.
Answer: Make a single timeout to run the callback. This may avoid the function from executing multiple times.
var timer;

function scrollEvt() {
    /* scroll actions */
}

$(window).scroll(function() {
    /* clear the old timeout */
    clearTimeout(timer);
    /* wait until 400 ms for callback */
    timer = setTimeout(scrollEvt, 400);
});

Using other ways may result in problems (like comparing (window.performance || Date).now())...
Comment: No, you have to debounce it, meaning you need to clear any prvious timeout, e.g using: `clearTimeout(timer);` before setting a new one
Comment: You are right just that sunday is my lazy day... ;)
Answer: Unbind that specific scroll event till your delayed operation is completed to prevent accumulating more of the event triggers which create the duplication behaviour as in your case.

var winCached = $(window),
  docCached = $(document)

var currLeng = 0;

function addContent() {
  dettachScrollEvent();
  setTimeout(function() { //this timeout simulates the delay from the ajax post
    for (var i = currLeng; i < currLeng + 100; i++)
      $('div').append(i + '
');
    currLeng = i;
    console.log("called loader!");
    attachScrollEvent();
  }, 500);

}

function infiNLoader() {
  if (winCached.scrollTop() + winCached.height() > docCached.height() - 300) {
    addContent();
    //alert("near bottom! Adding more dummy content for infinite scrolling");
  }
}

function attachScrollEvent() {

  winCached.scroll(infiNLoader);
}

function dettachScrollEvent() {
  winCached.unbind('scroll', infiNLoader);
}
addContent();


Javascript library for clickable bar chart?

Question: I need a Javascript charting tool to build a bar chart that allows me to click on a chart bar and get another chart (in a popup or below the first chart).
What I need is a bar chart that fires an event giving me some kind of id of the column that has been clicked.
Dettails
The data for the first chart should be loaded with ajax when the page loads and the data for the second chart should be loaded when you click on one of the columns.
an example:
A graph with one bar for March and one bar for April,
when you click on the March bar you get a second graph (below or in a pop up) with two bars: one for the 12/03/2011 and the other for the 23/03/2011.
Total expenses:
March 1200
April 300
Total expenses for March:
12/03/2011 1000
23/03/2011 200
Total expenses for April:
16/04/2011 10
21/04/2011 290
Answer: Yet another option, if you are already using jQuery: Flot.
Graph Types:

Interaction:

Click the images to see the actual demo.
Answer: Highcharts allows custom "click" handlers for individual points or entire series.
Comment: I hope Highcharts library is commercial. It is free for personal or non-profit projects.
Answer: D3.js is very impressive and renders beautiful charts. Check out their many nice examples on the website:

It is free and ships with a BSD license
Answer: Checkout http://www.jqplot.com/
It doesn't do all that you need out of the box, but if you extend the Cursor class I think you can get the functionality you've been looking for.
http://www.jqplot.com/docs/files/plugins/jqplot-cursor-js.html#$.jqplot.Cursor
Comment: jqplot has built-in click handling now: http://www.jqplot.com/deploy/dist/examples/barTest.html
Answer: See gRaphaël - scalable vector charts that work in Firefox, Safari, Chrome, Opera and even Internet Explorer 6+.
Comment: Thanks for sharing. The Raphaël looks pretty slick.
Answer: Flotr2 is a substantially enhanced fork of Flot.


Bootstrap Pills space at the top?

Question: I'm using Bootstrap Pills for a menu and there is a space at the top. I already have spacing removed for the
 but I don't know how to get rid of the space at the top of the very first
.
   .nav-pills > li > a
    {
        margin-top: -4px;
        margin-bottom: -1px;
    }

    .HomePageMenuContainer
    {
        background-color: #272b30;
        border-radius: 8px;
        border: 5px solid lightgray;
        padding: 1px;
    }

About Us

Collision Repair

Classic Restoration

Our Services

Testimonial

Our Shop

Contact Us

UPDATE: based on the answer below this is the CSS I to fix it.
Setting both margin and padding to "0" got rid of the space but also made it go above the border. I just added a little top padding to bring it down to where it needed to be.
ul.nav.nav-pills.nav-stacked {
  margin: 0 !important;
  padding-top: 3px !important;
}

Comment: check the `ul`.  It's probably a rogue margin or padding.
Answer: If you can't find a solution.
Try using this.
ul.nav.nav-pills.nav-stacked.voffset3 {
  margin: 0 !important;
  padding: 0 !important;
}

This will allow you to remove unnecessary spaces. I just use !important because I don't know the main path of the ul element.
Comment: Thanks...a couple minor tweaks to that got me fixed. I posted my fix in my question.
Answer:

<meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

           <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

About Us

Collision Repair

Classic Restoration

Our Services

Testimonial

Our Shop

Contact Us

As you can see from the above snippet there is no margin associated with it as mentioned in your question.
Comment: Do you have more css? Please post them to get a complete answer.

Bootstrap Pills space at the top?


DNS lookup on DNS server works, but wrong IP on clients

Question: I am trying to set up a DNS server to change a few domains in my local netwkork - first with bind9, then with dnsmasq. With both software, I resulted in the same problem: When executing nslookup / dig on the dns server itself, I am getting the correctly changed ip matches.
However, when doing a lookup on machines using the DNS server, it returns the wrong (original) host ip, instead of the modified one.
On the dns itself
nslookup mydomain.com
Server:     127.0.0.1
Address:    127.0.0.1#53

Name:   mydomain.com
Address: <correctly modified host ip>

On devices with flushed caches (mac / android):
nslookup mydomain.com
Server:     <dns server ip>
Address:    <dns server ip>#53

Non-authoritative answer:
Name:   mydomain.com
Address: <original host ip>

The question is, why is the entry on the server correct, but faulty on the clients?
Comment: What do you mean "correctly modified"? Are you referring to the NAT addresses?
Comment: I am overriding a few domain entries with different IP addresses. With 'correctly modified', I mean it is the new host IP instead of the original one. The main problem is, why is the entry on the server correct but faulty on the clients using the exact same server?
Comment: TTL? Is that server the only one they get answers from?
Comment: server-side caching of entries is disabled during setup, TTL 0. The DNS server is the only one set on the clients. As nslookup / dig confirms, the answer is coming from this server.
Comment: Check `lsof -i:53 -nP` and evaluate which programs are listening on which interfaces. It's possible that you have port contention.
Comment: Does flushing dns entries on client help ? In Windows clients I would use `ipconfig /flushdns` in command line. Let us know if that helped or if you have already tried that ?
Answer: It takes times to Propagate your modified dns entry to the Internet. New record will automatically replaced when your old record expires as defined in TTL. You have to wait time till TTL expires.
Answer: The problem was a very stupid and obvious one: My hoster had a UDP block on the machine active.
I assume Mac and Android use a fallback DNS server in case the one set is not reachable? That would explain the wrong (correct) results.
On a linux machine however, a nslookup / dig using the new DNS server resulted in a timeout.


Barra invertida em links antes do nome do arquivo

Question: Eu estava publicando uma resposta a uma pergunta de um usuário deste site quando reparei que no HTML havia tags de imagens com o src contendo uma barra invertida antes do nome do arquivo

Confesso que foi a primeira vez que vi algo desse tipo e não achei nenhuma publicação que me desse alguma explicação a respeito desse tipo de endereçamento no atributo src.
Isso é compatível? Alguma documentação a respeito?
Answer: Pelo que li na documentação do HTML Standard o atributo src do elemento  tem que ser uma "URL não-vazia potencialmente cercada de espaços válida" (valid non-empty URL potentially surrounded by spaces).

E o que é uma valid non-empty URL potentially surrounded by spaces?
É uma URL não vazia válida (valid non-empty URL) depois de os espaços em branco serem removidos. O que nos leva a próxima pergunta:

O que é uma valid non-empty URL ?
É uma string URL válida que não seja vazia. Então....

O que é uma string URL válida?
Agora juro que vou resumir porque tem um tanto de pormenores.
Ela pode ser relativa ou absoluta. E em ambos os casos e em todos cenários, a documentação que li cita sempre o carácter U+002F (/).
Então a conclusão é que pode funcionar provavelmente porque o navegador na hora de interpretar a URL faz a correção automaticamente, mas não é a especificação.
link para documentação
Comment: Sim eu vi e testei aqui no meu site e funcionou normalmente. Mas como escrevi não tem nada na documentação que fale sobre isso. Provavelmente é alguma correção que o próprio navegador faz na hora de interpretar a url.
Comment: @LeoCaracciolo as imagens deveriam aparecer neste seu exemplo? Aqui não apareceu, mas olhando o inspetor do Chrome, o navegador realmente troca `\` para `/` ao renderizar a imagem.
Comment: Isso tudo eu sei, eu até reproduzi a pagina do indagador e postei no meu servidor. Rodou redondo nos cinco principais navegadores. Veja no código fonte as barras invertidas antes do nome do arquivo nos src das imagens http://kithomepage.com/sos/marlonramos.htm @Fabri Damazio
Comment: A curiosidade é enorme em saber exatamente porque funciona. Acho que você tem razão em dizer que provavelmente é uma correção do navegador.
Comment: sim, como disse no meu primeiro comentário acima, rodou nos 5 navegadores. Fato esse corroborado  pelo amigo  Fabri Damazio no 1º comentário dele.  Anderson Carlos Woss, por curiosidade, qual versão que não funcionou?
Comment: @LeoCaracciolo Chrome, Version 57.0.2987.133 (64-bit) em Linux
Comment: Você me deu uma boa dica, inspetor, donde se conclui que Fabri Damazio tem razão em supor que seja correção do navegador. Se ele acrescentar isso na resposta, vou eleger como aceita.
Comment: Firefox 52.0.2 (64-bit) também não abriu as imagens. Opera 44.0.2510.1449 também não.
Comment: tonces, bom evitar né.
Comment: Aliás, acho que olhei o código fonte no lugar errado. No inspetor não houve a substituição e, pelo jeito, não carrega a imagem assim. Então é bom usar só `/` mesmo.
Comment: Ele substitui na hora de interpretar e não no código em si provavelmente. Na hora de fazer o parser
Comment: Sim, mas o inspetor mostra exatamente aquilo que o navegador está mostrando em tela. Se houvesse esta substitução, o link da imagem estaria corrigido no mesmo, mas continua com a barra invertida.
Comment: Façam o seguinte teste: abram este link da uma imagem na barra do navegador: https://fabridamazio.github.io/images/face.jpg
Troquem agora a ultima barra pela barra ao contrario e ele corrigirá automaticamente. Provavelmente faça a mesma coisa na hora de interpretar as urls.
Comment: Leo mas na hora de interpretar ele deve fazer a correção assim como acontece quando por exemplo esquecemos de fechar alguma tag e mesmo assim o codigo funciona porque o navegador acaba corrigindo e fechando a tag automaticamente


How do we configure Lustre to block client requests when under load, rather than failing?

Question: We are using Lustre in a cluster with approximately 200TB of storage, 12 Object Storage Targets (that connect to a DDN storage system using QDR Infiniband), and roughly 160 quad and 8-core compute notes. Most of the users of this system have no problems at all, but my tasks are I/O intensive. When I run an array job that has 250-500 processes that are simultaneously pounding the file system typically between 10 and 20 of my processes will fail. The log files indicate that the load on the OSTs are going over 2 and that the Lustre client is returning either bad data or failed read() function calls.
Currently the only way we have of resolving my problem is to run fewer simultaneous jobs.  This is unsatisfactory, because there is no way to know in advance if my workload will be CPU-heavy or I/O heavy.  Besides, just turning down the load isn't the way to run a supercomptuer: we would like it to run slower when running under load, not produce incorrect answers.
I'd like to know how to configure Lustre so that clients block when the load on the OSTs goes too high, rather than having the clients get bad data.
How do I configure Lustre to make the clients block?
Answer: Have you thought of adding more OSSs and spreading out the OSTs?  That should decrease the load.  In that vein, what kind of I/O pattern are you doing?  Do you have many large files, if so, are they striped?  Default striping is 1, which means each file resides on only 1 OST, that can be changed on a per file (at create) or on a per directory basis (for new files).
You could also try increasing the timeouts in lustre (lctl get_param/set_param) namely:

timeout
ldlm_timeout
Comment: I don't have the ability to add more OSSs, unfortunately. The I/O is that we have objects in the 20G to 100G range and each process reads the object from beginning to end. I don't think that striping would help. We really just need to make it block.
Comment: If you're just doing sequential I/O your just going to be limited by your backend storage.  Actually, if you do sequential I/O with a blocksize larger than the stripe size, you will see an improvement in performance, since multiple I/Os will be in-flight to the various OSTs.
Comment: Is that the user-specified I/O size or the system I/O size?


Why does drupal create revision table?

Question: From database design perspective, Why does Drupal even create these tables? They are so much alike. There are modules & methods for getting rid of these tables, But why are they there?
<code>MariaDB [park]> describe field_data_body;
+--------------+------------------+------+-----+---------+-------+
| Field        | Type             | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+-------+
| entity_type  | varchar(128)     | NO   | PRI |         |       |
| bundle       | varchar(128)     | NO   | MUL |         |       |
| deleted      | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id    | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id  | int(10) unsigned | YES  | MUL | NULL    |       |  ONLY DIFFERENT ONE
| language     | varchar(32)      | NO   | PRI |         |       |
| delta        | int(10) unsigned | NO   | PRI | NULL    |       |
| body_value   | longtext         | YES  |     | NULL    |       |
| body_summary | longtext         | YES  |     | NULL    |       |
| body_format  | varchar(255)     | YES  | MUL | NULL    |       |
+--------------+------------------+------+-----+---------+-------+
10 rows in set (0.00 sec)

MariaDB [park]> describe field_revision_body;
+--------------+------------------+------+-----+---------+-------+
| Field        | Type             | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+-------+
| entity_type  | varchar(128)     | NO   | PRI |         |       |
| bundle       | varchar(128)     | NO   | MUL |         |       |
| deleted      | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id    | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id  | int(10) unsigned | NO   | PRI | NULL    |       |  ONLY DIFFERENT ONE
| language     | varchar(32)      | NO   | PRI |         |       |
| delta        | int(10) unsigned | NO   | PRI | NULL    |       |
| body_value   | longtext         | YES  |     | NULL    |       |
| body_summary | longtext         | YES  |     | NULL    |       |
| body_format  | varchar(255)     | YES  | MUL | NULL    |       |
+--------------+------------------+------+-----+---------+-------+
10 rows in set (0.00 sec)

MariaDB [park]>
</code>
Comment: This is an ongoing issue. Read [Duplicate data in field_data* and field_revision* tables](http://drupal.org/node/1279440) and add your voice.
Answer: The revision table has been set up to track the revisions of a node.  Like Triskelion noted, there already is a thread up on D.O. Furthermore the reason the table is populated is for denormalization purposes, per The aforementioned issue.  Inevitably. this has some drawbacks.  The first of which is bloat.  Write speed is also affected, especially under a load.  The community has seemed to coalesce around using contrib to deal with this issue e.g. Field SQL norevisions.  At some point it would be nice to have this in core, but a rock solid contrib module is the next best thing.

Why does drupal create revision table?


( (Where and Where) OR (Where and Where) ) Laravel 5.2

Question: I am trying to create ( (Where and Where) OR (Where and Where) )  And after a lot of searching I found this
    $sender = \App\User::where('username','=',$username)->firstOrFail();
    $receiver = Auth::user();
    $messages = \App\Message::Where(function($query)
                              {
                                  $query->where("sender",$sender->id)
                                        ->where("receiver",$receiver->id);
                              })
                              ->orWhere(function($query)
                              {
                                  $query->Where("sender",$receiver->id)
                                        ->Where("receiver",$sender->id);
                              })
                              ->get();

But it's showing me that the $sender and the $receiver variables are undefined , Any help please , I'm trying to show the messages of the both users, I thought also that I can get the first (where and where) alone and then get the second one then I'll merge them.
Answer: To use $send and $receiver within a Closure do the following;
function ($query) use($sender, $receiver){

}

Allowing you to access the variables within the scope of that function.
So your solution becomes;
$messages = \App\Message::Where(function($query) use ($sender, $receiver)
                          {
                              $query->where("sender",$sender->id)
                                    ->where("receiver",$receiver->id);
                          })
                          ->orWhere(function($query) use ($sender, $receiver)
                          {
                              $query->Where("sender",$receiver->id)
                                    ->Where("receiver",$sender->id);
                          })
                          ->get();

Comment: Great answer. Thanks
Answer: You need to pass the variables through with use:
$messages = \App\Message::Where(function($query) use ($sender, $receiver)
                          {
                              $query->where("sender",$sender->id)
                                    ->where("receiver",$receiver->id);
                          })
                          ->orWhere(function($query) use ($sender, $receiver)
                          {
                              $query->Where("sender",$receiver->id)
                                    ->Where("receiver",$sender->id);
                          })
                          ->get();


Putting different datatypes in dictionaries from what was defined

Question: The Code:
Dictionary<String, Integer> dict = new Hashtable<>();
dict.put(record);

Is it possible to put another datatype in a dictionary if you've already defined the datatypes for the dictionary? For example, I want to put record which is has the datatype Data.
Comment: Well, the whole point of generics is that the compiler can do its type checking and flag bad code at compile time instead of having it crash at runtime. You can allow subtypes as well, but you cannot just put whatever in a typed collection. Check [these chapters from Effective Java](https://www.informit.com/articles/article.aspx?p=2861454&seqNum=4).
Comment: Your question smells of being an [XY Problem](http://mywiki.wooledge.org/XyProblem) where you ask how to solve a specific code problem when the best solution is not to mix Integer and Data types, but likely to use a completely different approach. Better that you tell us the overall problem that you're trying to solve rather than how you're currently trying to solve it, since your path is the wrong one.
Answer: Sub-types, not different types

Is it possible to put another datatype in a dictionary if you've already defined the datatypes for the dictionary?

No.
You can put in sub-types but not entirely different types. The purpose of Java Generics is to empower the compiler to stop you from using different types.
If your define your Map to hold keys of type String that lead to a value of type Integer, then:

Every key you enter into that map must be either a String object itself, or a subclass of String. The String class is final, so there is no such thing as a subclass of `String.
Every value you enter into that map must be either an Integer object itself, or a subclass of Integer.The Integer class is final, so there is no such thing as a subclass of Integer.

Suppose we defined your map with the more general types CharSequence and Number. Then we can add entries where the key is any implementation of the CharSequence interface such as String and StringBuilder. And we can add entries where the value is any subclass of Number such as Integer and Double.
Map < CharSequence, Number > map =
        Map.of (
                "Alice" , Integer.valueOf ( 42 ) ,                       // String , Integer
                new StringBuilder ( "Bob" ) , Double.valueOf ( "7.8" )   // StringBuilder , Double
        );

Records
If you want to replace your String -> Integer pairing with the use of records, no need for the Map. Just used any Set or List implementation you want to collect objects of your record type.
record CatsPerPerson ( String name , int countOfCats ) {}
List< CatsPerPerson > list =
    List.of (
        new CatsPerPerson ( "Alice" , 2 ) ,
        new CatsPerPerson ( "Bob" , 0 ) ,
        new CatsPerPerson ( "Paula Poundstone" , 12 )
    );

Comment: Hello, thank you so much for your help. I saw both yours and AztecCodes's response a while ago but didnt reply (quite frankly didnt notice a comments section until now) but this was helpful.


How to get jQuery ajax calls to work from greasemonkey page events

Question: I have a GM script which inserts a link on to the page, and then adds an event listener for when its clicked.
This then runs a function which contains among other things some jQuery.get calls. These calls however do not seem to fire unless I use the unsafeWindow version of jQuery.
function runMyFunc() {
    console.log('myFunc is called');

    $.get('index.php',function () {
        console.log('jQuery.get worked');
    });
}

$("#someHook").before('Link');

$('#myLink').click(runMyFunc);

The above will output 'myFunc is called' to console, but will not do anything with the .get
I'm using FF17 and GM1.5, jQUery from http://code.jquery.com/jquery.js
Is there a nicer way of getting this to work than using unsafeWindow? I had this working before GM 1.0 and have a lot of $.get which I would need to change in my scripts, not all of which are run from the same scenario
Answer: Your code works fine for me.  Why/How do you think $.get is not working?
Remember that you will never see the 'jQuery.get worked' message if there is a server error (404 etc.) with index.php.  Did you check the Firebug Net panel, or Wireshark, etc. to see if the AJAX call was made?
Anyway, you can see that code working, plus some error handling if you install this Greasemonkey script:
// ==UserScript==
// @name     _delme9h762
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @include  http://fiddle.jshell.net/ZqhRH/*
// @require  http://code.jquery.com/jquery.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/

function runMyFunc() {
    console.log('myFunc is called');

    $.get('index.php', function () {
        console.log ('jQuery.get worked');
    } )
    .error ( function (respObj) {
        console.log ("Error! ", respObj.status, respObj.statusText);
    } )
    .complete ( function (respObj) {
        console.log ("AJAX Complete. Status: ", respObj.status);
    } )
    ;
}

$("#someHook").before('Link');

$('#myLink').click(runMyFunc);

And then visit fiddle.jshell.net/ZqhRH/1/show/.
Note, the console will show:

myFunc is called
  Error! 404 NOT FOUND
  AJAX Complete. Status: 404

On the jsFiddle site, because index.php does not exist there, but $.get() is otherwise working perfectly.
Comment: When I test $.get without using the link event I see the 'jQuery.get  worked' message. The script above fails at jsfiddle (no index.php found)

On the site I am trying to run the code I get:
Error!

0

TypeError: xhr is undefined
jquery...user.js (line 21)

AJAX Complete. Status:

0
Comment: bleh, I dont like this comment box, keeps thinking my returns are submits. I see the GET request in firebug only for the non-link scenario tests
Comment: Verify: The answer script did not "fail" at jsFiddle.  It made the requested get (unlike what the question reports), and properly returned a 404 -- merely because the specified page doesn't exist.  The `$.get()` worked as intended.
Comment: As for getting error 0 on your site.  See [this question](http://stackoverflow.com/q/1023867/331508), but something (not shown in the question), that your script, and/or the server, and/or the target page are doing is the problem. **Link to the target page** (or at the very least, make a proper SSCE that demonstrates the problem).
Comment: Yeah, looks to be the same thing. I added their error function suggestion:
  if(xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0) { console.log('premature ajaxulation'); return;  } // it's not really an error
  else console.log ("Error! ", textStatus, errorThrown);

I also stuck your test page up on my own site and it tested fine when I changed the get target. So the target page (which i dont own) must be up to something dodgy.
Comment: I have since tested on a 'mobile' version of the same site. My code works fine. The normal version has a load a lot of their ajax code - so I assume there is something in their code that interferes with mine.


IDir '22.214.171.124' does not match to 'vpngw.fh-kempten.de

Question: I am trying to configure my client using VPN (strongswan) to access the remote server whose DNS is
vpngw.fh-kempten.de
Details of my remote VPN Server are:
Authentication Method = Mutual +XAuth
PSK =****
Phase 1
Exchange Type = aggressive
DH exchange = group2
Cipher Algorithm = 3ds
Hash Algorithm = md5
Key life time limit = 28800secs
Phase 2
Tensform Algorithm = esp-3des
HMAC Algorithm = md5
PFC exchange = Auto
compress Algorithm = disabled
Key life time limit = 28800secs
General
Host Name or IP = vpngw.fh-kempten.de
port = 500
Auto configuration = IKE conf. pull
MTU = 1400
Adapter mode = use a virtual adapter and assigned address
Client
firewall options
NAT traversal = enable
NAT traversal port = 4500
Keep alive packet rate = 15s
IKE fragmentation = enable
Maximum packet siye = 540 bytes
This is all info I have related to my VPN Server which is a remote server.
Using the command sudo ipsec up ikev1-psk-xauth, I try to run my client VPN. I get the following error in my raspberry pi
initiating Aggressive Mode IKE_SA ikev1-psk-xauth[1] to 22.214.171.124
generating AGGRESSIVE request 0 [ SA KE No ID V V V V V ]
sending packet: from 192.168.60.96[500] to 22.214.171.124[500] (363 bytes)
received packet: from 184.108.40.206[500] to 192.168.60.96[500] (404 bytes)
parsed AGGRESSIVE response 0 [ SA KE No ID HASH V V V NAT-D NAT-D V V ]
received Cisco Unity vendor ID
received XAuth vendor ID
received draft-ietf-ipsec-nat-t-ike-02\n vendor ID
received FRAGMENTATION vendor ID
received unknown vendor ID: 1f:07:f7:0e:aa:65:14:d3:b0:fa:96:54:2a:50:01:00
IDir '188.8.131.52' does not match to 'vpngw.fh-kempten.de'
generating INFORMATIONAL_V1 request 304912695 [ N(INVAL_ID) ]
sending packet: from 192.168.60.96[500] to 184.108.40.206[500] (56 bytes)
establishing connection 'ikev1-psk-xauth' failed

Following is my ipsec.conf file
config setup
conn ikev1-psk-xauth
ikelifetime=28800s
keylife=20m
rekeymargin=3m
keyingtries=1
keyexchange=ikev1
authby=secret
ike = 3des-md5-modp1024!
esp = 3des-md5-modp1024!
modeconfig = pull
aggressive = yes
fragmentation=yes
#keyexchange = ikev2
authby = secret
type = transport
leftauth = psk
leftauth2 = xauth
leftprotoport=17/1701
rightprotoport=17/1701
right = vpngw.fh-kempten.de
rightauth = psk
rightauth2 = xauth
auto = add

My motivation is to access the shared drives which are present on the remote VPN server.
Any suggestions would be highly appreciated.
Thanks in advance!!
Answer: The remote identity the server returns does not match your configuration (the identities default to the IP addresses). Try configuring rightid = vpngw.fh-kempten.de and you might have to configure leftid to the group name (Cisco lingo), which you have to determine somehow.
For your information, using Aggressive Mode with XAauth/PSK is inherently unsafe and the algorithm selection is from a different era (so is the use of L2TP actually), so you might want to complain to the admins of your university for providing such a crappy VPN.
Comment: After yout possible recommendation. I changed my config file and commenting agressive gives me the following when I run
          `sudo ipsec up  ikev1-psk-xauth`
Comment: `parsed TRANSACTION request 36532437 [ HASH CPS(X_STATUS) ]
no XAuth method found
`
Comment: Sounds like the _xauth-generic_ plugin is not loaded. See [here](https://wiki.strongswan.org/projects/strongswan/wiki/FAQ#Plugin-is-missing).
Comment: I have tried to install and use ** xauth-generic **  plugin but when I try to install using this command

, it gives me the following lines
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package strongswan-plugin-xauth-generic
Comment: Individual packages for plugins were only available on older Ubuntu releases. On newer ones the plugin is in the _libcharon-standard-plugins_ package.
Comment: Thanks, so to conclude this, when I checked the status of my ipsec using  ´sudo nano ipsec statusall´ , I can see that the xauth-generic plugin is there. :)

IDir '193.174.193.64' does not match to 'vpngw.fh-kempten.de


Fixar nome em campo de busca

Question: Neste html existe o campo de busca, onde digito o nome dos times.
Existe a opção de salvar o time como padrão, porém gostaria de deixar o nome já salvo, toda vez que abrir a pagina ele já abra buscando o time automático...
O Arquivo esta em meu desktop, assim a ideia era deixar várias copias de vários times aqui comigo, para fazerem os testes segue alguns times que podem ser lançados nesse campo: Ice Blood, Renascitur, JPHS e Fitnns.
Comment: Se alguma resposta te ajudou ou resolveu seu problema, dê um voto e marque como a resposta correta, caso contrário, informe mais detalhes sobre o que tentou e os resultados que obteve. Sempre votar e escolher as respostas corretas é uma boa prática e ajuda os outros usuários.
Comment: Testei todas as dicas e nenhuma funcionou.
Comment: Você precisará salvar o nome do time quando é seleciona como salvar como time padrão, aí depois jogará esse campo no value citado no comentário acima.
Answer: não consegui ver o seu exemplo, mas você pode usar IndexedDB.
para tal você pode armazenar o seu filtro no IndexedDB com o seguinte formato:
{
    id: "<inteiro auto-incremental>"
    timeA: "<nome do time A>",
    timeB: "<nome do time B>",
    selected: true/false
}

para criar o banco no IndexedDB, faça o seguinte:
var dbName = "filtros";
var db = null;
var request = indexedDB.open(dbName);

request.onupgradeneeded = function(event) {
  var db = event.target.result;
  var objectStore = db.createObjectStore(dbName, { keyPath: "id", autoIncrement: true });
  objectStore.createIndex("times", ["timeA", "timeB"], { unique: true });
  objectStore.createIndex("selected", "selected", { unique: false });
};

request.onsuccess = function(event) {
  db = request.result;
}

segue um exemplo das operações basicas com o IndexedDB:
Pegar todos os Registros:
var objectStore = db.transaction(dbName).objectStore(dbName);
objectStore.openCursor().onsuccess = function(event) {
    var cursor = event.target.result;
    if (cursor) {
        var id = cursor.key;
        var filtro = cursor.value
        cursor.continue();
    }
 };

Pegar Registro pelo ID:
var objectStore = db.transaction(dbName).objectStore(dbName);
var request = objectStore.get(id)
request.onsuccess = function(event) {
    var filtro= request.result;
};

Inserir Registro:
var objectStore = db.transaction(dbName).objectStore(dbName);
var request = objectStore.add(filtro)
request.onsuccess = function(event) {
    filtro.id = event.target.result;
};

Atualizar Registro:
var objectStore = db.transaction(dbName).objectStore(dbName);
var request = objectStore.put(filtro)
request.onsuccess = function(event) {
    //registro atualizado.
};

Uma vez feito isto, você terá total controle sobre os registros salvos.
Segue um exemplo completo:

var filtros = document.getElementById("filtros");
var filtro = document.getElementById("filtro");
var timeA = document.getElementById("timeA");
var timeB = document.getElementById("timeB");
var salvar = document.getElementById("salvar");
var selected = null;

var dbName = "filtros";
var db = null;
var request = indexedDB.open(dbName);

request.onupgradeneeded = function(event) {
  var db = event.target.result;
  var objectStore = db.createObjectStore(dbName, { keyPath: "id", autoIncrement: true });
  objectStore.createIndex("times", ["timeA", "timeB"], { unique: true });
  objectStore.createIndex("selected", "selected", { unique: false });
};

request.onsuccess = function(event) {
  db = request.result;
  var objectStore = db.transaction(dbName).objectStore(dbName);
  objectStore.openCursor().onsuccess = function(event) {
    var cursor = event.target.result;
    if (cursor) {
      var option = document.createElement("option");
      option.value = cursor.key;
      option.textContent = cursor.value.timeA + " x " + cursor.value.timeB;
      filtros.appendChild(option);
      if (cursor.value.selected) {
        selected = cursor.value;
        filtros.selectedIndex = filtros.options.length - 1;
        filtro.disabled = "disabled";
        timeA.value = selected.timeA;
        timeB.value = selected.timeB;
      }
      cursor.continue();
    }
  };
};

var atualizarFiltro = function () {
  var newSelected = parseInt(filtros.options[filtros.selectedIndex].value);
  filtro.disabled = newSelected != 0;

  if (newSelected != 0) {
    var objectStore = db.transaction([dbName], "readwrite").objectStore(dbName);
    var request = objectStore.get(newSelected)
    request.onsuccess = function(event) {
      var selected = request.result;
      timeA.value = selected.timeA;
      timeB.value = selected.timeB;
      selected.selected = true;
      objectStore.put(selected);
    };
  } else {
    timeA.value = "";
    timeB.value = "";
  }
}

filtros.addEventListener("change", function () {
  if (selected) {
    var objectStore = db.transaction([dbName], "readwrite").objectStore(dbName);
    selected.selected = false;
    var request = objectStore.put(selected);
    request.onsuccess = function(event) {
      atualizarFiltro();
    };
  } else {
    atualizarFiltro();
  }
});

salvar.addEventListener("click", function () {
  if (timeA.value && timeB.value && timeA.value != timeB.value) {
    var registro = { timeA: timeA.value, timeB: timeB.value, selected: true };
    var objectStore = db.transaction([dbName], "readwrite").objectStore(dbName);
    var request = objectStore.add(registro);
    request.onsuccess = function(event) {
     registro.id = event.target.result;
     var selected = registro;
      var option = document.createElement("option");
      option.value = selected.id;
      option.textContent = registro.timeA + " x " + registro.timeB;
      filtros.appendChild(option);
      filtros.selectedIndex = filtros.options.length - 1;
      filtro.disabled = "disabled";
    };
    request.onerror  = function(event) {
      alert(event.srcElement.error.message);
    };
  }
});
.linha {
  margin-bottom: 5px;
}

fieldset {
  padding: 0px;
  margin: 0px;
  border: 0px none transparent;
}

  Filtros:
  <select id="filtros">
    <option value="0">Novo Filtro</option>
  </select>

  <fieldset id="filtro">

    Time A:
    <input id="timeA" type="text" list="times" />

  x

    Time B:
    <input id="timeB" type="text" list="times" />

  <input id="salvar" type="button" value="Salvar" />
  </fieldset>

<datalist id="times">
  <option>Ice Blood</option>
  <option>Renascitur</option>
  <option>JPHS</option>
  <option>Fitnns</option>
</datalist>

O Exemplo acima não funciona, devido à uma limitação do Snippet do StackOverFlow, mas você pode conferir o mesmo no JSFiddle
Answer: Não estou conseguindo abrir a página aqui onde trabalho, mas se a tag é neste modelo:
<input type="text" name="algumName" value="COLOQUE AQUI O NOME DO TIME PADRAO"/>

Fazendo isso, inicialmente o textbox viria com o que você escrevesse no atributo value escrito
Coloque trechos do seu código pois isso varia muito de como você se comunica com seu servidor, mas basicamente o que está setado no campo value é o que está escrito, se quiser dar um submit de algum form de consulta após a página estar carregada você pode usar o query para isso;
$(document).ready(function(){

 $("#IdBotaoSubmitSeuForm").click();
 //ou voce pode usar
 $('#idDoSeuForm').submit();

});

Answer: Eu trabalharia com cookies utilizando o plugin jquery-cookie
No momento que o usuário seleciona a opção Salvar como time padrão você pega o valor do campo e salva no cookie dessa forma:
$.cookie("time_a_padrao", "Renascitur");
$.cookie("time_b_padrao", "JPHS");

Quando a página carregar, você pode usar o próprio jQuery $(document).load() e ver se existem cookies com os nomes time_a_padrao e time_b_padrao e pegar os valores dessa forma:
$.cookie("time_a_padrao");

Coloque o valor desse cookie no seu input e faz a pesquisa.
Para você excluir um cookie, caso o usuário deseja que o time padrão seja outro, faça dessa forma:
$.removeCookie("time_a_padrao");

Fixar nome em campo de busca


Função .filter() para um List

Question: Eu tenho uma classe Pessoa que tem as colunas Integer id. String name, e String date_born.
Na minha activity principal eu já estou recuperando a lista de pessoas que vem da minha requisição feita na API e já mando para minha função para agrupar.
private void loadList(List<Pessoas> listPessoas){
       Map<String, List<Pessoas>> listMap = listPessoas.stream().collect(Collectors.groupingBy(Pessoa::getDate_born)); //LISTA AGRUPADA
}

Mas eu preciso filtrar a lista antes de poder agrupar pelo campo date_born, aí vai minha pergunta.
private void loadList(List<Pessoas> listPessoas){
      List<Pessoas> listPessoasFiltered = ??
      Map<String, List<Pessoas>> listMap = listPessoasFiltered.stream().collect(Collectors.groupingBy(Pessoa::getDate_born));
}

Já existe uma função tipo .filter() que retorna a lista ou tem que implementar uma função de filtro para retornar minha lista de pessoas filtrada antes de agrupar as pessoas por este campo?
Lembrando não é dentro de um Adapter é um filtro de uma lista.
Answer: Você não precisa criar uma outra lista filtrada, pode aproveitar que está usando streams e usar o método filter:
Map<String, List<Pessoa>> map = listPessoas.stream()
    // filtrar pelo critério que precisa
    .filter(pessoa -> pessoa.getName().endsWith("o"))
    // agrupar por data de nascimento
    .collect(Collectors.groupingBy(Pessoa::getDate_born));

No exemplo acima, estou filtrando os nomes que terminam em "o", mas você pode usar qualquer critério que desejar (o importante é que o lambda passado para filter retorne true para os elementos que você quer manter).

Lembrando ainda que getDate_born não está de acordo com as convenções de nomenclatura da linguagem (deveria ser algo como getDateBorn, por exemplo). Ver mais sobre o assunto aqui.
Comment: To chorando de felicidade, achei que ia precisar criar uma função pra isso , agora que vi que tem uma pronta é só usar vlw mesmo.

Função .filter() para um List


Erro programa iniciante em C

Question: Estou começando a programar agora e estou com um problema no exemplo abaixo. A questão pede para calcular o imposto de renda, de acordo com o salário recebido pela pessoa. O erro é que, independente do valor do salário que eu coloco como entrada, o programa imprimi "isento", até mesmo para valores que ultrapassando o intevalo relativo à isenção.
include
int main (){
    double salario, aux1, aux2, aux3;

    printf("digite seu salario: ");
    scanf("%lf", &salario);

    if(salario>=0.00 || salario<=2000.00){
        printf("Isento");}
    else {if(salario>=2000.01 || salario<3000.00){
        aux1=salario*0.08;
        printf("O valor a ser pago e %.2lf", &aux1);}

    else {if(salario>=3000.01 || salario<=4500.00){
        aux2=salario*0.18;
        printf("o valor a ser pago e %.2lf", &aux2);}

    else {if(salario>=4500.01){
        aux3=salario*0.28;
        printf("O valor a ser pago e %.2lf", &aux3);}
            }
          }
        }

return 0;

}

Answer: Seu problema está aqui:
if(salario>=0.00 || salario<=2000.00){

Qualquer valor atenderá a tal condição (todos os números positivos serão maiores ou iguais a zero bem como todos os negativos serão menores ou iguais a 2000)
Creio que o teste correto seja:
if(salario>=0.00 && salario<=2000.00){

O mesmo se aplica a todos os outros comandos if.
Comment: Nossa, realmente. Não tinha me atentado a isso. Muito obrigada!
Answer: Além desse problema com operadores && e ||, existem outros problemas também.
Ao chamar o printf você esta passando o operador de endereçamento &, assim ele mostrara o endereço da variável em memoria e não seu valor.
Errado - printf("O valor a ser pago e %.2lf", &aux1);}
Correto - printf("O valor a ser pago e %.2lf", aux1);}

E uma dica para iniciante. Treine bastante a edentação do seu código.
Bons Estudo!
Answer: O problema está no identificador lógico || nesse caso você deveria usar o &&.
Na sua lógica você está dizendo que salario pode ser maior que 0 ou menor que 2000,  só que 2001 já é maior que 0 então o retorno é verdadeiro.
você usaria || se por exemplo necessitasse de uma expressão assim x < 1000 || x > 2000
Answer: Esta resposta é uma versão reformatada, porque o programa como foi postado está pessimamente formatado.
int main ()
{
  double salario, aux;

  printf("digite seu salario: ");
  scanf("%lf", &salario);

  if (salario >= 0.00 && salario <= 2000.00)
  {
    printf("Isento");
  }

  else if (salario >= 2000.01 && salario < 3000.00)
  {
    aux = salario * 0.08;
    printf("O valor a ser pago e %.2lf", aux);
  }

  else if (salario >= 3000.01 && salario <= 4500.00)
  {
    aux = salario * 0.18;
    printf("o valor a ser pago e %.2lf", aux);
  }

  else if (salario >= 4500.01)
  {
    aux = salario * 0.28;
    printf("O valor a ser pago e %.2lf", aux);
  }

  else
  {
    printf("salario digitado negativo!");
  }

  return 0;
}

Erro programa iniciante em C


How to Migrate from SQLite to MySQL?

Question: I built a Drupal 8 site using SQLite. Performance is awful, so I'd like to use MySQL instead.  What's the best way to go about this?
A step-by-step guide would be nice, but any advice and tips are appreciated.
Thanks in advance
Comment: See also: [Transfer a site from SQLite to MySQL](http://drupal.stackexchange.com/q/4135/9223)
Comment: @unor that link is for Drupal 7
Comment: @ParagMagunia: Yes, that's why it's just a "see also" and not suggested as duplicate.
Answer: It has been a while since I've used their product (MSSQL to MySQL) but a place to start might be here:
https://dbconvert.com/sqlite/mysql/
For me it worked flawlessly converting a MSSQL database with 10 years of data into MySQL so I could import it to Drupal 7. I would expect the same quality in this sister product, it's worth a look.
Comment: Thanks. This appears to be a $150 product. There is a trial version, but it has limitations and watermarks database records. I assume Drupal configuration files would need to be modified as well to use a new database driver.
Comment: For MySQL? I figured if you converted the database to MySQL, you could import it and set a database connecting to it in settings.php and specify the driver as MySQL. If it works, Drupal wouldn't know the difference. And yeah I paid the $100 for a license because the trial result was promising.
Comment: Which is exactly what I did, I converted, imported to MySQL as a new database, created another connection key in settings.php and voila, it worked. You can try that same approach and see what happens.
Comment: Get the trial version of navicat premium installed, it's free for 14 days and you can literally drag tables from a MSSQL database to a mysql one. Drupal won't know or care

How to Migrate from SQLite to MySQL?


why not session data is stored in table duration do login in site?

Question: I am New Comer in PHP with MVC Codeigniter Framework.
I have a issue about session storing in table(ci_sessions) with codeigniter.and i have also set config.php file like-
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration']= 3600;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database']= TRUE;
$config['sess_table_name']= 'ci_sessions';
$config['sess_match_ip']= FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;

and also created table namely ci_sessions in database. like
CREATE TABLE IF NOT EXISTS  `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(45) DEFAULT '0' NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id),
KEY `last_activity_idx` (`last_activity`)
);

After doing all activities of the above ,No data stored in user_data column of ci_sessions table in DB.
When I want to access session data by using like-
print_r($this->session->all_userdata());
print $this->session->userdata['myksb'];
then error is displayed like -

Array (
[session_id] => 97b9e34713b52f32a32e915053cba826
[ip_address] => 127.0.0.1
[user_agent] => Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko
[last_activity] => 1363866927 )

A PHP Error was encountered
Severity: Notice
Message: Undefined index: myksb
Filename: controllers/home.php
Line Number: 13876
Comment: Did you load the session library? (`$this->load->library('session');` or autoload)
Comment: Thanks Mr. Maxime Morin for reponse. I have include this statement like -   $this->load->library('session'); in costructor of controller
Comment: Have you assigned data to that key?
Comment: Yes Sir , I have assigned data to that key like - $this->session->set_userdata('myksb','chandan'); during session creation in any function.
Comment: Use `$this->session->userdata('myksb');`.  `userdata()` is a method not an array.  Although, it will print empty because it's obviously not in your session...
Comment: If i am using $this->session->userdata('myksb'); then it will print empty. Please help me.... what should i do to solve it....
Comment: @ChandanSroniyan Please show us the code where you add set your user's data.  (`$this->session->set_userdata('myksb','chandan');`)  I'm not sure what you meant by "during the session creation in any function".  On a side note, make sure you don't destroy the session before printing the results.
Comment: //Logic for demo session start here
`function sessionDemo()
{
$this->session->sess_destroy();
$this->session->set_userdata('myksb','chandan');
redirect('home/sessionDemo1');
}
function sessionDemo1()
{
print_r($this->session->all_userdata());
print $this->session->userdata('myksb');
die;
}`
//Logic for demo session end here
Comment: Did you try without the `$this->session->sess_destroy();` call?  `sess_destroy()` kills your session then you want to add data to your session.  Doesn't it sounds wrong? ... Stop with the "please help me" it's only adding noise to your question...
Comment: @Maxime Morin , a error occurs like -  Fatal error: Call to undefined function sess_destroy() in C:\wamp\www\mysadagi_voicetongues\system\application\controllers\home.php on line 13866
Comment: See my answer, you have to remove the whole line. (`$this->session->sess_destroy();`)
Comment: Very-Very Thank Mr.Maxime Morin. My Problem has been solved.
Comment: If your problem was solved by my answer below, feel free to accept it.  If your problem was solved by doing something else, please add an answer and accept it.
Comment: my problem was solved by @Maxime Morin .thanks
Answer: These a couple things to be fixed here.

$this->session->userdata() is a method not an array. $this->session->userdata['myksb']; is not valid.  You have to use $this->session->userdata('myksb');
$this->session->sess_destroy() kills your session.  It actually removes your sessionId from your session and cookie.  Once that is done, you can not assign new information to your session, it doesn't have an ID anymore.  You have to remove that call.  CodeIgniter will automatically clean your session table.


Login functionality from external API in React with Node.js

Question: I'm having trouble figuring out how to get Node.js backend tokens into React.js frontend local storage. To login a user will use their credentials though an external websites API using the Oauth2 flow, this will be the only way to login into the application.
Currently, the user clicks a button which opens a new window in the authorization URL where the user will grant privilege. Once granted, the user is redirected to the backend endpoint which goes through passport.js and gets the required access and refresh tokens sent from the external API. This is then stored in a session on the backend database. What I want, instead, is to not store a session on a database but instead implement JWT and store the user's data in local storage. With the current flow, its just not possible to do this and I haven't found the right documentation to work it out.
There are many websites that implement it the exact way I want but tracking down the way they do it has appeared to be a challenge in on itself.
Answer: So instead of using passport.js, which was causing a plethora of issues, I decided to implement the Oauth2 flow myself. Instead of doing ALL the work in the backend, I broke the flow into different parts.
Originally, I sent the user to the backend where they would recieve an authorization token there. This turned out to be troublesome, instead, request an authorization code on the front end. For example, send the user to the Auth path and redirect the user back the the front end once privileges have been granted. Wait at the frontend callback for a code, once obtained, send a post request to the backend with that code and any other data in the body.
When obtained at the backend, trade that code for the access token and respond to the post requst with the neccassary token and any other data that needs to be sent back e.g. profile name, picture, date of birth. You can the implementn the JWT flow and no database is required to store any session or tokens, all can be stored client side securely.


Limit of Bernoulli R.V.s is a singular distribution

Question: Working through an exercise in Probability (the question can be found in Lamperti).
Let $X_1,\dots$ be independent Bernoulli random variables with $\mathbb{P}(X_i=1) = p$ and $\mathbb{P}(X_i=0)=1-p$. Let $$Z = \sum_{k=1}^\infty X_k 2^{-k}$$ and $F_p(x) = \mathbb{P}(Z \le x)$.
Show that if $p = 1/2$ then $F_{1/2}(x) = x$, $0<x<1$. That is, $Z \sim U(0,1)$ and if $p\in(0,1)\setminus\{1/2\}$, then $F_p$ is continuous, strictly increasing and singular. That is, $F'_p(x) = 0$ almost-everywhere with respect to the Lebesgue measure.
We did the first part as an assignment question, where you approach it from a partial sum up to $n$ Bernoullis and take the characteristic function of that and then let $n\to\infty$. I'm not sure how to approach the singular part, because it was given as an exercise before we covered characteristic functions. Lampert hints that the distribution is singular if and only if the corresponding measure puts probability 1 on a set of Lebesgue measure 0.
Any hints or help would be appreciated! Thanks
Answer: This might be complicated to describe rigorously, using elementary notions, but the underlying concept is simple: almost all real numbers between $0$ and $1$, when written in binary, have equally many zeros and ones.  Because $Z$ assigns zero probability to such numbers--it favors an imbalance of zeros and ones when $p\ne 1-p$--it must have a singular distribution.
The statement in bold needs a clear definition.  I am going to sneak up on the definition by developing a series of simpler definitions and notations.  But before we proceed, let's look at some of these distributions.

The colored curves plot the CDFs.  They are all self-similar in the sense suggested by the underlying rectangles: The curve in the lower left rectangle is obtained by taking the entire curve and multiplying all x-values by $1/2$ and multiplying all y=values by $1-p$.  That is, the curve is shrunk towards the origin $(0,0)$ by factors of $1/2$ and $1-p$.   Likewise, the curve in the upper right rectangle is obtained by shrinking the entire curve towards the coordinate $(1,1)$ by factors of $1$ and $p$.  (This description completely determines each curve!)
Here are the major steps in the analysis.

Let $a_1, a_2, \ldots, a_n$ be any sequence of zeros and ones.  It represents a binary number in the interval $[0,1)$ by "putting a binary point in front of it."  As a matter of notation, and to define precisely what this means, let $$[a_1\,a_2\,\cdots\,a_n] = a_1 2^{-1} + a_2 2^{-2} + \cdots + a_n 2^{-n}.$$
Since we will be studying the proportions of ones within binary representations, let's invent a notation for that.  Define  $$\rho([a_1\,a_2\,\cdots\,a_n]) = \frac{\#\{i \in \{1,2,\ldots, n\}\mid a_i=1\}}{n}$$ to be that proportion.
We cannot analyze all the infinitely many binary digits of any real number $x$ all at once: we have to look at finitely many of them and take limits.  To this end, extend the function $\rho$ to entire intervals of real numbers determined by their initial sequences.  That is, if $$[a_1\,a_2\,\cdots\,a_n] \le x \lt [a_1\,a_2\,\cdots\,a_n] + 2^{-n},$$ then define $$\rho_n(x) = \rho([a_1\,a_2\,\cdots\,a_n]).$$  The functions $\rho_n$ are defined on the entire interval $[0,1)$.
If you like, you could also define the $\rho_n(x)$ numerically in terms of the binary expansion of the integer part of $2^n x$ (which is how the next figure was produced), but I thought the preceding description might give a clearer idea of the underlying concept.

The key idea is to collect all numbers that look, based on the initial (finite!) part of their binary representation, like they have a given proportion of ones.  We should allow for that proportion to be in a narrow range, say between $\alpha$ and $\beta$ where $0 \le \alpha \le \beta \le 1$.  To this end, define the (Borel measurable) set $R$ by $$R(n,\alpha,\beta) = \{x\in [0,1)\mid \alpha \le \rho_n(x) \le \beta\}.$$  That is, the proportion of ones within the first $n$ binary digits of $x$ lies between $\alpha$ and $\beta$.
In the preceding figure, you may visualize $R(n,\alpha,\beta)$ by referring to the graph of $\rho_n$, drawing the interval $[\alpha,\beta]$ on the vertical axis, identifying all parts of the graph whose heights are within that interval, and looking down at the horizontal ($x$) axis to see which numbers correspond to those heights: that (highly disconnected) set is $R(n,\alpha,\beta)$.
At this point we may leave the world of binary representations and focus on the digits themselves.  When those first $n$ binary digits are generated by $X_1, X_2, \ldots, X_n$, each having a chance $p$ of being $1$, then the proportion of ones has a Binomial$(n,p)$ distribution.  Thus, unless $X_{n+1}=X_{n+2}=\cdots = 1$, $$\rho_n(Z) = \rho[X_1\,X_2\,\cdots\,X_n] \sim \frac{1}{n}\text{Binomial}(n,p).$$  We may exclude all values of $Z$ that end in all ones because (as is easy to see and show) their chance of occurring is zero.
Consequently, writing $F_{n,p}$ for the Binomial$(n,p)$ distribution function, $$\mathbb{P}(Z \in R(n,\alpha,\beta)) = F_{n,p}(n\beta) - F_{n,p}(n\alpha).$$
Now suppose $p\ne 1/2$.  Pick $\alpha,\beta$ such that $p\in[\alpha,\beta]$ but $1/2\notin[\alpha,\beta]$.  It is easy to prove (in many ways, ranging from the Weak Law of Large Numbers to Chebyshev's Inequality) that as $n$ grows large, the value of $F_{n,p}(n\beta)-F_{n,p}(n\alpha)$ approaches $1$: that is, the Binomial distribution becomes concentrated around its expected value $p$.  This means as $n$ grows large, all the probability of $Z$ becomes concentrated within the (very complicated union of intervals) $R(n,\alpha,\beta)$.
However, the result for the case $p=1/2$ (for which the distribution of $Z$ is Lebesgue measure) shows that the Lebesgue measure of $R(n,\alpha,\beta)$ approaches zero.  Together with (7) we conclude that for $p\ne 1/2$, the distribution of $Z$ is singular (with respect to Lebesgue measure).
In fact, the same argument shows that the various distributions of $Z$ for any two different $p$ are all mutually singular: as $n$ grows large, the probability of one concentrates within a region that has vanishingly small probability for the other.

Example R code to plot one of these distribution functions follows.  Function f generates the sequence of integers $n\rho_n(0), n\rho_n(2^{-n}), n\rho_n((2)2^{-n}), \ldots, n\rho_n((2^n-1)2^{-n}).$  These count the number of $X_i$ for $i=1,2,\ldots, n$ that are equal to $1$. It then computes the associated probability and accumulates it to approximate the CDF of $Z$ across an equally-spaced set of $2^n$ points in the interval $[0,1]$.  This process emulates the self-similarity transformation described at the beginning of this answer.
#
# The distribution function, approximated to an accuracy of 2^(-n) in Z.
#
f <- function(n, p=1/2) {
  y <- rep(0, 2^n)
  if (n > 0)
    for (i in 1:n) {
      j <- 1:(2^(i-1)); y[j + 2^(i-1)] <- y[j] + 1
    }
  cumsum(p^y * (1-p)^(n-y))
}
#
# Example: plot a distribution for given `p`.
#
n <- 11
p <- 1/6
z <- c(0:(2^n) / 2^n)
Probability <- c(0, f(n, p))
plot(z, Probability, type="S")


Input parameters in Dirichlet density function

Question: I'm trying to feed the Dirichlet density function with some sample data and estimated alpha vector using R in Python (library rpy2), but I don't understand the error that I got:
>>> q['dirichlet2b'] = DirichletReg.ddirichlet(np.asarray(mySample),np.asarray(listOfAlphas), log=False, sum_up=True)
Error in rowSums(alpha) : 'x' must be an array of at least two dimensions
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/rpy2/robjects/functions.py", line 82, in __call__
    return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/rpy2/robjects/functions.py", line 34, in __call__
    res = super(Function, self).__call__(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Error in rowSums(alpha) : 'x' must be an array of at least two dimensions

The function I'm dealing with is declared as:
ddirichlet(x, alpha, log = FALSE, sum.up = FALSE) .
Its implementation is here.
From the documentation:

alpha the Dirichlet distribution's parameters. Can be a vector (one
  set of parameters
        for all observations) or a matrix (a different set of parameters for each observa-
       tion), see details
  Details:

Usually, alpha is a vector thus the same parameters will be used for all observations. If alpha is a
matrix, a complete set of alpha-parameters must be supplied for each observation.

So
In a test I am running, these are the values of the two variables:
>>> mySample
[0.23947368421052631, 0.29122807017543861, 0.13596491228070176, 0.24473684210526317]
>>> listOfAlphas
[0.96321625726816873, 0.010664397021223898, 0.0073408705340313662, 0.011574312890446362]

Why should I need a matrix of alphas for my observations? What exactly is needed to feed a Dirichlet density function?
Answer: The error appears to be caused by the fact that x is not a matrix.  The reason why x needs to be a matrix, in principle is that the Dirichlet is a multivariate distribution; each of your $N$ observations has, let us say, $K$ elements, leading naturally to a representation of x as an $N \times K$ matrix.  Even if you only have one observation, the function as implemented in DirichletReg is looking for a $1 \times K$ matrix (but see below for an alternative.)  Here's the relevant line of code from the implementation:
  if(is.null(dim(x))) stop("x must be a matrix")

alpha does not need to be a matrix; however, if it is a matrix, it needs to be $N \times K$ as well.  The latter representation allows for a Dirichlet with each observation having a different parameterization.
Try constructing x as a matrix and see if that fixes the problem.
The example below uses the ddirichlet function in the gtools package, which has the same calling structure as that in DirichletReg (for some directory-related reason I can't get DirichletReg to load in python, but I can get gtools to load):
>>> xval = robjects.FloatVector([0.3,0.5,0.4,0.3,0.3,0.2])
>>> x = robjects.r['matrix'](xval, nrow=2)
>>> alpha = robjects.FloatVector([4,4,2])
>>> print(x)
     [,1] [,2] [,3]
[1,]  0.3  0.4  0.3
[2,]  0.5  0.3  0.2

>>> print(alpha)
[1] 4 4 2

>>> gtools.ddirichlet(x,alpha)
<FloatVector - Python:0x3e5e830 / R:0x2ec7748>
[5.225472, 6.804000]

Also note that gtools's implementation of ddirichlet treats x differently than DirichletReg's implementation of ddirichlet:
if (!is.matrix(x))
    if (is.data.frame(x))
        x <- as.matrix(x)
    else x <- t(x)

It looks like you can just load a vector in, as you wished, and it will be converted to a row vector.  Let's try it:
>>> x2 = robjects.FloatVector([0.3,0.4,0.3])
>>> alpha = robjects.FloatVector([3,4,3])
>>> gtools.ddirichlet(x2,alpha)
<FloatVector - Python:0x2c63a28 / R:0x266ee58>
[7.838208]

So that's another fix to your problem.
Comment: Thank you. I'm now comparing the results yielded by [this implementation](http://stackoverflow.com/questions/10658866/calculating-pdf-of-dirichlet-distribution-in-python) and those given by the implementation in gtool.  They usually match, but sometimes a few strange things happen.
case 1) I get values slightly > 1  (like 1.07) when there is only one x and one alpha. Why should a density function return such a value?
Comment: case 2) x = [0.99401197604790414, 0.0059880239520958087]
 alphas =[0.16590711348505713, 0.029765153762857845]
 ======> implementation 1:  3.66328469334 ; implementation 2:  3.663285
Comment: ADDITIONAL INFO FOR CASE 1)
 x=[0.94736842105263153]; alphas = [0.032034681077891182]======> implementation 1: 1.05372888806 ; implementation 2: 0.   This happens very often when I have only 1 value and 1 alpha. Does it make sense? Also, why do the two densities differ?


Is it OK to play a G chord on the Ukulele differently than the standard finger position?

Question: I'm very new to learning any instrument, so the uke is my first foray into anything musical. My question is, the standard placement of fingers for a G chord is not what I learned originally and I'm having a hard time retraining myself.
This is what I mean:

Is much easier for my fingers to fall to naturally than this:

Is there an argument in favor of reteaching myself the "correct" way? I'm not the fastest at switching chords so I have no way of knowing yet if I'm screwing myself over by taking this "shortcut".
Comment: For what it's worth, I am no expert at the ukulele or frankly any fretted instruments, but I learned the second way and that's how I've always done it.
Answer: With all fretted instruments, there are several ways of fingering certain chords. The criteria are where you've come from and where you're going to. The fingering may well vary and you'll maybe have two or three different ways to play the exact same chord shape, considering the criteria. So, any fingering will be o.k., but think about these variables.
Comment: While it's of course true than often there is more than one reasonable way to arrange your fingers for a given shape,  there are many bad ways to finger guitar chords that beginner self-taught guitarists can end up stumbling into that then later on cause problems.  The general principle you're advocating is correct.  You're getting upvoted for the general idea that "the most common way isn't necessarily right, if it feels good, do it" And while I agree with you in general, in this specific example I think this is a bad fingering.
Comment: In your answer you mentioned the "variables" of what chords precede and follow the chord in fingering choice, but I would advocate that you also factor in the effect of a choice of the left hand position, and the pressure required to keep the hand in that position.  There's a reason An E shape is fingered 2,3,1 not 3,2,1 and if a beginner thinks that maybe they want to play it 3,2,1, they should be advised against that.
Comment: @Some_Guy - this shape is the same as a D chord on the guitar. I've said it before - there are twelve different ways to finger that shape. All effective, some easier than others, some suiting one better than another player. Also, helping by being more convenient after a certain chord shape, or before another chord. I tend to use three different shapes, dependant on what I'm doing. So, it's fair to suggest options are found and used. If a particular fingering suits only one person, it's not *wrong*, just different. Django didn't have many options, but seemed to do more than just get by...
Answer: TL;DR: you should probably play it the standard way, not the way you're playing it, because it promotes a poor left hand position.  You should never have a higher finger coming in "under" a lower finger.
(all this advice would apply to playing a D chord on a guitar too, since they're the same fingering, 0 2 3 2. (on a guitar, x x 0 2 3 2) )
I would say that, while there is no solid reason you absolutely have to play any chord with any specific fingering, with a good left hand position some fingerings stand out as better than others.
Firstly, for "comfortable" chords (not "spider" chords that require you to stretch out in both directions) your fingers should naturally fall tilted towards the fretboard (with your knuckle pointed towards the headstock), or at the very most 90 degrees, but never the other way.
this is a guitar but applies equally to uke.  If you were to tilt your fingers the other way, you would have to over-rotate your left hand counter clockwise, and your G fingering forces this.  In your picture you can see that in one position, only the right side of your left hand is touching the neck, rather than the left.  This implies an unnatural wrist rotation.  If you play with the uke headstock significantly raised it might not be as obviously uncomfortable as with it lower, but the problem, while reduced, will be still present.
This will effect your ability to quickly change between chords, as you will have change your entire left hand position to play a G chord (coming from, say an E minor chord 0 4 3 2)
You want to choose a position where your fingers are the most free and flexible possible, as this will aid you in changing to and from chords (and later on in adding ornaments to chords and passing notes between chords).
One last thing, you might find cutting your nails allows you to adopt a more natural left hand position, with your fingers pointing more into the neck.
More general tips for a beginner ukelelist wrapping their hands around chords for the first time: try fingering a chord, taking your hand off the neck (even shaking it around a little), then fingering it again, not one string at a time but all strings simultaneously.  This will give you a) a good clue as to what hand positions feel more natural as this will be more difficult with contorted left hand positions and b) is a good exercise to help with learning quick changes between chords.  Fingering chords by putting down each finger string by string is a habit you should try your best get out of immediately after learning a new chord, you want to try and build a muscle memory of the overall shape by putting down all fingers simultaneously.
Happy ukeleling!
Comment: On guitar,(uke) at the last count, there are actually *12* different fingerings for that open D (G) chord, so not sure what the *standard* way would be. It's a personal thing, and whilst I maybe wouldn't use perhaps half of those options, - I tend to use 3 different shapes -  others could and possibly do.
Comment: @Tim  There are not 12 different fingerings for that d shape that aare in any way useful. There are 3:  (starting in the bass): 1st 3rd 2nd ; 2nd 4th 3rd ; and with a partial barre on the 2nd fret. While 2nd 3rd 1st and 3rd 4th 2nd are physically possible they are a bad idea, requiring you to position your right hand in a way that restricts movement.  3rd 4th 1st for example is technically doable.  But you of course would never actually use it.
Answer: Just to add to @Tim's answer, one other important factor to consider how to finger chords, is comfortability. How flexible your fingers are and the length of your fingers plays an important role is fingering chords. One's hand needs to be comfortable with the chord you are currently fingering.
I've never played an ukulele, but on guitar, I can finger a G chord with my 2nd, 3rd and 4th finger (apart from playing it with 4 fingers) because my fingers are really long. Guys with short fingers usually prefer to play the G chord using their 1st, 2nd and 3rd fingers due to the length and stretch of the middle finger.
It is as stated by @Tim, context is important, from which chord you are coming from and where you are going to, so you need to work around that and find what works best in which context. If you have difficulty with fingering certain chords, like G in this context, and you are comfortable with your how you are fingering the chord now, try and see if you can't find alternative fingering for the preceding chord and the chord following that G. Experiment and see what works best for you.
Remember one thing, chord books and teachers are just basic guidelines, and not the alpha and omega. There is no correct way or wrong way to finger any chord. Create your own unique style which works best for you and work on that.
Just for interest sake and to conclude, when it comes to unique fingering, have a look at how uniquely the late Kurt Cobain fingered his open A chord and open E5 chord, haven't seen these fingerings in any chord book or online source
Comment: just a note, a G chord on a uke is a D major shape from a guitar (0  2 3 2)
Answer: I learned the second image first, but find it hard to use the finger position, so I changed it and find the position on the first image more comfortable for me during progressions. I think it does not matter so long as you're comfortable while playing.
Answer: I would be very careful with this. It might be a right moment to consult a teacher and take a few lessons to get some help with something more fundamental - the hand position. It's hard to judge by the pictures but I suspect you might need to correct something when it comes to hand position.
Also think about it this way - you still need to learn lots of chords and fingerings, and a lot of them would feel uncomfortable and awkward at first. So there is no harm learning this chord both ways and finding out which fingering "wins" in the longer term.
You might for example notice down the line that lots of typically used chord ornamentations and little embellishments (like eg. going between G and Gsus4 and Gsus2) work much better with the second fingering. From that point of view it always makes sense to follow the canon when you starting, to make following and learning from other good players easier.


How to sudo on a computer using ssh inside a bash script

Question: I'm trying to run a bash script that has:
ssh -l <username> <compname> 'sudo yum -y install expect'

I get the error:
sudo: sorry, you must have a tty to run sudo

on some computers but on others the process runs smooth. How can I prevent this?
Comment: superuser.com might be a better place for this question
Comment: The question *is* programming related because it is in a script.  That is enough to make it valid for SO.  No mere user would need to know this.
Answer: Use the -t flag to force a tty to be allocated:
ssh -t -l <username> <compname> 'sudo yum -y install expect'