text:
Q: tufte-latex: Full-width algorithm2e blocks without minipage I'm using an algorithm2e block in the tufte-latex book and I would like to try to make it full width. I know that the question has been asked here:
tufte-latex: Full-width algorithm2e blocks
but using a minipage is not an option for me because it messes up with all the floats. Is there a way to create a version of the algorithm environment that spans the full width without messing with the floats?
Minimum (non-working) example
\documentclass[a4paper,justified]{tufte-book}
\usepackage[ruled,vlined,linesnumbered]{algorithm2e}

\begin{document}
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? [33] At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat

%\begin{fullwidth}
%\begin{minipage}{\linewidth}
\begin{algorithm}[p]

\KwIn{$N$: number of intervals, $S$: space size, $d_1$: first interval, $P$: number of iteration (precision)}
\KwOut{The ratio $r$}
$m \gets S/d_1$\;

  \uIf{$m=N$}{
    \tcc{There is no solution in this case, we can perhaps throw an error!}
  }
  \uElseIf{$m < N$}{
    \tcc{There is one solution between 0 and 1. We unleash the bisection algorithm!}
    xleft $\gets 0$\;
    xright $\gets 1$\;
    \For{$i \gets 1$ \textbf{to} $P$}{
    xcandidate $\gets 0.5*(\textrm{xright} + \textrm{x\_left})$\;
    ymonomial $\gets pow(\textrm{xcandidate}, N)$\;
    yline $\gets \textrm{xcandidate}\cdot m/2 -m+1$\;
    \eIf{$\textrm{ymonomial} \geq \textrm{yline}$}{
       xleft $\gets \textrm{xcandidate}$\;
    }{
       xright $\gets \textrm{xcandidate}$\;
    }
   }
   \tcc{We have narrowed down the search to the interval between `left' and `right'. The best we can do now is to output the middle point.}
   \KwRet{$0.5 \cdot \textrm{xright} + \textrm{xleft}$}
  }
  \Else{
      \tcc{There is one solution greater than 1. The first thing we can do is to find a x far enough so that the line is below the monomial. We do that by considering exponentially larger steps: first x=2, then x=4, then x=8, and so on.}
      xleft $\gets 1$\;
      xright $\gets 2$\;
      \While{$pow(\textrm{xright}, N)  < \textrm{xright}\cdot m/2 -m+1$} {
        xright $\gets 2\cdot \textrm{xright}$
      }

      \tcc{Now we unleash the very same bisection algorithm as before, paying attention that the extremes are now switched: the right one has the monomial above the line.}

    \For{$i \gets 1$ \textbf{to} $P$}{
    xcandidate $\gets 0.5*(\textrm{xright} + \textrm{x\_left})$\;
    ymonomial $\gets pow(\textrm{xcandidate}, N)$\;
    yline $\gets \textrm{xcandidate}\cdot m/2 -m+1$\;
    \eIf{$\textrm{ymonomial} \geq \textrm{yline}$}{
       xright $\gets \textrm{xcandidate}$\;
    }{
       xleft $\gets \textrm{xcandidate}$\;
    }
   }
   \tcc{Once again, we have narrowed down the search to the interval between `left' and `right'. The best we can do now is to output the middle point.}
   \KwRet{$0.5 \cdot \textrm{xright} + \textrm{xleft}$}
  }
\caption{Find the ratio of a geometric difference progression via bisections}
\label{algo:geometricratio}
\end{algorithm}
%\end{minipage}
%\end{fullwidth}

Something else that should be in the same page as the stuff before, but goes to the next one if I uncomment the fullwidth/minipage solution, as proposed in https://tex.stackexchange.com/questions/553891/tufte-latex-full-width-algorithm2e-blocks

\end{document}

Thank you very much in advance,
Daniele

A: You can't use the {p} version of algorithm, nor does fullwidth float at all.  You can achieve the same effect as {p} using the afterpage package, however.
\documentclass[a4paper,justified]{tufte-book}
\usepackage[ruled,vlined,linesnumbered]{algorithm2e}
\usepackage{afterpage}

\begin{document}
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? [33] At vero eos et accusamus et iusto odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat

\afterpage{\clearpage\vspace*{0pt plus 1fil}
\begin{fullwidth}
\begin{minipage}{\linewidth}
\begin{algorithm}[H]
\KwIn{$N$: number of intervals, $S$: space size, $d_1$: first interval, $P$: number of iteration (precision)}
\KwOut{The ratio $r$}
$m \gets S/d_1$\;

  \uIf{$m=N$}{
    \tcc{There is no solution in this case, we can perhaps throw an error!}
  }
  \uElseIf{$m < N$}{
    \tcc{There is one solution between 0 and 1. We unleash the bisection algorithm!}
    xleft $\gets 0$\;
    xright $\gets 1$\;
    \For{$i \gets 1$ \textbf{to} $P$}{
    xcandidate $\gets 0.5*(\textrm{xright} + \textrm{x\_left})$\;
    ymonomial $\gets pow(\textrm{xcandidate}, N)$\;
    yline $\gets \textrm{xcandidate}\cdot m/2 -m+1$\;
    \eIf{$\textrm{ymonomial} \geq \textrm{yline}$}{
       xleft $\gets \textrm{xcandidate}$\;
    }{
       xright $\gets \textrm{xcandidate}$\;
    }
   }
   \tcc{We have narrowed down the search to the interval between `left' and `right'. The best we can do now is to output the middle point.}
   \KwRet{$0.5 \cdot \textrm{xright} + \textrm{xleft}$}
  }
  \Else{
      \tcc{There is one solution greater than 1. The first thing we can do is to find a x far enough so that the line is below the monomial. We do that by considering exponentially larger steps: first x=2, then x=4, then x=8, and so on.}
      xleft $\gets 1$\;
      xright $\gets 2$\;
      \While{$pow(\textrm{xright}, N)  < \textrm{xright}\cdot m/2 -m+1$} {
        xright $\gets 2\cdot \textrm{xright}$
      }

      \tcc{Now we unleash the very same bisection algorithm as before, paying attention that the extremes are now switched: the right one has the monomial above the line.}

    \For{$i \gets 1$ \textbf{to} $P$}{
    xcandidate $\gets 0.5*(\textrm{xright} + \textrm{x\_left})$\;
    ymonomial $\gets pow(\textrm{xcandidate}, N)$\;
    yline $\gets \textrm{xcandidate}\cdot m/2 -m+1$\;
    \eIf{$\textrm{ymonomial} \geq \textrm{yline}$}{
       xright $\gets \textrm{xcandidate}$\;
    }{
       xleft $\gets \textrm{xcandidate}$\;
    }
   }
   \tcc{Once again, we have narrowed down the search to the interval between `left' and `right'. The best we can do now is to output the middle point.}
   \KwRet{$0.5 \cdot \textrm{xright} + \textrm{xleft}$}
  }
\caption{Find the ratio of a geometric difference progression via bisections}
\label{algo:geometricratio}
\end{algorithm}
\end{minipage}
\end{fullwidth}\newpage}

Something else that should be in the same page as the stuff before, but goes to the next one if I uncomment the fullwidth/minipage solution, as proposed in https://tex.stackexchange.com/questions/553891/tufte-latex-full-width-algorithm2e-blocks

\end{document}


text:
Q: expectation and variance problem $n$ married couples (a total of 2n people) are randomly arranged in a line. Let $X$ be
the number of married couples that are standing next to each other. Compute the expectation
and variance of X
How can we solve this?
Is there any smart way to do this?

A: Write $X$ as a sum of simpler variables and use the linearity of expectation and the formula for the variance of a sum:
For $i=1,\ldots,n$ define
$$X_i=\cases{1, & if the $i$'th wife stands next to her husband \cr 0,& otherwise.} $$
 Then $X=\sum\limits_{i=1}^n X_i$.

Towards finding the expectation of $X$:
Note $\Bbb E(X_i)=\Bbb E(X_j)$ for all $i$, $j$.   We then have
$$\Bbb E(X)=\sum\limits_{i=1}^n \Bbb E(X_i) =n\Bbb E(X_1).$$

Towards finding the variance of $X$:
Use the formula (note the $X_i$ are not independent)
$$ \sigma^2(X)  = \sum\limits_{i=1}^{n} \sigma^2_{X_i} +   2\sum\limits_{i< j} {\rm Cov}(X_i,X_j)=n \sigma^2_{X_1} +n(n-1){\rm Cov}(X_1,X_2).$$
To compute $ {\rm Cov}(X_1,X_2)$, use the identity
$$ {\rm Cov}(X,Y)= \Bbb E(XY)-\mu_X\mu_ Y.$$
Towards finding $\Bbb E(X_1X_2)$, note that $X_1X_2$ is a Bernouili variable; so, $$\Bbb E(X_1X_2)=P[X_1X_2=1]=P[X_1=1,X_2=2]=P[X_1=1]\cdot P[X_2=1|X_1=1].$$
I'll leave it to you to compute the relevant quantities.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Weird problem on android webview with canvas I am draw some canvas charts on the android webview, and use javascript to change chart just by hiding and showing, and also change the title by reset its innerHTML.
The title is just a normal html tag  "

",
The problem is that the page does not render well when I switch charts, for example. when I choosed to display the next chart and change the title's innerHTML, the title seems 'remembered' its previous innerHTML and it looks like one text overlapped another.
If I manually change my phone's orientation, it seems make the webview redraw its content (not refresh), then everything will be fine.
Any idea on this? or can I simulate the orientation change event to make my webview redraw its page to work around it?

A: This issue seems to come up when you are using a transparent background with your webview. Try adding this into your CSS:
body {
    background-color:black;
}

Or whatever you wish your background color to be.

A: If you call invalidate() from within your View, you should get it to redraw itself.  When you have an orientation change, your View is invalidated with invalidate() which forces it to re-draw its contents.  You can use this invalidate() method to redraw your contents without changing the orientation.
invalidate() is a public method of your View and can be called anywhere it is in scope.


text:
Q: How to sort a specific column in multiple Google sheets I'd like to sort the forth column of more than one sheet in ascending order.
I can do this in the active sheet (sheet1), but can not figure out how to do it in the non-active sheets.
Below is my code.

function sort() {

   var bus = SpreadsheetApp.openByUrl("URI");
   var sheet = bus.getSheets()[0];

   sheet.sort(4,true);
}

A: Instead of getting just the first sheet, get all of them in a variable (notice the absence of the zero index - [0]):
var sheets = bus.getSheets();

Then iterate through all of them in a FOR loop:
for( sheet in sheets)
  sheets[ sheet ].sort(4,true);

That will sort every sheet in the active Spreadsheet, you can also open sheets by ID, URL, name and the position in Spreadsheet, to find the methods you want just read the documentation.


text:
Q: Function to join the first 2 elements from each list in a list of lists I have this list of lists:
listoflist = [['BOTOS', 'AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE', 'AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]

^^ That was just a example, I will have many more lists in my list of lists with the same format.
This will be my desired output:
listoflist = [['BOTOS AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]

Basically in each list I want to join first index with the second to form a full name in one index like in the example.
And I would need a function for that who will take a input a list, how can  I do this in a simple way? (I don't want extra lib for this). I use python 3.5, thank you so much for your time!

A: You can iterate through the outer list and then join the slice of the first two items:
def merge_names(lst):
   for l in lst:
      l[0:2] = [' '.join(l[0:2])]

merge_names(listoflist)
print(listoflist)
# [['BOTOS AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]

A: this simple list-comprehension should do the trick:
res = [[' '.join(item[0:2]), *item[2:]] for item in listoflist]

join the first two items in the list and append the rest as is.

A: You can try this:
f = lambda *args: [' '.join(args[:2]), *args[2:]]

listoflist = [['BOTOS', 'AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE', 'AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]

final_list = [f(*i) for i in listoflist]

Output:
[['BOTOS AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]

A: You can use a list comprehension as well:
listoflist = [['BOTOS', 'AUGUSTIN', 14, 'March 2016', 600, 'ALOCATIA'], ['HENDRE', 'AUGUSTIN', 14, 'February 2015', 600, 'ALOCATIA']]

def f(lol):
  return [[' '.join(l[0:2])]+l[3:] for l in lol]

listoflist = f(listoflist)
print(listoflist)
# => [['BOTOS AUGUSTIN', 'March 2016', 600, 'ALOCATIA'], ['HENDRE AUGUSTIN', 'February 2015', 600, 'ALOCATIA']]


text:
Q: How to set Element as ReadOnly by clicking outside the element I have an <input> element set to readonly by default:
<input readonly id="uniqueId" type="text" ondblclick="onDoubleClick(this.id)">

If the user double-clicks this element it will be set to editable with:
function onDoubleClick(id){
    var element = $('#'+id);
    if (element.prop('readonly')==true) { element.prop('readonly', false);}
    else { element.prop('readonly', true); }

Apparently this <input> element will stay editable up until the user double clicks it again. I wonder if I could link a mouse click that happens outside of the <input> element to turn it into readonly again. How to achieve it?

A: You can make any clicks on the document make the element readonly.

function onDoubleClick(id) {
  var element = $('#' + id);
  if (element.prop('readonly') == true) {
    element.prop('readonly', false);
  } else {
    element.prop('readonly', true);
  }
}

function inputClicked(e) {
    e.stopPropagation();
}

$(document).click(function() {
  $('#uniqueId').prop('readonly', true);
});
input[readonly] {
  background: lightgray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input readonly id="uniqueId" type="text" onclick="inputClicked(event)" ondblclick="onDoubleClick(this.id)">

A: Two approaches which I suggest
Method 1 - Using one
Add this inside your current function
$('html').one('click',function() {
    $("#uniqueId").prop('readonly', true);
  });

Explanation: when ever you double click and make the input editable The above script will attach one click event to HTML which makes the input read-only. This event works only once as we have used one.
So technically when ever you make the input editable a new event is attached which will make input read-only on further click.
Method 2 - Checking if the click was outside the element
Add this into your script.
$('html').on('click',function(e){
  if(!$(event.target).is('#uniqueId'))
  {
    $("#uniqueId").prop('readonly', true);
  }
});

Explanation: when ever there is a click on you HTML you will check if the click was on the input, If not then make it readonly.

A: One option is to add a blur event to the input box, so it will make field readonly even if user hits TAB and moves out of field.

$("input").on("blur", function() {
  $(this).prop('readonly', true);
})

function onDoubleClick(id) {
  var element = $('#' + id);
  if (element.prop('readonly') == true) {
    element.prop('readonly', false);
  } else {
    element.prop('readonly', true);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input readonly id="uniqueId" type="text" ondblclick="onDoubleClick(this.id)">

A: you could rely on the blur event to take action when it loses focus

function onDoubleClick(elem) {
  console.log('toggling readonly property');
  var element = $(elem);
  element.prop('readonly', !element.prop('readonly')); // toggle
}

function lostFocus(elem) {
  console.log('lostFocust');
  var element = $(elem);
  element.prop('readonly', true);
}
input {
  background-color: white;
}
input[readonly] {
  background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<input readonly id="uniqueId" type="text"  ondblclick="onDoubleClick(this)" onblur="lostFocus(this)">

A: No jQuery needed here since we already have access to the element when using the ondblclick handler, and you can add a function to the onfocusout or onblur event handler of your element:
<input readonly id="uniqueId" type="text" ondblclick="onDoubleClick(this)" onfocusout="onFocusOut(this)">

<script>
  function onDoubleClick(element){
    element.readOnly = !element.readOnly;
  }

  function onFocusOut(element) {
    element.readOnly = true;
  }
</script>

A: Same as the ondblclick attribute you can use the onblur attribute of the input element. It will run that function once that element gets blurred (out of focus).

function onDoubleClick(el) {
  var element = $(el);
  if (element.prop('readonly')==true) {
    element.prop('readonly', false);
  } else {
    element.prop('readonly', true);
  }
}
function onBlur(el) {
  $(el).prop('readonly', true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input readonly id="uniqueId" type="text" ondblclick="onDoubleClick(this)" onblur="onBlur(this)">


text:
Q: MD5 Hashing function outputs garbage I'm working on a C++ class, and we're learning about the MD5 hashing function.  I'm running into this issue however, where I do something like:
string input = "testInput";
unsigned char *toHash = new unsigned char[input.size()+1];
strcpy( (char*)toHash, input.c_str() );

unsigned char output[MD5_DIGEST_LENGTH];

MD5(toHash, input.size(), output);

cout << hex << output << endl;

But I always get some weird garbage characters instead of what I'm looking for, something like a long string of numbers / letters. What's going on?
~
Very confused by low level C++

A: Don't get fooled by the "unsigned char" type of the array, all that means here is that each value in the array is going to be an 8-bit unsigned integer.  In particular it doesn't imply that the data written to the array will be human-readable ASCII characters.
If you wanted to see the contents of the array in human-readable hex form, you could do this (instead of the cout command):
for (int i=0; i< MD5_DIGEST_LENGTH; i++) printf("%02x ", output[i]);
printf("\n");


text:
Q: Different buckets give different outputs at first time step during decoding Background
I'm trying to build a chat bot and have a basic understanding of tensorflow Sequence2Sequence API by reading from here:
https://www.tensorflow.org/tutorials/seq2seq/
I've also read related papers for Neural translation, attention mechanism during encoding/decoding etc.
RNN translate code is taken from here:
http@s://github.com/tensorflow/models/blob/master/tutorials/rnn/translate/seq2seq_model.py
Bucketing/Attention mechanism code is picked from here:
http@s://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/legacy_seq2seq/python/ops/seq2seq.py
During my training(attention mechanism, GRU cell), I gave my buckets as [(2,2),(4,4),(6,6),(,8,8),(10,10)].
Issue
During decoding, if I force a bucket_index on the same input I'm getting totally different outputs at the first time step. For example:
Input : How're you ?
Bucket index : 1
Output : NAME UNK NAME
Input : How're you ?
Bucket index : 2
Output : Hi NAME to the
Observations
I can fix the bad outputs at each time step using beam-search. However, why I'm getting different word as output at the first time step during decoding ? Shouldn't the smaller bucket output be a subset of larger bucket output ?
I've tried searching online and everywhere it's mentioned that parameters are shared across various buckets. Buckets are used for training efficiency and not for model tuning. I've also verified that my trainable parameters are common across all the buckets.
The biggest difference I can see between encoder inputs for various buckets is the extra padding at the very start. We are doing attention mechanism on encoded_states, and softmax weights are already learned for those encoded states during training. Therefore, Can those softmax weights for those extra padded inputs cause sufficient difference leading to different output during first time step of decoding ?
Did any one else also encounter the above issue? Any help for fixing the above error would be greatly appreciated.
I've also opened an issue here because I'm unsure whether it is a bug(file on github), or my mis-understanding(Stackoverflow):
https://github.com/tensorflow/tensorflow/issues/7561

A: I am not sure if you have figured out an answer for this. I would like to comment on this in case someone else wants an idea on this.
I believe this is the expected behavior. If you check the source implementation of model_with_buckets function in TensorFlow, you see roughly the following lines of code:
for j, bucket in enumerate(buckets):
    with variable_scope.variable_scope(
        variable_scope.get_variable_scope(), reuse=True if j > 0 else None):
        bucket_outputs, _ = seq2seq(encoder_inputs[:bucket[0]],
                                    decoder_inputs[:bucket[1]])
        outputs.append(bucket_outputs)

If you use 5 buckets, then this above outputs list will contain 5 sub-lists. In each of sub-list, it contains the decoder_outputs for each bucket. This outputs will be returned, and will be used both for training and prediction. You can see that each decoder_output (singular form) in different buckets are normally different as they are trained to generate outputs that match different targets for different buckets (although the variables in different buckets are re-used).
One interesting test you can do is: add to your training set a pair with short question but long answer (make sure your model is big enough to remember almost every training samples). This means, this pair will use a larger bucket in the training, but a smaller bucket in the prediction. You also need a mechanism to type in your pad token in string format, say, pad. After your model is trained, perform such a prediction test. Type in the original answer, you will very likely get a totally different/meaningless answer. However, you then type in your question followed with a number of pad until the input sentence is long enough so that the desired bucket can be chosen. You will then very likely get the same exact answer in that new training pair.
Hope this explanation makes sense.


text:
Q: Proper way to define type (typedef vs #define) Which of these methods is more secure for defining variable types? I know that we all frown when we see #defines, but it seems to work just as well as typedef here:
Is there an advantage one way or the other, and if so what might it be?
Method One:
    #include <iostream>

    #define byte unsigned char

    int main() {
        byte testByte = 'A';
        std::cout << testByte << std::endl;

        return 0;
    }

Method Two:
     #include <iostream>

     int main() {
        typedef unsigned char byte;

        byte testByte = 'A';
        std::cout << testByte << std::endl;

        return 0;
    }

A: Only one of your examples actually is a way to define a type, so there's no contest between them.

#define byte unsigned char

This just makes all utterances of byte in your code get replaced with unsigned char before compilation begins. It does not define a type.
The declaration int byte; will become int unsigned char;, which is nonsense.

typedef unsigned char byte;

This defines a type. The type will be subject to syntax rules, scoping rules and all of that lovely stuff.
The declaration int byte; will still be the declaration int byte;, because byte here is found in the space for a variable name.

using byte = unsigned char;

This is the "modern" way to define a type alias, which has much clearer syntax than a typedef statement (especially for more complex types).
It was introduced because otherwise the new syntax for template type aliases would have been next to impossible to make sane.

A: You should always use the 2nd one (i.e. typedef or using).
Try to not use macros in c++ as far as possible, and most cases could be avoided. They're just text replacement before compiling, and more "dangerous". e.g.
#define byte_pointer unsigned char*
byte_pointer p, q; // only p is a pointer

A: Using #define is not safe (see other answer)
Using typedef is the usual way to define types aliases.
There's also the new "using" syntax
using MyByte = unsigned char;

see this answer to a related question (typedef vs. using) https://stackoverflow.com/a/10748056/446303

A: Go with the typedef. There are many reasons, but the first one that comes to mind is that the typedef applies to the scope where it is declared, but the #define ignores scope and applies to the remainder of whatever source module it is defined in. For that reason alone, the typedef is "safer".


text:
Q: How to create multiple mysql tables with MySQLdb in python? This is what i am trying to do:
cursor.execute("CREATE DATABASE testing")
cursor.execute("USE testing")
cursor.execute("CREATE TABLE Contract(mEnd varchar(7))")
cursor.execute("CREATE TABLE User(uName varchar(15)")

When I run the python script using MySQLdb it only creates the first table and it ignores all the other lines of code.

A: ) is missing in your last statement. Though you really don't want to do it this way.

A: Try the following
execute = ["CREATE DATABASE testing","USE testing","CREATE TABLE Contract(mEnd varchar(7))","CREATE TABLE User(uName varchar(15))"]
for i in execute:
    cussor.execute(i)
    cussor.commit()


text:
Q: ViewController not properly sending over NSURL data to Destination ViewController When a user taps a cell, I want itemURL to be set to that cells "Item URL" property. Once it does this, it should then send over the itemURL in prepareForSegue over to WebViewController, as I've attempted to do. When I have WebViewController NSLog the itemURL property however, it comes up as null. How can I make sure the value is sent over properly?
MatchCenterViewController.h:
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "AsyncImageView.h"
#import "SearchViewController.h"
#import "WebViewController.h"

@interface MatchCenterViewController : UIViewController <UITableViewDataSource>

@property (nonatomic) IBOutlet NSString *itemSearch;

@property (nonatomic, strong) NSArray *imageURLs;
@property (strong, nonatomic) NSString *matchingCategoryCondition;
@property (strong, nonatomic) NSString *matchingCategoryLocation;
@property (strong, nonatomic) NSNumber *matchingCategoryMaxPrice;
@property (strong, nonatomic) NSNumber *matchingCategoryMinPrice;

@property (strong, nonatomic) NSArray *matchCenterArray;
@property (strong, nonatomic) NSString *searchTerm;

@property (strong, nonatomic) NSURL *itemURL;

@end

MatchCenterViewController.m:
#import "MatchCenterViewController.h"
#import <UIKit/UIKit.h>

@interface MatchCenterViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *matchCenter;
@end

@implementation MatchCenterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.matchCenter = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewCellStyleSubtitle];
    self.matchCenter.frame = CGRectMake(0,50,320,self.view.frame.size.height-100);
    _matchCenter.dataSource = self;
    _matchCenter.delegate = self;
    [self.view addSubview:self.matchCenter];

    _matchCenterArray = [[NSArray alloc] init];
}

- (void)viewDidAppear:(BOOL)animated
{
    self.matchCenterArray = [[NSArray alloc] init];

    [PFCloud callFunctionInBackground:@"MatchCenter"
                       withParameters:@{
                                        @"test": @"Hi",
                                        }
                                block:^(NSArray *result, NSError *error) {

                                    if (!error) {
                                        _matchCenterArray = result;
                                        [_matchCenter reloadData];

                                        NSLog(@"Result: '%@'", result);
                                    }
                                }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _matchCenterArray.count;
}

//the part where i setup sections and the deleting of said sections

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 21.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 21)];
    headerView.backgroundColor = [UIColor lightGrayColor];

    _searchTerm = [[[[_matchCenterArray  objectAtIndex:section] objectForKey:@"Top 3"] objectAtIndex:3]objectForKey:@"Search Term"];

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 250, 21)];
    headerLabel.text = [NSString stringWithFormat:@"%@", _searchTerm];
    headerLabel.font = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
    headerLabel.textColor = [UIColor whiteColor];
    headerLabel.backgroundColor = [UIColor lightGrayColor];
    [headerView addSubview:headerLabel];

    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteButton.tag = section;
    deleteButton.frame = CGRectMake(300, 2, 17, 17);
    [deleteButton setImage:[UIImage imageNamed:@"xbutton.png"] forState:UIControlStateNormal];
    [deleteButton addTarget:self action:@selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:deleteButton];
    return headerView;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Initialize cell
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        // if no cell could be dequeued create a new one
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    // No cell seperators = clean design
    tableView.separatorColor = [UIColor clearColor];

    // title of the item
    cell.textLabel.text = _matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Title"];
    cell.textLabel.font = [UIFont boldSystemFontOfSize:14];

    // price of the item
    cell.detailTextLabel.text = [NSString stringWithFormat:@"$%@", _matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Price"]];
    cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f];

    // image of the item
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Image URL"]]];
    [[cell imageView] setImage:[UIImage imageWithData:imageData]];

    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSURL *itemURL = _matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Item URL"];

//    NSLog(@"The url is: '%@'", itemURL);

    [self performSegueWithIdentifier:@"WebViewSegue" sender:self];
}

- (void)deleteButtonPressed:(id)sender
{
    // links button
    UIButton *deleteButton = (UIButton *)sender;

    // Define the sections title
    NSString *sectionName = _searchTerm = [[[[_matchCenterArray  objectAtIndex:deleteButton.tag] objectForKey:@"Top 3"] objectAtIndex:3]objectForKey:@"Search Term"];

    // Run delete function with respective section header as parameter
    [PFCloud callFunctionInBackground:@"deleteFromMatchCenter"
                       withParameters:
                      @{@"searchTerm": sectionName,}
                                block:^(NSDictionary *result, NSError *error) {
                                   if (!error) {
                                       [PFCloud callFunctionInBackground:@"MatchCenter"
                                                          withParameters:@{
                                                                           @"test": @"Hi",
                                                                           }
                                                                   block:^(NSArray *result, NSError *error) {

                                                                       if (!error) {
                                                                           _matchCenterArray = result;
                                                                           [_matchCenter reloadData];

                                                                           NSLog(@"Result: '%@'", result);
                                                                       }
                                                                   }];

                                   }
                                }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

 #pragma mark - Navigation

 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {

     WebViewController *controller = (WebViewController *) segue.destinationViewController;
     controller.itemURL = self.itemURL;

 }

@end

WebViewController.h:
#import <UIKit/UIKit.h>
#import "MatchCenterViewController.h"

@interface WebViewController : UIViewController <UIWebViewDelegate>

@property (strong, nonatomic) NSURL *itemURL;
@property (weak, nonatomic) IBOutlet UIWebView *myWebView;

@end

WebViewController.m:
#import "WebViewController.h"

@interface WebViewController ()

@end

@implementation WebViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"The url is: '%@'", _itemURL);

//    _myWebView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
//    _myWebView.delegate=self;
//    [self.view addSubview:_myWebView];

    self.myWebView.delegate = self;

    //////////
    NSURLRequest *request = [NSURLRequest requestWithURL:_itemURL];
    //4
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    //5
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
     {
         if ([data length] > 0 && error == nil) [self.myWebView loadRequest:request];
         else if (error != nil) NSLog(@"Error: %@", error);
     }];

    [self.myWebView setScalesPageToFit:YES];
    //////

    //[self.myWebView loadRequest:request];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

A: In your didSelectRowForIndexPath: instead of
NSURL *itemURL = _matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Item URL"];

use
self.itemURL = _matchCenterArray[indexPath.section][@"Top 3"][indexPath.row][@"Item URL"];


text:
Q: How does binding two slider XAML control values together work? I made a simple blank metro store app in VS2012 and added two sliders in a StackPanel, like this:
<StackPanel>
     <Slider Name="sliderTest1" Value="{Binding ElementName=sliderTest2, Path=Value}" />
     <Slider Name="sliderTest2" Value="{Binding ElementName=sliderTest1, Path=Value}" />
</StackPanel>

I expected that sliding either slider would cause them both to move. And that's true as long as I've only touched one slider. As soon as I touch the other slider, they no longer move together.
Why is that?

A: You just need to add Mode=TwoWay to the bindings -- that will cause each to update the other.
<Slider Name="sliderTest1"
    Value="{Binding ElementName=sliderTest2, Path=Value, Mode=TwoWay}" />


text:
Q: IB and UIView. What is the correct way to load a view hierarchy from a nib? Can someone please school me on the proper way to load a view hierarchy from a nib file. I am using the loaded view as a template to stamp out a family of views and the current approach I am using is subtly broken. I don't appear to be copy-ing or retain-ing when I should be. Here's the relevant code:
// pageSet is a list of view tag numbers I'll be using
for (NSNumber *n in pageSet) {

    NSUInteger viewTag = [n integerValue];

    // Ingest the nib. Should there be a copy or retain here?
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"RandomStripe" owner:self options:nil];

    // Pull the view from the nib. Should there be a copy or retain here?
    MyView *view = (MyView *)[topLevelObjects objectAtIndex:0];

    // The view has a label as it's subview
    UILabel *pageNumberLabel = [view.subviews objectAtIndex:0];
    pageNumberLabel.text     = [NSString stringWithFormat:@"%d", viewTag];

    CGFloat xOffset = ((float) viewTag) * self.scrollView.bounds.size.width;

    view.frame = CGRectMake(xOffset, 0, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height);
    view.tag = viewTag;

    // Insert the view as a child of my containerView
    [self.containerView addSubview:view];

} // for (pageSet)

This has be making my head hurt for while now?
Cheers,
Doug

A: If you use IBOutlets from within Interface Builder back to your code, things would be a little easier.  That way as soon as you try to access the UIView outlet you have set up, it gets loaded, with all its children, and then the UIView's initWithCoder will get called (useful if you have subclassed it).
@property (retain, nonatomic) IBOutlet iiView   *iiView;

Otherwise, I do this:
if (self.numberView == nil) {
    NumberView  *numView = [[NumberView alloc] initWithNibName:@"NumberView" bundle:[NSBundle mainBundle]];
    self.numberView = numView;
    [numView release];
}

(With an IBOutlet for numberView, I just go ahead and start using numberView instead of the code above)
In both conditions, all the subviews - the children - of numberView will get loaded at the same time.  If I needed to access a label or button I would do an IBOutlet for those too so I won't have to traverse the view hierarchy looking for them.
IBOutlet UIButton *nextButton,
          *stopButton1,
          *stopButton2,
          *infoButton,
          *bitsonthegoButton;
IBOutlet UILabel *pointsLabel1,
         *pointsLabel2,
         *totalPointsLabel1,
         *totalPointsLabel2;

A: I wasn't sure if the other answer was exactly clear on this point, but any IBOutlets you set up on your view will get wired in with that same loadNibNamed: call you are doing today.  So in the header for that view, you'd declare IBOutlets for both myView and pageNumberLabel, then attach them to the File's Owner in the xib (and set File's Owner type to be the view you are calling loadNibNamed: from).
That's just to make your life easier.  To answer the question you asked, the documentation for "loadNibNamed:owner:options" tells us:

You should retain either the returned
  array or the objects it contains
  manually to prevent the nib file
  objects from being released
  prematurely.

So the array is autoreleased, and all the objects in it are as well (which you would expect from a call returning an autoreleased array).  Since you want to keep the view you would retain that - doing so would mean any subviews of the main view would be kept around as well, since a view will retain anything set as a subview.  If you also retained the label that would cause a leak when you released the main view unless you also release the label at the same time (but there seems no point in doing that).
However note that when I say "retain the view", you are already doing so in the code you posted, simply by adding it as a subview to your container view - as noted the view retains subviews.  MyView will be released if it's ever removed from the subview, so you'd want to retain it if you do that for any reason and want it kept around.
Nib loading memory management seems complex at first, but the rules are actually much simpler than it would seem.


text:
Q: Ember evented on error: Assertion Failed: on called without valid event names I have a controller in my ember 2.18 app and I want to make it listen to some event myEventName triggered somewhere in the app, to change the model properties.
According to the API docs for this version the way to catch an emitted event is like this:
import Evented from '@ember/object/evented';
import Controller from '@ember/controller';
// extend some object, like a Controller
const myExtendedObject = Controller.extend(Evented, {
    // stuff ...
     });

myExtendedObject.on('myEventName', function (args) {
    console.log("catch importDone  ok", args);
    });
export default myExtendedObject;

the code compiles well with ember build dev,
but in the browser's JS console I get this error message:

Error: Assertion Failed: on called without valid event names error.js:40

I tried renaming event, but I cannot find why the event name is wrong.
I also tried to set three arguments to the on method, but it is still bugging with the event name.
What am I missing?
Edit:
I made an Ember twiddle showing that events are scoped to components.
I would like to catch them from anywhere;
like triggering an event from a Service and catch it in a Route.
https://ember-twiddle.com/ce22cc0a542e8e0997a1ad57a4a9688c?fullScreen=true

A: You can use it like this:
import { on } from '@ember/object/evented';

export default Controller.extend(Evented, {
  init() {
    this._super(...arguments);
    this.trigger('greet');
  },

  myGreetImplementation: on('greet', function() {
    console.log('hello');
  })
});

Another example: Using a service to manage the user settings and subscribing to changes:
export default Service.extend(Evented, {
  ...
  changeProfilePicture() {
    ...
    this.trigger('profilePictureChanged', ... event parameters ...);
  }
});

Then you could watch for such event anywhere using the on method:
 export default Controller.extend({
  userSettings: service(),

  init() {
    this._super(...arguments);
    this.get('userSettings').on('profilePictureChanged', this, this.profilePictureChanged);
  },

  profilePictureChanged(... event parameters ...) {
   ...
  }
});

There error you get is coming from here:
https://github.com/emberjs/ember.js/blob/6fc89cdf13124d88b8ae6adf99bb02a8c0cdf508/packages/ember-metal/lib/events.ts#L211
(You can just paste error messages in the github search or use the debugger to find out more about why something is failing)

Update: Extending your twiddle to have the Controller register on the service's event:
import Ember from 'ember';
import { inject as service } from '@ember/service';
import { on } from '@ember/object/evented';

export default Ember.Controller.extend({
  appName: 'Ember Twiddle',
  myService: service(),
  init() {
    this._super(...arguments);
    this.get('myService').on('mycall', this, this.mycallHandler);
  },
  mycallHandler: on('mycall', function() {
    console.log('here we are');
  })
});


text:
Q: How can I create a desktop shortcut for "Listen to this device"? In windows, there is a way to make audio from your input go to your output, by checking "Listen to this device". Is there a way to make a desktop shortcut or start menu shortcut that enables/disables this for a certain device?
On Linux mint I use
gst-launch pulsesrc ! pulsesink

in a launcher (Linux Mint), and I'm basically wondering how to do something similar in windows.
I know I sound lazy, but I want to do this pretty fast sometimes.


text:
Q: get row with className How can you get the first row in a table with a specific className?
var rows = $('tr', tbl);

A: var rows = $('tr.classname:first', tbl);

or
var rows = $('tr.classname', tbl).first();

Docs here: http://api.jquery.com/category/selectors/

A: var firstRow = $('tr.classname:first', tbl)

A: You can use the :first selector along with the class selector,
Try this:
var rows = $('tr.someclass:first', tbl);

A: var row = $("tr.className:first", tbl); should do the trick.

A: If you keep the proprietary :first selector out of it, you'll have a valid querySelectorAll selector.
var rows = tbl.find('tr.someClass').slice( 0, 1 );

or
var rows = tbl.find('tr.someClass').eq( 0 );

Also, using the context parameter $( selector, context ) is just a slower way of using the find()[docs] method.

A: You can even use eq method of jquery if you want to loop through a list of elements.
var rows = $('tr.classname');
rows.eq(0);//first row
rows.eq(1);//second row


text:
Q: C++ GLSL shaders: "error: GLSL 3.30 is not supported. Supported versions are: 1.10, 1.20, 1.30, 1.00 ES, and 3.00 ES" or black window I'm added in my simple OpenGL project very simple GLSL shaders, and it not working.
#include <python3.6m/Python.h>
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <vector>
#include <fstream>
#include <sstream>

using namespace glm;

GLuint LoadShaders(const char * vertex_file_path, const char * fragment_file_path){

    // Создаем шейдеры
    GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
    GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);

    // Загружаем код Вершинного Шейдера из файла
    std::string VertexShaderCode;
    std::ifstream VertexShaderStream(vertex_file_path, std::ios::in);
    if (VertexShaderStream.is_open()) {
        std::stringstream sstr;
        sstr << VertexShaderStream.rdbuf();
        VertexShaderCode = sstr.str();
        VertexShaderStream.close();
    }

    // Загружаем код Фрагментного шейдера из файла
    std::string FragmentShaderCode;
    std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in);
    if (FragmentShaderStream.is_open()){
        std::stringstream sstr;
        sstr << FragmentShaderStream.rdbuf();
        FragmentShaderCode = sstr.str();
        FragmentShaderStream.close();
    }

    GLint Result = GL_FALSE;
    int InfoLogLength;

    // Компилируем Вершинный шейдер
    printf("Компиляция шейдера: %s\n", vertex_file_path);
    char const * VertexSourcePointer = VertexShaderCode.c_str();
    glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
    glCompileShader(VertexShaderID);

    // Выполняем проверку Вершинного шейдера
    glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
    glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
    if ( InfoLogLength > 0 ){
        std::vector<char> VertexShaderErrorMessage(InfoLogLength+1);
        glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
        fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]);
    }

    // Компилируем Фрагментный шейдер
    printf("Компиляция шейдера: %s\n", fragment_file_path);
    char const * FragmentSourcePointer = FragmentShaderCode.c_str();
    glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
    glCompileShader(FragmentShaderID);

    // Проверяем Фрагментный шейдер
    glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
    glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
    if ( InfoLogLength > 0 ){
        std::vector<char> FragmentShaderErrorMessage(InfoLogLength+1);
        glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]);
        fprintf(stdout, "%s\n", &FragmentShaderErrorMessage[0]);
    }

    // Создаем шейдерную программу и привязываем шейдеры к ней
    fprintf(stdout, "Создаем шейдерную программу и привязываем шейдеры к ней\n");
    GLuint ProgramID = glCreateProgram();
    glAttachShader(ProgramID, VertexShaderID);
    glAttachShader(ProgramID, FragmentShaderID);
    glLinkProgram(ProgramID);

    // Проверяем шейдерную программу
    glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
    glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
    if (InfoLogLength > 0) {
        std::vector<char> ProgramErrorMessage(InfoLogLength+1);
        glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
        fprintf(stdout, "%s\n", &ProgramErrorMessage[0]);
    }

    glDeleteShader(VertexShaderID);
    glDeleteShader(FragmentShaderID);

    return ProgramID;
}

int main(int argc, char *argv[]) {
    // Инициализируем GLFW
    if (!glfwInit()) {
        fprintf( stderr, "Ошибка при инициализации GLFW\n" );
        return -1;
    }
    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_SAMPLES, 4);  // Включаем сглаживание
    glEnable(GL_MULTISAMPLE);
//    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Мы хотим использовать OpenGL 3.3
//    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

//    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
//    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Мы не хотим старый OpenGL

    // Открыть окно и создать в нем контекст OpenGL
    GLFWwindow* window; // (В сопроводительном исходном коде эта переменная является глобальной)
    window = glfwCreateWindow(1024, 768, "Tutorial 01", NULL, NULL);
    if (window == NULL) {
        fprintf( stderr, "Невозможно открыть окно GLFW. Если у вас Intel GPU, то он не поддерживает версию 3.3. Попробуйте версию уроков для OpenGL 2.1.\n" );
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

//     Инициализируем GLEW
    glewExperimental=true; // Флаг необходим в Core-режиме OpenGL
    if (glewInit() != GLEW_OK) {
        fprintf(stderr, "Невозможно инициализировать GLEW\n");
        return -1;
    }

    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    // Массив 3 векторов, которые являются вершинами треугольника
    static const GLfloat g_vertex_buffer_data[] = {
            -1.0f, -1.0f, 0.0f,
            1.0f, -1.0f, 0.0f,
            0.5f,  1.0f, 0.0f,
    };

    // Это будет идентификатором нашего буфера вершин
    GLuint vertexbuffer;

// Создадим 1 буфер и поместим в переменную vertexbuffer его идентификатор
    glGenBuffers(1, &vertexbuffer);

// Сделаем только что созданный буфер текущим
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);

// Передадим информацию о вершинах в OpenGL
    glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);

    // Включим режим отслеживания нажатия клавиш, для проверки ниже
    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

    // Создать и откомпилировать нашу шейдерную программу
    GLuint programID = LoadShaders( "SimpleVertexShader.vertexshader", "SimpleFragmentShader.fragmentshader" );

    do {
//        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        // Устанавливаем наш шейдер текущим
//        glUseProgram(programID);

        // Рисуем треугольник...

        // Указываем, что первым буфером атрибутов будут вершины
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glVertexAttribPointer(
                0,                  // Атрибут 0. Подробнее об этом будет рассказано в части, посвященной шейдерам.
                3,                  // Размер
                GL_FLOAT,           // Тип
                GL_FALSE,           // Указывает, что значения не нормализованы
                0,                  // Шаг
                (void*) nullptr     // Смещение массива в буфере
        );

// Вывести треугольник!
        glDrawArrays(GL_TRIANGLES, 0, 3); // Начиная с вершины 0, всего 3 вершины -> один треугольник

        glDisableVertexAttribArray(0);

        // Сбрасываем буферы
        glfwSwapBuffers(window);
        glfwPollEvents();

    } // Проверяем нажатие клавиши Escape или закрытие окна
    while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
           glfwWindowShouldClose(window) == 0);
}

I see black window (if I write
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

else i see errors:
Compiling shader: SimpleVertexShader.vertexshader
0:1(10): error: GLSL 3.30 is not supported. Supported versions are: 1.10, 1.20, 1.30, 1.00 ES, and 3.00 ES
*Compiling shader: SimpleFragmentShader.fragmentshader *
Creating shader programm and linking...
error: linking with uncompiled/unspecialized shader
)
Vertex shader:
#version 300 es

layout(location = 0) in vec3 vertexPosition_modelspace;

void main(){
    gl_Position.xyz = vertexPosition_modelspace;
    gl_Position.w = 1.0;
}

Fragment shader:
#version 300 es
precision mediump float;
layout(location = 0) out vec3 color;

void main() {
    color = vec3(1,0,0);
}

A:
GLuint programID = ...

You mihght actually sucessfully create and link your program object, but you never activate it. You have to add glUseProgram(programID) somewhere before your draw call.


text:
Q: Where is sulfur found when using Railcraft? Title says it all, really.
When using Railcraft, where can sulfur be found?

A: I've found a few hints that may point you in the right direction. From the patch notes:

NEW: Sulfur and Saltpeter, in the hills yellow and hot, and in the
  darkness beneath the parched sky.

From a list of coding thanks for another mod:

CovertJaguar - For helping me with sulfur generation around lava and
  Railcraft compatibility!

These make me think that you may find sulfur around pools of lava on the surface.

A: After some nuke-based prospecting and using the hints provided by SaintWacko, I've managed to find the answer:
Sulfur spawns near underground lava lakes in ExteremeHills biomes.
Plentiful when present, but the conditions can be hard to come by.


text:
Q: Does "cafe" relate to the word "cafeteria?" I know that the word cafe (referring to a place to go eat) stems directly from the same word in French meaning coffee, but what etymological connection does it have with the English word cafeteria? The two words have different connotations in English but I wonder if cafeteria and cafe share a closer background or snynonymity (either in English or Fench) or if one's usage predates the other's.
General reference resources vary about the details, especially as concerns the origins of cafeteria. Merriam Webster, with reference to cafeteria in the sense of "a restaurant in which the customers serve themselves or are served at a counter and take the food to tables to eat" and in the sense of "lunchroom", says the origins are

American Spanish cafetería coffeehouse, from cafetera coffee maker, from French cafetière, from café.
First Known Use: 1894.

Merriam gives the first known use of cafeteria as a adjective in the sense of "providing a selection from which a choice may be made" as 1908.
Random House (at Dictionary.com), for noun senses similar to those given by Merriam, says the origin is earlier:

1830-40, Americanism; < American Spanish cafetería café, equivalent to Spanish cafeter(a) coffeemaker (< French caf(f) etière; café coffee + -ière, feminine of -ier -ier2; t apparently by analogy with words such as bouquetière flower seller, from bases ending in t) + -ía -ia.

Wiktionary is very loose about the date of origin for cafeteria, but provides a more detailed description of the language origins:

(Mid 19th or 20th century) American Spanish cafetería ("coffeehouse"), from cafetera ("coffee maker"), from French cafetière, from café, from Ottoman Turkish قهوه (kahve) (Turkish kahve), from Arabic قَهْوَة (qahwa, "coffee").

A: Café
The origin and history of 'café' in English seems at first blush to be straightforward, well understood and well documented. For example, OED, in an entry not fully updated after its first publication in the 1888 edition, provides this account of the meaning of 'café' and its introduction into English from French:

A coffee-house, a restaurant; strictly a French term, but in the late 19th c. introduced into the English-speaking countries for the name of a class of restaurant.  [Emphasis mine.]

Note the "late 19th" century attribution; presumably "late 19th c." means sometime before the 1888 date of first publication. (The previous, 1989 version of the entry uses the same wording; earlier versions of the entry are not available to me.)
OED follows with quotation evidence starting from 1802 (an earlier 1789 quotation is bracketed, indicating the English quotation includes café in French). The entry profile, however, suggests quotation evidence from 1763 ("first cited in Horace Walpole") was at one time part of the entry, but was corrected for the 1989 edition.
The 1802, 1815, and 1851 attestations of 'café' (not italicized) are likely cases OED considered "strictly" French. The 1870 attestation from D.J. Kirwan's Palace & Hovel, an account of an American's visit to London, most likely was not considered "strictly" French.
All that suggests 1870 was the date OED considers 'café' was "introduced" into English with the sense of "a class of restaurant". That date does not antedate the first OED attestation of 'cafeteria' in English, 1839. Nonetheless, the French term café could well have influenced the development of 'cafeteria'; the question is how and when, and whether other language influences were more prominent.
Cafeteria
'Cafeteria' has an oddly convoluted and difficult history in English. This history is not credited by OED's treatment, which starts by misdating what they provide as the first attestation, from 1839. Etymology Online perpetuates that misdating to 1839, I surmise, but does not provide the attestation for the 1839 date given, and so is not easily faulted.

cafeteria, n.
  ....
Etymology: < American-Spanish cafetería coffee-shop.
  orig. U.S.
  A coffee-house; a restaurant, esp. now a self-service restaurant.
1839   J. L. Stephens Trav. Russian & Turkish Emp. I. 157   Every third shop, almost, being a cafteria [sic] where a parcel of huge turbanded fellows were at their daily labours of smoking pipes and drinking coffee.
1894   Lakeside Directory Chicago 2188   Cafetiria Catering Co. 45 Lake.
OED

As mentioned, 1839 is not correct; the Stephens work was first serialized in 1836, in The American Monthly Magazine, v. 8. That serialization included several references to 'cafteria' (pp 482-4, 486), the context of which suggests these 'cafteria' were Turkish group lodgings where locals and travelers gathered to smoke, drink coffee, and sleep.
Additionally, but inconsequentially, the later publication of Stephens work in book form took place in 1838 (New York), rather than 1839. In that publication, 'cafteria' appears twice (pp 35, 156), and the context suggests a use in the sense of 'a class of restaurant', that is, the same sense accorded to the later, 1870, English term 'café'.
Antedating 'Cafeteria'
The OED attestation from 1839, and the slightly earlier appearances of 'cafeteria' in works by the same author are not, however, the earliest appearances of the term in English. Earlier appearances suggest the word entered English not from American-Spanish, but rather from Spanish or Italian (Castel Nuovo is in Naples, Italy).
In The Eclectic Review of 1833, this mention is made:

...the Spaniard's lemonade is tasteless unless he can sip it in the accustomed Caffeteria...

And in The London Literary Gazette of 1829, in an exerpt from an 1828 work (Reisen in Egypten, &c. Travels in Egypt, Libya, Nubia, and Dongola, Between the Years 1820-1825, W.F. Hemprich and C.G. Ehrenberg), this:

...nor can I ever forget the five living Rolandos whom I saw standing in the caffeteria of Castel Nuovo...

Although neither of the attestations provides enough context to reliably ascertain the nature of the Spanish or Italian 'caffeteria', it seems clear that such were, generally, coffeehouses or "a class of" restaurants.
These attestations demonstrate that 'caffeteria' was in use in British English, with a sense at least similar to 'café', before it was adopted from American-Spanish into US English and began its progress toward the contemporary sense of 'self-service restaurant'.
Another Consideration
Noting the 55 (or more accurately, 58) year gap between the first and second OED attestations, I made shift to fill it. This was not so easily accomplished.
In an 1870 work, Italy: Handbook for Travellers, by K. Bædeker, I found this, where 'Caffeteria' is obviously Italian, in the section listing establishments of interest to tourists in Bologna:

Cafés. ...Beer: Birraria e Caffeteria della Ditta Neviani in the side passage of the Piazza, E. of S. Petronio...

Cafeteria in US English
I found no uses of 'cafeteria' (or variants) in British or US English between 1839 and 1894. Numerous uses of 'cafetiere', meaning coffeepot, do appear, but do not seem on point for this answer.
Looking at the 1894 uses of 'cafeteria' did provide some interesting background, although the credibility of the claims made by the complainant in this March, 1894 newspaper article (The Inter Ocean, Chicago, Illinois, p 10; paywalled) has been undermined by the foregoing attestations of 'caffeteria' in English, possibly Spanish, and Italian:

John Kroger, the proprietor of the "Cafeteria" Catering Company, has filed a bill in the Circuit Court to restrain W. H. Dittmer from using the name "Cafetier" in connection with the latter's restaurant. The bill says that the complainant adopted the name "Cafeteria" as a fanciful and arbitrary name for his business, although he says that the word has no descriptive meaning, and is not found in any language.

Also of passing interest is this April, 1894 (The Worthington Advance, Worthington, Minnesota, p 6; paywalled) description, which makes plain that the sense of 'cafeteria' as "a self-service restaurant" has been established:

These new places are called cafetiria, or cafetier, or cafelakota, or buffetiria, or some other meaningless variation on a common name, and their motto is every man is his own waiter.

A: YES, the terms derive from Italian caffè
Cafeteria  is a more recent AmE term of Spanish influence:
cafe (n.) :

*

*1802, from French café "coffee, coffeehouse," from Italian caffe "coffee"  (see coffee).

*The beverage was introduced in Venice by 1615 and in France from 1650s by merchants and travelers who had been to Turkey and Egypt. The first public café might have been the one opened in Marseilles in 1660.

Coffee:

*

*Introduced to England by 1650, and by 1675 the country had more than 3,000 coffee houses. Coffee plantations established in Brazil 1727.

*Meaning "a light meal at which coffee is served" is from 1774. Coffee break attested from 1952, at first often in glossy magazine advertisements by the Pan-American Coffee Bureau. Coffee pot from 1705.

Cafeteria:

*

*1839, American English, from Mexican Spanish cafeteria "coffee store," from café "coffee" (see coffee) + Spanish -tería "place where something is done" (usually business).

*The ending came to be understood popularly as meaning "help-yourself" (as though café + -teria) and was extended to new formation with that sense from c. 1923.

(Etymonline)

A: What seems to be missing from all the other answers is the meaning of the suffix -eria.
In Italian, the -eria suffix can mean "a place connected with". So a pizzeria sells pizza and a gelateria sells gelato.
In Spanish, the -ería suffix means "a place that sells something." So a heladería is an ice cream parlor and a florería is a florist.
So cafetería (in Spanish) etymologically means a place you could buy and drink coffee. I don't know why there's an extra "t" in it; that is, why isn't it simply cafería.  It may be because cafetera means coffee-pot in Spanish. Wiktionary thinks the extra "t" in cafetera was influenced by the "t" in tetera (teapot). And presumably there's an extra "t" in tetera because you te is a one-syllable word in Spanish, so you need to add a consonant when you add the suffix -era.

A: Brazil exports coffee to England since the XVI century, maybe some portuguese words can be helpful to understand the question:
Cafezal: Coffee plantation (where farmers work)
Café da manhã: breakfast (which includes café)
Cafeteria: place where the workers eat, including "café da manhã"
Cafeteira: coffee jar
As a Portuguese speaker, all these words seem totally related.


text:
Q: Unable to export list of external email recipient using Get-MessageTrackingLog as Sender@domain.com.CSV? I cannot export the list of the external recipient email address and its total number of email based on multiple inputs of the InternalSender.CSV list:
Email
John.Larkin@domain.com
Breville.May@domain.com
Katie.Brunetti@domain.com
Anna.Belle@domain.com

This is the script code:
Import-PSSession (New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://VM-MAILSVR01/PowerShell/ -Authentication Kerberos) -AllowClobber

$resultFile = 'C:\TMP\Results.CSV'
$inputFile = 'C:\TMP\InternalSender.csv'

$trackparams = @{
    $start = "2018-08-01 12:01 AM"
    $end   = "2018-08-21 1:01 PM"
    ResultSize = 'Unlimited'
    EventId    = 'SEND'
}

$AcceptedEmailDomains = '@' + ((Get-AcceptedDomain).Name -join '|@')

Write-host "`n Time window between $($trackparams.start.ToString("dd/MM/yyyy HH:MM")) until $($trackparams.end.ToString("dd/MM/yyyy HH:MM"))" -ForegroundColor Yellow
Import-Csv $inputFile |
    ForEach-Object{
        $email = $_.email
        Write-host "Email address: $email" -ForegroundColor Green
        Get-TransportService |
            ForEach-Object {Get-Messagetrackinglog -Server $_.Name @trackparams -Sender $email} |
                # The below line is set for filtering all external emails not in Exchange Accepted Email Domain lists.
                Where-Object { $_.Recipient -notmatch $AcceptedEmailDomains } |
                Group-Object -NoElement Recipient |
                Sort-Object Count -Descending |
                Select Recipient, Count |
                Export-CSV -Path "C:\TMP\$($_.email).CSV" -NoTypeInformation
}

The error is:
A null key is not allowed in a hash literal.
At line:7 char:2
+     $start = "2018-08-01 12:01 AM"
    + CategoryInfo          : InvalidOperation: (System.Collections.Hashtable:Hashtable) [], RuntimeException
    + FullyQualifiedErrorId : InvalidNullKey

You cannot call a method on a null-valued expression.
At line:15 char:38
+ Write-host "`n Time window between $($trackparams.start.ToString("dd/MM/yyyy HH: ...
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At line:15 char:95
+ ... :MM")) until $($trackparams.end.ToString("dd/MM/yyyy HH:MM"))" -ForegroundColor  ...
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

A: Like the error states, the problem is your hash definition.
Change:
$trackparams = @{
    $start = "2018-08-01 12:01 AM"
    $end   = "2018-08-21 1:01 PM"
    ResultSize = 'Unlimited'
    EventId    = 'SEND'
}

To:
$trackparams = @{
    start = "2018-08-01 12:01 AM"
    end   = "2018-08-21 1:01 PM"
    ResultSize = 'Unlimited'
    EventId    = 'SEND'
}

And it should work as expected.
Keep in mind that you can also make start and end datetime-Objects in the Hash like this:
$trackparams = @{
        start = [datetime]"2018-08-01 12:01 AM"
        end   = [datetime]"2018-08-21 1:01 PM"
        ResultSize = 'Unlimited'
        EventId    = 'SEND'
}


text:
Q: Question about creating table using psycopg2's sql module '''
host = "localhost"
user = "postgres"
password = "Lall1739!@#"
port = "5432"
dbname = "snp500"
con_form = "host={0} user={1} password={2} port={3} dbname={4}".format(host, user, password, port, dbname)

con = psycopg2.connect(con_form)
cur = con.cursor()

components_name, components_prices, components_fetch_dates = fetch_investing_snp500_components_datas()

for component_name in components_name:
    table_name = component_name
    cur.execute(
        query=sql.SQL("CREATE TABLE %s"),
        vars=(sql.Identifier(table_name))
    )

'''

TypeError: 'Identifier' object does not support indexing

It's also not a good idea to use Python string interpolation to build the query string.
So I am trying to write a query using the sql module.
What exactly are the benefits of writing a query using the sql module and why am I getting a Type error?

A: Note that execute is used for parameter substitution (.i.e. string literals), whereas you want to substitute identifiers (i.e. table names). Use SQL.format() for that:
cur.execute(
    query=sql.SQL("CREATE TABLE {table}").format(
        table=sql.Identifier(table_name),
    ),
)


text:
Q: Firebase Error : Failed to resolve : com.google.firebase:firebase-database:16.0.6
Error:com.google.firebase:firebase-database:16.0.6

When I am trying to add firebase real time database in my android project this error pops up what should i do?

A: In order to add firebase-database to your application, you also need to add the firebase-core libraries (which you commented out).
app/build.gradle
dependencies {
  // ...
  implementation 'com.google.firebase:firebase-core:16.0.6'
 }

If you haven't done so, you also need to add rules to include Google services and Google's Maven repository.
Please read Add Firebase to Your Android Project to find out more.


text:
Q: How to manage css files the best way A question about performance.
I have a web project with different CSS files at the moment (uncompressed). Every page is including the needed files.
I am thinking about putting all style definitions in one file, compressing it, and putting it central in the header.
What makes for a better performance? One file compressed (every page loads all styles), or to split the files and only load the needed ones?

A: Splitting the files up will require the browser to do more requests - in the long run, this is probably slower than if you put up one stylesheet that is reused for all the pages. Once the browser has the stylesheet, it will be stored in the browsercache. For all pages after the first, the browser won't need to download the stylesheets. In the end I think this gives a better user experience.
Hope this helps!

A: We typically keep all of our CSS file separate under development, then when it comes to deploy, we pack them together into a single file, and use gzip compression on the server to send them compressed to the client.

A: One compressed file will probably be fastest. You want to cut down on HTTP requests. Also try and put all background images into one file and use css sprites.

A: It depends on the type of website,

*

*if it is an intranet website where the users are probably using every-page on the site then pre-loading all the css will be the fastest.

*if it is an internet website where most users will go away after a few clicks then I would use smaller css file per page.

Have a look at YSlow and Google Page Speed for more tips.

A: I'm working in an environment where we're working with the public stylesheets in uncompressed separate files, and then they're automatically merged and compressed into a single file. As it's compressed, it's obviously less size and loads faster, but it's even better when it's only one file since there will only be one connection to the server when fetching the stylesheets (each CSS file requires 1 connection) and then it will remain cached in the users browser.


text:
Q: using unison options in shell script? I'm new to unison, and am trying to use its options in a simple shell script, but they seem to be ignored when the script is executed, causing no changes to be synced between the two servers.
My shell script:
#!/bin/bash
# set paths / dirs
_paths="/var/www/html/ \
"

# binary file name
_unison=/usr/bin/unison

# Log in to remote server without a password
source $HOME/.keychain/$HOSTNAME-sh

# server names
# sync node1.example.com with rest of the servers in cluster
_rserver="node2.example.com"

# sync it
for r in ${_rserver}
do
    for p in ${_paths}
    do
            ${_unison} -batch -time -owner -group "${p}"  "ssh://${r}/${p}"
    done
done

If i remove the -time -owner -group options, the script syncs changes made fine.
If i add the options to the ~/.unison/default.prf file instead then the script executes successfully. e.g.
# Unison preferences file

prefer=newer
times=true
group = true
owner = true

However. Since I have different scripts being called by different cron jobs, I'd prefer to have the options stated in the scripts themselves as opposed to preference files.
Any suggestions on what I'm doing wrong?

A: Looks like you have to place the unison options after defining the root directories:
Formatted like this: link to unison manual (RTFM!)
unison root1 root2 [options]

So my code should be:
${_unison} -batch "${p}"  "ssh://${r}/${p}" -times -owner -group

Once the options are placed here, the script executes without any errors.


text:
Q: add a new document in a collection in firestore using flutter I am making a shopping/selling  kind of application. There I want to add my list of products to a collection named books whenever any seller adds his product. I wrote
     Firestore.instance.collection('books').add({
         'title':b.title,    //b is an argument I got in the method
     });

but when I run it, no collection is added in the Firestore.
What to do?
the console comes till here and then nothing happens:
E/flutter (15848): #28     _invoke1 (dart:ui/hooks.dart:275:10)
E/flutter (15848): #29     _dispatchPointerDataPacket (dart:ui/hooks.dart:184:5)
E/flutter (15848):

A: If you want to make a document with random id, keep the id inside document empty
   Firestore.instance.collection('books').document().setData({
         'title':b.title,    //b is an argument I got in the method
     });

If you want to add document with specific ID, put the ID inside document():
   Firestore.instance.collection('books').document("docId").setData({
         'title':b.title,    //b is an argument I got in the method
     });

A: The problem where with rules of I wrote for Firestone. I simply put too many restrictions so my user was not getting permission to write in the database.
Then I erased what I wrote and set the rules to default what they were written at
the start.


text:
Q: Resize A4 PDF to SRA4 and center content I'd like to be able to resize an A4 PDF to the slightly bigger SRA4 format, used by printing professionals. The content shouldn't be resized, but only centered. In other words, I'd like to add margins to my A4 document.
I managed more or less to do that with this Ghostscript (9.05) call:
gs -dPDFSETTINGS=/default -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite
-sOutputFile=out.pdf -dDEVICEWIDTHPOINTS=637 -dDEVICEHEIGHTPOINTS=907
-dFIXEDMEDIA in.pdf

The problem is that the A4 content is not centered in the SRA4 page, but is placed at the bottom left corner.
Any idea how to center the content?

A: I found a solution, by using -c "<</PageOffset [21 32]>> setpagedevice", like so:
gs -dPDFSETTINGS=/default -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite
-sOutputFile=out.pdf -dDEVICEWIDTHPOINTS=637 -dDEVICEHEIGHTPOINTS=907
-dFIXEDMEDIA -c "<</PageOffset [21 32]>> setpagedevice" -f in.pdf

Content is perfectly centered in the SRA4 document.


text:
Q: Executing sp_send_dbmail with an Agent Job: Failed to initialize sqlcmd library I'm executing a SP that dynamically builds a global temp table of data gathered from multiple databases. At the end of this SP is this line of code:
Exec msdb.dbo.sp_send_dbmail
    @profile_name = @dbmailProfileName,
    @recipients = @emailRecipents,
    @subject = @subject,
    @body = @body,
    @query = 'Select * From tempdb..##MyTempTable'

This SP works perfectly when I execute it manually, however, when I let my Server Agent Job run it, it fails with the following error:
Message
Executed as user: WORKGROUP\MyServer2016$. Failed to initialize sqlcmd library with error number -2147467259. [SQLSTATE 42000] (Error 22050)  Failed to initialize sqlcmd library with error number -2147467259. [SQLSTATE 42000] (Error 22050).  The step failed.

Commenting out @query portion of the SP will work fine, but that's useless since I need the data emailed.

A: I knew it was some kind of security issue, but my lack of DBA skills defeated me here. However, I found a workaround solution which worked, not exactly what I was looking for, but it works.
Editing the Job Step to include an Execute As with my working login:
Execute As Login='MyUser'
GO
exec DBNAME.dbo.SPNAME
GO
Revert
GO

Since MyUser could run this thing manually, I executed as my login.

A: I was getting this same error then, after numerous trial and error attempts, another error popped up:
  The EXECUTE permission was denied on the object 'xp_sysmail_format_query',
  database 'mssqlsystemresource', schema 'sys'.

I added the user to the public role in the master database then added this permission for the user:
  grant execute on xp_sysmail_format_query to [myuser]

It seems that Database Mail relies on this stored proc.  After doing this, the email job works fine.  Note:  I run the job as a designated user.

A: Did you try use the @execute_query_database parameter? If that doesn't work, try to add the Sql Server Agent account to the Sql Server as a sysadmin


text:
Q: This Site Can't be Reached Error while trying to Run the Dash App locally in Chrome Browser When I'm trying to run locally a sample dash app code but I'm always getting an error of this site cant be reached. From other threads i came to know this error can be solved by doing some settings in chrome browser.
I'm using Jupyter Notebook and running the below sample code for my learnings.
# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

from dash import Dash, html, dcc
import plotly.express as px
import pandas as pd

app = Dash(__name__)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for your data.
    '''),

    dcc.Graph(
        id='example-graph',
        figure=fig
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

I am tring to access on this link:
http://127.0.0.1:8050/
I am still getting the error. I have no doubt on code because it is just copied from the dash official website
https://dash.plotly.com/layout


text:
Q: How to add a nested dictionary to PostgreSQL with Python? I have a dictionry, I don't know it's a nested dict or no.
My dictionary is:
my_dict = {"username": "XYZ", "email": "xyz@gmail.com",
           "location": "Mumbai", "Address": {"Country": "", "City": "", "Street": ""}}

I addedd two values like this:
my_dict['name'] = []
my_dict['number'] = []

and finaly I want to add this dict to Postgresql table. The table is:

My full code is:
my_dict = {"username": "XYZ", "email": "xyz@gmail.com",
           "location": "Mumbai", "Address": {"Country": "", "City": "", "Street": ""}}

my_dict['name'] = []
my_dict['number'] = []

my_dict["name"] = 'Test'
my_dict["number"] = 30
my_dict["Address"]["Country"] = "Turkey"
my_dict["Address"]["City"] = "Istanbul"
my_dict["Address"]["Street"] = "221sk"

cursor_connection.execute(
    '''INSERT into test_table VALUES (%(username)s, %(email)s , %(location)s, %(Country)s , %(City)s , %(Street)s , %(name)s , %(number)s);''', my_dict)
connection_db.commit()

I received this error:
KeyError: 'Country'

I can insert this dict without "Address"'s dictionary but I have a problem with "Address"

A: The query expects to find a Country in the dict at first level, but here isn't.
I'd suggets you create a new dict, with setting the Address values at first level
values = {**my_dict, **my_dict['Address']}
del values['Address']

cursor_connection.execute(
    '''INSERT into test_table VALUES (%(username)s, %(email)s , %(location)s, %(Country)s , %(City)s , %(Street)s , %(name)s , %(number)s);''', values)
connection_db.commit()

# my_dict
{'username': 'XYZ', 'email': 'xyz@gmail.com', 'location': 'Mumbai', 'name': 'Test',
 'Address': {'Country': 'Turkey', 'City': 'Istanbul', 'Street': '221sk'}, 'number': 30}

# values
{'username': 'XYZ', 'email': 'xyz@gmail.com', 'location': 'Mumbai', 'name': 'Test',
  'number': 30, 'Country': 'Turkey', 'City': 'Istanbul', 'Street': '221sk'}


text:
Q: Как сравнить две строки чтобы узнать на каких символах отличаются у меня есть 2 строки и я хочу узнать какой символ не правильный по сравнению с другой. Пробовал compare, equals, но они дают не те ответы.
String a1="Text";
String a2="Taxt";
/*Some code*/
System.out.println();

Вывод
Diferent in position 1

Вот попробовал написать код он определяет где ошибка но у меня складывается впечатление что он не очень эффективный
      String vvedeno="Строка для сравнения 1";
      String nadovvesti="сТрока для сравнения 2";

      int i=nadovvesti.length();
      if(i==vvedeno.length()) {
          StringBuffer line=new StringBuffer();
          boolean[] srav = new boolean[i];
          for (int j=0; j < i; j++) {
              if (vvedeno.charAt(j) == nadovvesti.charAt(j))
                  srav[j] = true;
          }
          for(int j=0;j<i;j++){
              if(!srav[j])
                  line.append("_");
              else line.append(" ");
          }
          System.out.println(nadovvesti);
          System.out.println(line.toString());
          System.out.println(vvedeno);

Результат работы
Строка для сравнения 1
__                   _
сТрока для сравнения 2

A: Вот попробовал написать код он определяет где ошибка но у меня складывается впечатление что он не очень эффективный
`String vvedeno="Строка для сравнения 1"; String nadovvesti="сТрока для сравнения 2";

  int i=nadovvesti.length();
  if(i==vvedeno.length()) {
      StringBuffer line=new StringBuffer();
      for (int j=0; j < i; j++) {
          if (vvedeno.charAt(j) == nadovvesti.charAt(j))
            line.append(" ");
          else line.append("_");
      }
      System.out.println(nadovvesti);
      System.out.println(line.toString());
      System.out.println(vvedeno);`

Результат работы
Строка для сравнения 1
__                   _
сТрока для сравнения 2


text:
Q: How to write a valid xsd for elements with different names I would like to validate xml with xsd schema, but i do not know how to create correct xsd schema for elements which would have changable names. My xml document :
<Settings xmlns="main">
  <Object>
    <Rules>
      <Rule0>
        <Range>0 to 0</Range>
        <String>SomeString</String>
        <Integer>80</Integer>
        <Enabled>No</Enabled>
      </Rule0>
      <Rule0>
        <Range>0 to 0</Range>
        <String>SomeString</String>
        <Integer>80</Integer>
        <Enabled>No</Enabled>
      </Rule0>
    </Rules>
    <ObjectEnabled>No</ObjectEnabled>
  </Object>
</Settings

And my xsd document:
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"           targetNamespace="main" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Settings">
<xs:complexType>
  <xs:sequence>
    <xs:element name="Object">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="Rules">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="?" maxOccurs="unbounded" minOccurs="0">
                  <xs:complexType>
                    <xs:sequence>
                      <xs:element type="xs:string" name="Range"/>
                      <xs:element type="xs:string" name="String"/>
                      <xs:element type="xs:byte" name="Integer"/>
                      <xs:element type="xs:string" name="Enabled"/>
                    </xs:sequence>
                  </xs:complexType>
                </xs:element>
              </xs:sequence>
            </xs:complexType>
          </xs:element>
          <xs:element type="xs:string" name="ObjectEnabled"/>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
  </xs:sequence>
</xs:complexType>

Off course instead of "Rule1" it could be "Blablabla". I know that i cannot put in name wildcard or question mark, so i kindly ask you for help.

A: You will have to reorganise the elements a bit, i think.
Instead of having different elements...
<Rule0 />
<Rule1 />

you could write...
<Rule name="rule0" />
<Rule name="rule1" />

Think of elements as classes that describe the properties of all rules, and not of objects, that describe the properties of a single rule.


text:
Q: Yii2: How to refer to an action attached to a controller with a Behavior? I am using a Behavior to add an action to a few controllers, the oversimplified behavior is defined as
public class GreetBehavior extends Behavior {
    public function sayHello() {
        return "Hello"
    }

    public function actionGreet() {
        return "Hello";
    }
}

The behavior is attached successfully. From within a Controller (f.i. Person) method I can access sayHello with $this->sayHello();.
The actionGreet however, is not recognized if I call it from the address bar: ...index.php?r=person/greet. It gives the message that it cannot be resolved. Is it possible to add actions to a controller with behaviors anyway? If so, can you give me a hint what to do/what I am doing wrong. If not, do you know an alternative?

A: In Yii2 there are two ways to add actions to a controller; standalone and inline. You are trying to add an inline action - which means that it is declared as a method on the controller's class with the 'action' prefix.
The other way to load actions are as 'standalone' files, that are defined in the controller's 'actions' method. This returns an array of references to action classes that exist elsewhere.

If you look at the createAction method on yii\base\Controller (which loads the action when your app runs) you can see that it first looks through its actions array (the standalone ones) and if it can't find it it looks through its own methods (after formatting the name and adding the 'action' prefix - see lines 224-225).
The problem you have is that when the base controller looks for the inline method it uses php's method_exists function, which is totally blind to yii2's behavior functionality.
I don't know why it doesn't use the 'hasMethod' method on the base controller instead, which would know about the behavior methods. I'm only just looking at Yii2 at this level of detail though so there may be a reason I'm unaware of.

So the answer to your question is that the way Yii2 is currently coded you cannot put an inline action on a controller's behavior - because it won't be seen when Yii2 comes to look for it.
And the solution is to switch to standalone actions, which you can read about on this guide page.

A: You can not do that, since actions must be extended from a Controller class, so a method in a behavior class can not be replaced with a controller action.
You can achieve this goal, by creating a base controller and change your other controllers to extend from that controller. Like below:
use yii\web\Controller;
class BaseCont extends Controller{
    public function actionGreat(){
        return "Hello";
    }
}

Then by creating a controller which extends it like below:
class MyController extends BaseCont{
    //rest of code
}

You will have greatAction in addition to your other actions in MyController.

A: Use Controller::actions()
public function actions() {
    return [
        'ajaxsearch' => [
            'class'=>'app\components\searchlinewidget\AjaxSearchAction',
            'searchClass'=>PublisherSearch::className()
        ]
    ];
}

A: You can add actions with the Actions class definition. See item 3 here http://www.yiiframework.com/doc/guide/1.1/en/basics.controller
Your issues is being discussed here:
No this is not possible yet because CController::createAction() checks if "actionExample" is a valid method for the given controller. Behavior methods are no real methods within a controller since they get called via magic __get().
For now, as workaround I guess you can override CController::createAction() or CController::missingAction() in some way to get it work.
http://www.yiiframework.com/forum/index.php/topic/10652-actions-by-behavioring/


text:
Q: apply CheckReturnValue to entire project I work on a large legacy Java 8 (Android) application. We recently found a bug that was caused by an ignored result of method. Specifically a caller of a send() method didn't take the right actions when it the sending failed. It's been fixed but now I want to add some static analysis to help find if other existing bugs of the same nature exist in our code. And additionally, to prevent new bugs of the same nature from being added in the future.
We already use Find Bugs, PMD, Checkstyle, Lint, and SonarQube. So I figured that one of these probably already has the check I'm looking for, but it just needs to be enabled. But after a few hours of searching and testing, I don't think that's the case.
For reference, this is the code I was testing with:
public class Application {
    public status void main(String[] args) {
        foo(); // I want this to be caught
        Bar aBar = new Bar();
        aBar.baz(); // I want this to be caught
    }

    static boolean foo() {
        return System.currentTimeMillis() % 2 == 0;
    }
}

public class Bar {
    boolean baz() {
        return System.currentTimeMillis() % 2 == 0;
    }
}

I want to catch this on the caller side since some callers may use the value while others do not. (The send() method described above was this case)
I found the following existing static analysis rules but they only seem to apply to very specific circumstances to avoid false positives and not work on my example:

*

*Return values from functions without side effects should not be ignored (only for immutable classes in the Java API)

*Method ignores exceptional return value (only for known methods like File.delete())

*Method ignores return value (only for methods annotated with javax.annotation.CheckReturnValue I think...)

*Method ignores return value, is this OK? (only when the return value is the same type as the type the method is invoked on)

*Return value of method without side effect is ignored (only when the method does not produce any effect other than return value)

So far the best option seems to be #3 but it requires me to annotate EVERY method or class in my HUGE project. Java 9+ seems to allow annotating at the package-level but that's not an option for me. Even if it was, the project has A LOT of packages. I really would like a way to configure this to be applied to my whole project via one/few locations instead needing to modify every file.
Lastly I came across this Stack Overflow answer that showed me that IntelliJ has this check with a "Report all ignored non-library calls" check. Doing this seems to work as far as highlighting in the IDE. But I want this to cause CI fail. I found there's a way to trigger this via command line using intelliJ tools but this still outputs an XML/JSON file and I'll need to write custom code to parse that output. I'd also need to install IDE tools onto the CI machine which seems like overkill.
Does anyone know of a better way to achieve what I want? I can't be the first person to only care about false negatives and not care about false positives. I feel like it should be manageable to have any return value that is currently being unused to either be logged or have it explicitly stated that the return value is intentionally ignored it via an annotation or assigning to a variable convention like they do in Error Prone

A: Scenarios like the one you describe invariably give rise to a substantial software defect (a true bug in every respect); made more frustrating and knotty because the code fails silently, and which allowed the problem to remain hidden. Your desire to identify any similar hidden defects (and correct them) is easy to understand; however, (I humbly suggest) static code analysis may not be the best strategy:

*

*Working from the concerns you express in your question: a CheckReturnValue rule runs a high risk of producing a cascade of //Ignore code comments, rule violationSuppress clauses, and/or @suppressRule annotations that far outnumber the rule's positive defect detection count.

*The Java programming language further increases the likelihood of a high rule suppression count, after taking Java garbage collection into consideration and assessing how garbage collection effects software development. Working from the understanding that Java garbage collection is based on object instance reference counting, that only instances with a reference count of 0 (zero) are eligible for garbage collection, it makes perfect sense for Java developers to avoid unnecessary references, and to naturally adopt the practice of ignoring unimportant method call return values. The ignored instances will simply fall off of the local call stack, most will reach a reference count of 0 (zero), immediately become eligible for and quickly undergo garbage collection.
Shifting now from a negative perspective to positive, I offer alternatives, for your consideration, that (I believe) will improve your results, as well as your probability to reach a successful outcome.

*

*Based on your description of the scenario and resulting defect / bug, it feels like the proximate root cause of the problem is a unit testing failure or an integration testing failure. The implementation of a send operation that may (and almost certainly will at some point) fail, both unit testing and integration testing absolutely should have incorporated multiple possible failure scenarios and verified failure scenario handling. I obviously don't know, but I'm willing to bet that if you focus on creating and running unit tests and integration tests, the quality of the system will improve at every step, the improvements will be clearly evident, and you may very well uncover some or all of the hidden bugs that are the cause of your current concern, trepidation, stress, and worry.

*Consider keeping the gist of your current static code analysis research alive, but shift your approach in a new direction. The first time I read your question, I was struck by the realization that the code checks you would like to perform exist in multiple unrelated locations across the code base and are quickly becoming overly complex, the specific details of the checks are different in many section of code, and each of the special cases make the overall effort unrealistic. Basically, what you would like to implement represents a cross-cutting goal that falls across a sizable section of the code base, and the implementation details have made what is a fairly simple good idea ridiculously complex. Your question is almost a textbook example of a problem that is best implemented taking a cross-cutting aspect-oriented approach.
If you have the time and interest, please take a look at the AspectJ framework, maybe code a few exploratory aspects, and let me know what you think. I'd like to hear your thoughts, if you feel like having a geeky dev conversation at some point. I really hope this is helpful-

A: You may use the intelliJ IDEA's inspection: Java | Probable bugs | Result of method call ignored with "Report all ignored non-library calls" option enabled. It catches both cases provided in your code sample.