text:
Q: How is java platform independent if I need different JVM for different system? Just like how we need to download different C compiler for different Systems, We need to download different JVM for different System. So, how is java platform independent ?

A: The Java language is platform independent because a particular piece of code is guaranteed to run the same on any system it is executed on.
While there may be a different JVM for each system, all JVMs are required to run the same Java bytecode the same way.


text:
Q: GR examples in Python don't open a window with visualization I installed GR and its dependencies on Ubuntu 20.04 with Python 3.8.10 following instructions on https://gr-framework.org/python.html#installation. The first example:
from gr.pygr import mlab
mlab.plot(range(100), lambda x: x**2)

Doesn't create a window or terminal output. Any ideas what may be missing?

The plot shows when run in Jupyter. What is the way to plot from the terminal?

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++: Using predeclared operator[] in another method I am trying to use a predeclared operator[] in another method of the same class. However, I have no idea how to proceed. Funny part is that I don't even know how to google it :(. Please, advise...
This is part of a doubly-linked-list - I want to enable Array behavior in it (I know - not good :)).
Code snippet:
template <typename T>
T& DLL<T>::operator[](int i) const{
  Node <T>*n = this->head;
  int counter = 0;
  while (counter > i) {
    n = n->next;
    counter++;
  }
  return n->next->val;
}

template <typename T>
T& DLL<T>::at(int i) const throw (IndexOutOfBounds) {
  if (i < 0 || i >= elemNum) {
    throw IndexOutOfBounds("Illegal index in function at()");
  }
  // I want this part to use the predeclared operator
  // obviously this is not right...
  return this[i];  // Why u no work?!??!?
}

A: Try calling this->operator[](i). This should get you the desired result.
EDIT
As WhozCraig said: (*this)[i] works as well and is probably more elegant.


text:
Q: How to benchmark openvpn server Ive successfully setup a tunnel between my home ubuntu desktop(Japan) and my remote server(UK) using openvpn. Ive set it so that i can have the server fetch pages for me hiding my desktop ip to bypass geo restrictions (tv, radio etc) whilst im abroad.
Sometimes the playback is very choppy and i want to pinpoint why. Is it my configs? is the location of the server? Is it just that the webpage being accessed is very busy at that time of day? Would switching the server location to london instead of maidenhead make a difference?
Im wondering how best to go about this? Any ideas? Tools tips etc? I am a server newb but not to stuff like programming so not afraid of console etc.

A: most probably it's the network latency between the two ends of the tunnel; if you feel artistic, use some graphical tools (cacti, for example, if not plain rrdtool) to keep track of various issues - latency, traffic, etc

A: I'd start with one of the available network benchmarks (google results).
You can try one of the web-based ones, like Speedtest, too :)

*

*Also, how fast is your connection?

*How fast are the intervening connections?

*Does the VPN sometimes route/connect across faster pipes than others?

A: I would check some things:

*

*Bandwidth between the client and server.

*Bandwidth between the server and the internet.

*Latency between the client-server, client-internet (using the vpn), client-internet (not using the vpn). Compare.

*When the connection slows down, you need to check which other traffic is using the server. Is this server also working as proxy/router to other clients?. iftop would be a useful tool.


text:
Q: Can I use glVertexAttribPointer instead of glVertexAttribIPointer A tutorial I read specifically advocated using glVertexAttribIPointer for integer data, uploading data into a ivec4 data type in the shader.
I was wondering why I can't use glVertexAttribPointer with the GL_INT data type instead. Why will it corrupt my data? Reading the API reference gave no clue to this.

A: I looked at the OpenGL 3.3 (Core Profile) spec, and all I could find was this wording on page 29:

Data for an array specified by VertexAttribPointer will be converted to floating-point by normalizing if normalized is TRUE, and converted directly to floating-point otherwise. Data for an array specified by VertexAttribIPointer will  always  be  left  as  integer  values;  such  data  are  referred  to  as pure integers.

I couldn't find any explicit mention that there would be error checking, unspecified values, or undefined behavior, but presumably, if your attribute array converts integers to floating-point, but your shader takes integers, you'll end up with incorrect attribute values.
I know that very old hardware was used floating point everywhere, so ivec4 would just be vec4 in disguise.  Therefore, even if this works on your hardware, you shouldn't do it.
Summary: Don't do it.


text:
Q: Define the space of distributions with algebraic decay? A tempered distribution $u\in \mathcal{S}'(\mathbb{R})$ is said to be rapidly decreasing if for every $f \in \mathcal{S}(\mathbb{R})$, $u*f \in  \mathcal{S}(\mathbb{R})$.
One rough way to motivate this definition is that $u*f$ has the best regularity between $f$ and $u$ (and thus, for $f$ smooth, it is smooth) and the worst decay between $f$ and $u$ (for $f$ rapidly decreasing, it has consequently the decay of $u$).
I am wondering if we could define similarly the space of distributions with algebraic (or slow) decay in the following way. First, a smooth function $f$ has an algebraic decay if we have
for every integer $n$ a bound $$|f^{(n)}(t)| \leq \frac{C}{1 + |t|^\alpha}$$ for some $C$ and $\alpha >0$.
Then, $u \in \mathcal{S}'(\mathbb{R})$ is said to have a algebraic decay if for every $f\in \mathcal{S}(\mathbb{R})$, the smooth function $u*f$ has an algebraic decay.

Questions: Is the space of distributions with algebraic decay already introduced and studied somewhere? Is the previous definition the correct one for that concept? What are the properties of such distributions? Especially, what can we say about the Fourier transform of a distribution with algebraic decay?


text:
Q: Mysql in Java. How to implement efficient asynchronous queries? I'm creating a game with a server and multiple clients.
I'm using Kryonet for networking and each connection has it's own listener where it receives packets.
There listeners are called on a background Kryonet thread and I can't block them cause it would affect all of the users.
I have created my database, configured a ConnectionPool in a synchronized Singleton class:
private static final BasicDataSource dataSource = new BasicDataSource();

static {
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://111.111.111.111/db");
    dataSource.setUsername("server");
    dataSource.setPassword("serverpass");
}

public Connection getConnection() throws SQLException {
    return dataSource.getConnection();
}

and now I need to execute some queries.
Here comes my issue. As we know, query could take long to return a result so it's totally unacceptable to execute it on a 'Kryonet' thread (when packet is received).
For example, when user sends his 'RegistrationPacket' I need to make a query to the database and return him a result within a packet. When I receive the packet, I need to put it in background and from there - send result to the client.
Here comes my question:
How to handle making database queries in background using Java?
Should I use Executors? Threads? As I know opening a Thread for each connection is a bad idea, (cause 200+ workers).equals(disaster). If someone could help me I would be grateful! :)

A: With jasync-sql You can do something like this:
// Connect to DB
Connection connection = new MySQLConnection(
  new Configuration(
    "server",
    "111.111.111.111",
    3306,
    "serverpass",
    "db"
  )
);
CompletableFuture<?> connectFuture = connection.connect()
// Wait for connection to be ready
// ...
// Execute query
CompletableFuture<QueryResult> future = connection.sendPreparedStatement("select 0");
// Close the connection
connection.disconnect().get()

See more details on the lib itself. It is an async MySQL driver based on Netty.


text:
Q: Jquery cannot skipped evaluation of first json result I want to evaluate a set of JSON results but somehow the first result is always skipped. My Jquery code is as follows:
function check_product_cash_discount(total_id){
        //check for cash discount
        $.ajax({
            url:siteurl+"checkout/get_cash_discount_ajax/",
            type:"POST",
            success:function(res){
                var parsed = JSON.parse(res);
                var this_product_total = $(total_id).text();
                $.each(parsed,function(k,v){
                    var amount = v.cash_discount_amount;
                    //console.log(v);
                    if(this_product_total >= amount){
                        $(total_id).text(v.cash_discount_percentage);
                        console.log(amount);
                    }
                });
            }
        });
    }

The result from the AJAX call is "res" and I parsed it with JSON.parse and place in "parsed". The value(v) of the result is as follows when console.log(v) with $.each:
Object {cash_discount_id: "4", cash_discount_amount: "1000", cash_discount_percentage: "10"}
Object {cash_discount_id: "3", cash_discount_amount: "800", cash_discount_percentage: "8"}
Object {cash_discount_id: "2", cash_discount_amount: "300", cash_discount_percentage: "7"}

My question is this: how come the variable "this_product_total" skips the first JSON result object when it is smaller that the variable "amount" in the "if" statement? when I console.log(amount), the log shows 1000, 300 and 200 when the text, in variable "this_product_total" is 512.89? The values in "amount" and "thid_product_total" are true when I evaluated them with $.isNumeric(); Please help.

A: The problem with this is that the amount "1000" was treated as a string. So I had to parseInt(amount) and the 1000 problem is solved and I added a break; to the if(this_product_total >= amount) so that once it found the 1st matching condition, it stops looping ...


text:
Q: PHP can't search alias directory XAMPP I have my server set up and I can send images from the htdocs/images folder. However, I want to display images from outside of the htdocs folder.
In my httpd.conf file, I created an alias, so now /myimages links to the appropriate folder on my computer. If I navigate to localhost/myimages, I get the index of myimages and it displays a listing of all my images.
Whenever I directly access the file, say
$file = "myimages/image.jpg";

It works perfectly fine, I return the image as I expect. The problem comes in when I try to look for the image instead of directly accessing it.
Whenever I try to do:
$files = scandir($dir);

Where $dir is "images" or "myimages" it just returns an error message saying no such file or directory.
My intention is to set it up so that I can search for the file I wanted by some text input from the user and serve up the file. However, it seems to be a problem that it's an alias and not actually there.

A: the alias will work for the web-server but scandir() is not using the web-server you want to set up a Symbolic link


text:
Q: Change separator in Bibtex bibliography from comma to period I've been editing a Bibtex style, the standard agsm.bst, to match my university's requirements. I've managed to get everything correct, except that the style separates the year, title, and journal with commas:

Schuster-Böckler, B., Schultz, J. and Rahmann, S. (2004), HMM Logos for visualization of protein families, BMC Bioinformatics 5(1),7.

I need the output to use a full stop (period) as the separator:

Schuster-Böckler, B., Schultz, J. and Rahmann, S. (2004). HMM Logos for visualization of protein families. BMC Bioinformatics 5(1),7.

I'm fairly sure this isn't defined in the style file. Where is this behaviour defined, and how can I change it?

A: You concluded the posting with:

I'm fairly sure this isn't defined in the style file. Where is this behaviour defined, and how can I change it?

Actually, this behavior is set in the style file, but it's not easy to find. First, make a copy of the file agsm.bst and name it, say, my-agsm.bst. Then, search for the function that starts with
FUNCTION {output.nonnull}

(located on l. 59 of my copy of agsm.bst). A couple of lines further down, you should find:
  output.state mid.sentence =
    { ", " * write$ }

Replace the comma in the second line with a period, save the file, and don't forget to specify
\bibliographystyle{my-agsm}

in your tex file. (If you've chosen a filename other than my-agsm.bst, you'll of course have to make the appropriate adjustment.) You'll note that there are other commas (or is that "commata"?!) in the .bst file, but those pertain to separating names of authors and editors -- settings that, according to your posting, should remain unchanged.


text:
Q: Can a DSL splitter be used in place of a micro filter I don't want to do the rewiring required to put a splitter at the demarcation point, but we don't have DSL micro filters available here.
Can I use two splitters as filters for the modem and the phone?
@Edit:
I think the Wikipedia article clearly answers this question:

Typical installation for an existing home involves installing DSL filters on every telephone, fax machine, voiceband modem, and other voiceband device in the home, leaving the DSL modem as the only unfiltered device.

A: I think this would probably give you a better overview of your options and the correct use of filters vs. splitters: http://www.cisco.com/en/US/tech/tk175/tk15/technologies_tech_note09186a0080094a17.shtml
Put briefly, in your situation you should use two splitters, not one.
Cheers,
Chris

A: If I understand your question, you want a whole-house filter for voice and a raw line to your DSL modem?  I have done this using one of the DSL filters typically used for a single phone to filter the voice side of a split feed into the house, and run the other leg of the split, raw, directly from the network interface to the modem.
I don't know how the number of telephone extensions, the number of extensions in use at the same time, or the total lengths of extension wiring segments might affect this.  Maybe I was just lucky that day, but it's worth a try.  Another thing to consider is whether you have an alarm system that needs to seize the phone line and how doing this might affect its operation.  Best to check that with your alarm company.

A: As far as I know, you need a filter for your phones, one way or another. Given that those filters are hard to find for you, I would see two choices:
Get a single filter, in line before the entire house wiring. Split the phone line BEFORE the filter, and connect your modem. You should be able to order such filters, even if they would have to come from remote locations. There are some that will connect to a phone jack, and provide two connections out. One that is unfiltered, and one that is filtered. I got one of those when I switched back to ADSL technology.
Use your modem on and off, and use the phone only when the modem is not in operation. The noise that is filtered out is what the filter is for. If you do not use your modem, your phones will operate just fine without any filter.


text:
Q: Why is the definition of inductive set well defined? I've been studying from Enderton's Mathematical Introduction to Logic in which he defines an inductive set as follows:

To simplify our discussion, we will consider an initial set $B \subseteq U$ and a class $F$ of functions containing just two members $f$ and $g$, where
  $f:U×U→U$ and $g:U→U$.
  Thus $f$ is a binary operation on $U$ and $g$ is a unary operation. (Actually $F$ need not be finite; it will be seen that our simplified discussion here is, in fact, applicable to a more general situation. $F$ can be any set of relations on $U$, and in Chapter 2 this greater generality will be utilized. But the case discussed here is easier to visualize and is general enough to illustrate the ideas. For a less restricted version, see Exercise 3.)
  If $B$ contains points $a$ and $b$, then the set $C$ we wish to construct will contain, for example,
  $b, f (b, b), g(a), f (g(a), f (b, b)), g( f (g(a), f (b, b)))$.
  Of course these might not all be distinct. The idea is that we are given certain bricks to work with, and certain types of mortar, and we want $C$ to contain just the things we are able to build.
In defining $C$ more formally, we have our choice of two definitions. We can define it "from the top down" as follows: Say that a subset $S$ of $U$ is closed under $f$ and $g$ iff whenever elements $x$ and y belong to $S$ , then so also do $f(x,y)$ and $g(x)$.Say that $S$ is inductive iff $B \subseteq S$ and $S$ is closed under $f$ and $g$ . Let $C^*$ be the intersection of all the inductive subsets of $U$; thus $x \in C^*$ iff $x$ belongs to every inductive subset of $U$. It is not hard to see (and the reader should check) that $C^*$ is itself inductive. Furthermore, $C^*$ is the smallest such set, being included in all the other inductive sets.
The second (and equivalent) definition works "from the bottom up." We want $C_*$ to contain the things that can be reached from $B$ by applying $f$ and $g$ a finite number of times. Temporarily define a construction sequence to be a finite sequence $<x_1, . . . , x_n>$ of elements of $U$ such that
  for each $i \leq n$ we have at least one of
$x_i \in B$,
$x_i=f(x_j,x_k)$ for some $j<i,k<i$,
$x_i =g(x_j)$ for
  some $j<i$.
In other words, each member of the sequence either is in B or results from earlier members by applying f or g. Then let C be the set of all points x such that some construction sequence ends with x.

I am confused as in other texts I've read an inductive set to be defined in a similar fashion to as follows from Enderton's Elements of Set Theory:

A set $A$ is said to be inductive iff $\emptyset \in A$ and it is "closed under successor," i.e.,
  $(\forall a \in A) a^+ \in a$

or similarly for For Natural Numbers
What confuses me most is that by just defining an inductive set as such "$S$ is inductive iff $B \subseteq S$ and $S$ is closed under $f$ and $g$" doesnt that lead to inductive sets such as $\{1,2,3,4\}$ where $f$ and $g$ can be sent to map all to the same element $1$.
What is the advantage to this type of definition for induction and how is it consistent with other definition. Using this definition of induction how may one say that the natural numbers are an inductive set any more than my finite set above. What is the intuition in this definition?
Thank you for help.

A: Enderton is giving a very general definition template for different kinds of inductive sets. The actual definition of inductive depends on the choice of $B$ and $F$.
Maybe it would be clearer to write it like this: Let $B$ be a set and $F$ a class of functions. A set $S$ is $(B,F)$-inductive if $B\subseteq S$ and $S$ is closed under all the functions in $F$.
Now as a particular case of this definition template, we can take $B = \{\emptyset\}$ and $F = \{s\}$, where $s$ is the unary function on sets defined by $s(x) = x\cup \{x\}$. Then a set $S$ is $(\{\emptyset\},\{s\})$-inductive if and only if $\emptyset\in S$ and for all $x\in S$, also $s(x)\in S$. So $\omega$ is the least $(\{\emptyset\},\{s\})$-inductive set.
But there are many other instances of this definition template, with many different results. You suggest another example at the end of your question: If $B = \emptyset$ and $F = \{f,g\}$, where $f$ and $g$ are constant functions with output $1$, then a set $S$ is $(B,F)$-inductive if and only if $S = \emptyset$ or $1\in S$. So yes, $\{1,2,3,4\}$ is $(B,F)$-inductive. Enderton is not claiming that this notion of $(B,F)$-inductive has anything to do with the example above in which $\omega$ is the least inductive set.

What is the advantage to this type of definition for induction and how is it consistent with other definition.

The advantage to this definition is that it's very general, handling not just induction for the natural numbers, but many other example of the same type in mathematics. Different instances of the definition (for different $B$ and $F$) are inconsistent with each other, but they are all instances of the same abstract pattern.


text:
Q: Putting marginpar always on the right in a two sided document I'm drafting a document using a required style file for a conference, which is a two sided style. (i.e. odd and even pages are different.)
During the drafting process, I like to use the marginnote package to put comments to myself and colleagues in the margin. Sometimes I want these notes to appear on the right and sometimes the left. I know that the side the notes appear on can be controlled using \reversemarginpar and \normalmarginpar.
However, since it's a two-sided document, the side that's considered "normal" changes depending on whether it's an odd or an even page. I don't want that. How can I put a note in the margin that will always be on the right or always on the left, regardless of odd or even pages?
Note that this is only a 'temporary' measure, in that all margin comments will be removed before submitting the paper, so if the solution changes (for example) the running head etc. I don't mind. However, I don't want to remove the style file or use a different one, since it's important to make sure the text will fit within the page limit when the final style is applied.
The following mwe demonstrates the issue, using the twoside option to the article class instead of a style file. (Sorry it's not quite as minimal as it could be - it seems there has to be a certain amount of text on the page otherwise \marginnote just goes mad and positions things randomly, but that's a separate issue.)
\documentclass[a4paper,twoside]{article}

\usepackage[margin=1.75in,marginparwidth=1.4in]{geometry}

\usepackage{marginnote}

\begin{document}
Some text.
{\marginnote{On the right}}%
{\reversemarginpar\marginnote{On the left}}%
Some more text.

Some more text.

Some more text.

Some more text.
{\marginnote{Still right}}%
{\reversemarginpar\marginnote{Still left}}%
Some more text.

Some more text.

\raggedbottom
\pagebreak

Some text.
{\marginnote{On the right?}}%
{\reversemarginpar\marginnote{On the left?}}%
Some more text.

Some more text.

Some more text.
{\marginnote{Still right?}}%
{\reversemarginpar\marginnote{Still left?}}%
Some more text.

Some more text.

\end{document}

Page 1 of the output looks like this:

but page 2 looks like this, with the "normal" marginpars on the left and the "reverse" ones on the right.

(Note: there are some similar old questions, but as far as I can tell none quite cover my situtation. This one, this one and this one could all be solved with a twoside=semi option that the third-party style file I'm using doesn't accept, the solution to this one seems to be specific to a two-column document, and the solutions to this one seem to put all the notes on the left, so that \reversemarginpar cannot be used to put them on the right.)

A: Putting my comments to a full answer... here's what could potentially solve your issue:
Define two new commands \leftmarginnote{...} and \rightmarginnote{...} that would work equally across even and odd pages.
\documentclass[a5paper,twoside]{article}

\usepackage[margin=1.75in,marginparwidth=1.4in]{geometry}
\usepackage{marginnote}

\usepackage{ifthen,changepage}
\usepackage{xargs}

\newcommandx{\leftmarginnote}[2][2=0pt]
           {\checkoddpage
            \ifoddpage
              {\reversemarginpar\marginnote{#1}[#2]}
            \else
              {\marginnote{#1}[#2]}
            \fi}
\newcommandx{\rightmarginnote}[2][2=0pt]
           {\checkoddpage
            \ifoddpage
              {\marginnote{#1}[#2]}
            \else
              {\reversemarginpar\marginnote{#1}[#2]}
            \fi}

\begin{document}
Some text.
\rightmarginnote{On the right}%
\leftmarginnote{On the left}%

Some more text.

Some more text.

Some more text.

Some more text.
\rightmarginnote{Still right}%
\leftmarginnote{Still left}%

Some more text.

Some more text.

\raggedbottom
\pagebreak

Some text.
\rightmarginnote{On the right!}%
\leftmarginnote{On the left!}%

Some more text.

Some more text.

Some more text.
\rightmarginnote{Still right!}%
\leftmarginnote{Still left!}%

Some more text.

Some more text.

\end{document}

I changed the papersize to A5, to get a full compact screenshot.


text:
Q: Agent works on Dialogflow, but not on Actions on Google I don't know how to use Webhook or another language, so I am working with basic options of Dialogflow.
The problem is that my agent works on Dialogflow, but not on Actions on Google.
I made a list of google assistant. It has two options.
The one is "What is that?", and another is "Don't choose this".
I also add an event 'actions_intent_OPTION'. (This intent name is 'First'.)
And I want to allow users to input or choose only "What is that?".
If users input "What is that?", AI will say that "It's correct.".(This intent name is 'Second'.)
If users input another words or sentences except for "What is that?", AI will say that "It's wrong. Please send correct answer again."(This intent is Fallback Intent.).
For this, I made an entity of "What is that?" and I checked required option.
Like this.
And by using contexts and Fallback intent, If users input another words or sentences, Fallback intent responds.The output context of Fallback is Second Intent.
First Intent's Input context: question /
First Intent's Output context: Answer (lifespan:1)
Second Intent's Input context: Answer /
Second Intent's Output context: Anotherquestion
Fallback intent's Input context: Answer /
Fallback intent's Output context: Answer (lifespan:1)
It works well on dialogflow.
First Second
However, It doesn't work on Actions on Google or mobile Google Assistant.
If I choose "What is that?", It says "It's wrong. Please send correct answer again."
I cannot find any problems.
Please help me.. ;(


text:
Q: Is it possible to do execute a set of steps which includes system restart in node js? I am having a project in node JS in which I have to execute a set of steps. One of such steps is system restart (I know system restart is possible). Is it possible in NodeJS to restart the system (windows) and pick up where we left and execute the remaining steps that were there after the reboot?  I have a few steps before the reboot and few steps after the reboot.

A: You could accomplish this by putting part the part of your script you want run before in one Node.js file, the part you want run after in another file, then putting everything into a PowerShell workflow and just running that PS script.
workflow Run-And-Reboot {
  node /path/to/scriptPart1.js
  Restart-Computer -Wait
  node /path/to/scriptPart2.js
}


text:
Q: Get the background color of textbox I'm new to Jquery , please pardon my ignorance. I have a page where I set textboxes with different colors on page load, the requirement is to filter on a particular color i.e to display only 1 color on click of particular checkbox.
What I'm trying to do:
I'm traversing through the html table row by row, trying to get the current color of each text box, if the color matches keep it else hide the row where the textbox color does not match. I have seen various posts which show how to set the color but not how to retrieve the current color of the textBox, tried on the same lines but no luck, please help.
$('input[id$=cbx]').click(function () {
 var v = document.getElementById("<%=TextBox3.ClientID%>");
 // to get the color value of current text box
 var v2 = v.style.background
 // below also does not work
 var v2 = v.style.background.val()
 // below also does not work
 var v3= v.css('background-color');
 if (v2 == "green")
  {
   $('[id$=user1]').hide();
  }

A: 'green' is rgb(0, 128, 0)
try this one.
$('input[id$=cbx]').click(function () {
    var v = $('#<%=TextBox3.ClientID').css('background-color');
    if( v== 'rgb(0, 128, 0)') {
        $('[id$=user1]').hide();
    }
});

A: I think the propbelm is with this line. Since you have not shared the HTML it is not possible to understand if there is a style attribute to this element.
v.style.background

If there is no style attribute v.style will give CSSStyleDeclaration but all will have empty value.
If there is a style attribute defined in the element like this below example
HTML
<input id= "abc" type = "text" class = "red" style = "background:red">

JS
var v = document.getElementById("abc");
var v2 = v.style.background
console.log(v.style.background); // red

DEMO
will log red
If there is no style attribute defined on the element, you can use getComputedStyle property to get the value. But in this case the value will be in rgb format.
var v = document.getElementById("abc");
var v2 = window.getComputedStyle(v, null);
console.log(v2.background)

DEMO2

A: You can get background color using jQuery as follows
var bgColor = $('#textbox-id-here').css('background-color');

You will get RGB value. If you want to convert this to hex value, you can use following function
function rgb2hex(rgb){
 rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
 return (rgb && rgb.length === 4) ? "#" +
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}

EDIT
Assume you have table to hold your textboxes. then you can do something like this
$('#table-id tr td input[type=text]').each(function(){
  var bg = rgb2hex($(this).css('background-color'));
  if(bg==='#ff0000'){
    $(this).hide();
  }
});


text:
Q: fgets is limited to 1024 bytes - what can I use instead? I want to read from user's input string of size 16000bytes. fgets only reads 1024  bytes. What can I use instead? I am writing in c and this is my code right now. Is it that I am not using malloc?
char str[16392];

while(fprintf(stderr, "> "), fgets(str, 16392, stdin), !feof(stdin)) { }

Also, readline seems to work.
  while(line = readline("> "), !feof(stdin)) {
    printf("You entered: %s\n", line);
    free(line);
  }

A: Do not replace fgets() with a worse option. fgets() has no limit.
#include <stdio.h>
#include <stdlib.h>

    char *buffer;
    size_t size;
    size = 10000000; /* 10m */
    buffer = malloc(size);
    if (!buffer) /* error */;
    if (fgets(buffer, size, stdin) == NULL) /* error */;
    // ...
    free(buffer);

A: Perhaps there is an implementation where fgets() has a 1024 byte limit; however, this is not something I have seen before.
An alternative might be fread().


text:
Q: Vertical scrollbar for legend box I'm using legend scrollbar tool in the teechart to show scrollbar for legend box. Now horizontal scroll bar is visible at bottom position but  I'm looking for a way to display a vertical scrollbar for legend box which in some cases could contain more than 50 legend items.

A: Unfortunately, the legend scrollbar always is drawn in same position as legend alignment. But,  you can prevent possible problems in the cases where legend is aligned to bottom and contains a lot of legend items using the property MaxNumRow. The code below shows you how can do that
  public Form1()
        {
            InitializeComponent();
            InitializeChart();
        }
        private void InitializeChart()
        {
            tChart1.Aspect.View3D = false;
            tChart1.Dock = DockStyle.Fill;
            Steema.TeeChart.Tools.LegendScrollBar sclenged = new Steema.TeeChart.Tools.LegendScrollBar(tChart1.Chart);
            for ( int i=0; i<50; i++)
            {
                new Steema.TeeChart.Styles.FastLine(tChart1.Chart);
                tChart1[i].FillSampleValues(10);
            }

            tChart1.Legend.Alignment = Steema.TeeChart.LegendAlignments.Bottom;
            tChart1.Legend.MaxNumRows = 3;
        }

A: As described by Sandra, the TeeChart Legend places the scrollbar at the bottom of the Legend, horizontally, when aligned Top or Bottom of the Chart and on the right, vertically, when aligned to Left or Right. So an option for the vertical scroll is to position the Legend to the right of the Chart.
If you prefer the Legend at the bottom and you specifically require a vertical scrollbar, you can override the scrollbar location by custom setting the Legend position and dimensions. Note when overriding position, that the scrollbar horizontal or vertical behaviour will still respect the original Top/Bottom or Left/Right alignment of the Legend. Hence, for the Legend you want to achieve you can do something like this:
  tChart1.Legend.Alignment = Steema.TeeChart.LegendAlignments.Right;
  tChart1.Legend.CustomPosition = true; //Chart will now redimension, ignoring Legend location. Your responsibility now.
  tChart1.Panel.MarginBottom = 35; //make room. This is % .. can set as pixels, see MarginUnits
  tChart1.Legend.Left = tChart1.Axes.Left.Position; //lineup with Left Axis
  tChart1.Legend.Top = tChart1.Axes.Bottom.Position + tChart1.Axes.Bottom.Labels.Font.Size + 20; //make Top relative to Chart bottom axis location
  tChart1.Legend.AutoSize = false; //now set dimension you require
  tChart1.Legend.Width = 130; //your settings
  tChart1.Legend.Height = 70;

Downside is you're not offered multiple columns with this approach (as the Legend still thinks it's vertical); the previous suggestion (MaxNumRows on a bottom Legend) may still be more desirable.


text:
Q: Is there a cleaner way to use try-with-resource and PreparedStatement? Here is the Main.java:
package foo.sandbox.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {
    public static void main(String[] args) {
        final String SQL = "select * from NVPAIR where name=?";
        try (
                Connection connection = DatabaseManager.getConnection();
                PreparedStatement stmt = connection.prepareStatement(SQL);
                DatabaseManager.PreparedStatementSetter<PreparedStatement> ignored = new DatabaseManager.PreparedStatementSetter<PreparedStatement>(stmt) {
                    @Override
                    public void init(PreparedStatement ps) throws SQLException {
                        ps.setString(1, "foo");
                    }
                };
                ResultSet rs = stmt.executeQuery()
        ) {
            while (rs.next()) {
                System.out.println(rs.getString("name") + "=" + rs.getString("value"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

And here is DatabaseManager.java
package foo.sandbox.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Initialize script
 * -----
 * CREATE TABLE NVPAIR;
 * ALTER TABLE PUBLIC.NVPAIR ADD value VARCHAR2 NULL;
 * ALTER TABLE PUBLIC.NVPAIR ADD id int NOT NULL AUTO_INCREMENT;
 * CREATE UNIQUE INDEX NVPAIR_id_uindex ON PUBLIC.NVPAIR (id);
 * ALTER TABLE PUBLIC.NVPAIR ADD name VARCHAR2 NOT NULL;
 * ALTER TABLE PUBLIC.NVPAIR ADD CONSTRAINT NVPAIR_name_pk PRIMARY KEY (name);
 *
 * INSERT INTO NVPAIR(name, value) VALUES('foo', 'foo-value');
 * INSERT INTO NVPAIR(name, value) VALUES('bar', 'bar-value');
 */
public class DatabaseManager {
    /**
     * Class to allow PreparedStatement to initialize parmaters inside try-with-resource
     * @param <T> extends Statement
     */
    public static abstract class PreparedStatementSetter<T extends Statement> implements AutoCloseable {
        public PreparedStatementSetter(PreparedStatement pstmt) throws SQLException {
            init(pstmt);
        }

        @Override
        public void close() throws Exception {
        }

        public abstract void init(PreparedStatement pstmt) throws SQLException;
    }

    /* Use local file for database */
    private static final String JDBC_CONNECTION = "jdbc:h2:file:./db/sandbox_h2.db;MODE=PostgreSQL";

    static {
        try {
            Class.forName("org.h2.Driver");  // Init H2 DB driver
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return Database connection
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(JDBC_CONNECTION, "su", "");
    }
}

I am using H2 database for simplicity since it's a file based one that is easy to create and test on.
So everything works and resources get cleaned up as expected, however I just feel there may be a cleaner way to set the PreparedStatement parameters from inside the try-with-resources block (and I don't want to use nested try/catch blocks as those look 'awkward').  Maybe there already exists a helper class in JDBC that does just this, but I have not been able to find one.
Preferably with a lambda function to initialize the PreparedStatement but it would still require allocating an AutoCloseable object so it can be inside the try-with-resources.

A: First off, your PreparedStatementSetter class is awkward:

*

*it is a typed class but the type is not used.

*the constructor is explicitly calling an overridable method, which is a bad practice.

Consider the following interface instead (inspired from the Spring interface of the same name).
public interface PreparedStatementSetter {
    void setValues(PreparedStatement ps) throws SQLException;
}

This interface defines a contract of what a PreparedStatementSetter is supposed to do: set values of a PreparedStatement, nothing more.
Then, it would be better to do the creation and initialization of the PreparedStatement inside a single method. Consider this addition inside your DatabaseManager class:
public static PreparedStatement prepareStatement(Connection connection, String sql, PreparedStatementSetter setter) throws SQLException {
    PreparedStatement ps = connection.prepareStatement(sql);
    setter.setValues(ps);
    return ps;
}

With this static method, you can then write:
try (
    Connection connection = DatabaseManager.getConnection();
    PreparedStatement stmt = DatabaseManager.prepareStatement(connection, SQL, ps -> ps.setString(1, "foo"));
    ResultSet rs = stmt.executeQuery()
) {
    // rest of code
}

Notice how the PreparedStatementSetter was written here with a lambda expression. That's one of the advantage of using an interface instead of an abstract class: it actually is a functional interface in this case (because there is a single abstract method) and so can be written as a lambda.

A: Extending from @Tunaki's answer, it's also possible to factor-in the try-with-resources and rs.executeQuery() such that the DatabaseManager handles all of this for you and only asks for the SQL, a PreparedStatementSetter and a ResultSet handler.
This would avoid repeating this everywhere you make a query. Actual API will depend on your usage however – e.g. will you make several queries with the same connection?
Supposing you will, I propose the following:
public class DatabaseManager implements AutoCloseable {

    /* Use local file for database */
    private static final String JDBC_CONNECTION = "jdbc:h2:file:./db/sandbox_h2.db;MODE=PostgreSQL";

    static {
        try {
            Class.forName("org.h2.Driver");  // Init H2 DB driver
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private final Connection connection;

    private DatabaseManager() throws SQLException {
        this.connection = getConnection();
    }

    @Override
    public void close() throws SQLException {
        connection.close();
    }

    public interface PreparedStatementSetter {
        void setValues(PreparedStatement ps) throws SQLException;
    }

    public interface Work {
        void doWork(DatabaseManager manager) throws SQLException;
    }

    public interface ResultSetHandler {
        void process(ResultSet resultSet) throws SQLException;
    }

    /**
     * @return Database connection
     * @throws SQLException
     */
    private static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(JDBC_CONNECTION, "su", "");
    }

    private PreparedStatement prepareStatement(String sql, PreparedStatementSetter setter) throws SQLException {
        PreparedStatement ps = connection.prepareStatement(sql);
        setter.setValues(ps);
        return ps;
    }

    public static void executeWork(Work work) throws SQLException {
        try (DatabaseManager dm = new DatabaseManager()) {
            work.doWork(dm);
        }
    }

    public void executeQuery(String sql, PreparedStatementSetter setter, ResultSetHandler handler) throws SQLException {
        try (PreparedStatement ps = prepareStatement(sql, setter);
            ResultSet rs = ps.executeQuery()) {
            handler.process(rs);
        }
    }
}

It wraps the connection as an instance field of DatabaseManager, which will handle the life-cycle of the connection, thanks to its implementation of AutoCloseable.
It also defines 2 new functional interfaces (additionally to @Tunaki's PreparedStatementSetter) :

*

*Work defines some work to do with a DatabaseManager via the executeWork static method

*ResultSetHandler defines how the ResultSet must be handled when executing a query via the new executeQuery instance method.

It can be used as follows:
    final String SQL = "select * from NVPAIR where name=?";
    try {
        DatabaseManager.executeWork(dm -> {
            dm.executeQuery(SQL, ps -> ps.setString(1, "foo"), rs -> {
                while (rs.next()) {
                    System.out.println(rs.getString("name") + "=" + rs.getString("value"));
                }
            });
            // other queries are possible here
        });
    } catch (Exception e) {
        e.printStackTrace();
    }

As you see, you don't have to worry about resource handling any
more.
I left SQLException handling outside the api since you might want to let it propagate.
This solution was inspired by Design Patterns in the Light of Lambda Expressions by Subramaniam.

A: I found another way of doing this which may be helpful to people:
PreparedStatementExecutor.java:
/**
 * Execute PreparedStatement to generate ResultSet
 */
public interface PreparedStatementExecutor {
    ResultSet execute(PreparedStatement pstmt) throws SQLException;
}

PreparedStatementSetter.java:
/**
 * Lambda interface to help initialize PreparedStatement
 */
public interface PreparedStatementSetter {
    void prepare(PreparedStatement pstmt) throws SQLException;
}

JdbcTriple.java:
/**
 * Contains DB objects that close when done
 */
public class JdbcTriple implements AutoCloseable {
    Connection connection;
    PreparedStatement preparedStatement;
    ResultSet resultSet;

    /**
     * Create Connection/PreparedStatement/ResultSet
     *
     * @param sql String SQL
     * @param setter Setter for PreparedStatement
     * @return JdbcTriple
     * @throws SQLException
     */
    public static JdbcTriple create(String sql, PreparedStatementSetter setter) throws SQLException {
        JdbcTriple triple = new JdbcTriple();
        triple.connection = DatabaseManager.getConnection();
        triple.preparedStatement = DatabaseManager.prepareStatement(triple.connection, sql, setter);
        triple.resultSet = triple.preparedStatement.executeQuery();
        return triple;
    }

    public Connection getConnection() {
        return connection;
    }

    public PreparedStatement getPreparedStatement() {
        return preparedStatement;
    }

    public ResultSet getResultSet() {
        return resultSet;
    }

    @Override
    public void close() throws Exception {
        if (resultSet != null)
            resultSet.close();
        if (preparedStatement != null)
            preparedStatement.close();
        if (connection != null)
            connection.close();
    }
}

DatabaseManager.java:
/**
 * Initialize script
 * -----
 * CREATE TABLE NVPAIR;
 * ALTER TABLE PUBLIC.NVPAIR ADD value VARCHAR2 NULL;
 * ALTER TABLE PUBLIC.NVPAIR ADD id int NOT NULL AUTO_INCREMENT;
 * CREATE UNIQUE INDEX NVPAIR_id_uindex ON PUBLIC.NVPAIR (id);
 * ALTER TABLE PUBLIC.NVPAIR ADD name VARCHAR2 NOT NULL;
 * ALTER TABLE PUBLIC.NVPAIR ADD CONSTRAINT NVPAIR_name_pk PRIMARY KEY (name);
 *
 * INSERT INTO NVPAIR(name, value) VALUES('foo', 'foo-value');
 * INSERT INTO NVPAIR(name, value) VALUES('bar', 'bar-value');
 */
public class DatabaseManager {
    /* Use local file for database */
    private static final String JDBC_CONNECTION = "jdbc:h2:file:./db/sandbox_h2.db;MODE=PostgreSQL";

    static {
        try {
            Class.forName("org.h2.Driver");  // Init H2 DB driver
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return Database connection
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(JDBC_CONNECTION, "su", "");
    }

    /** Prepare statement */
    public static PreparedStatement prepareStatement(Connection conn, String SQL, PreparedStatementSetter setter) throws SQLException {
        PreparedStatement pstmt = conn.prepareStatement(SQL);
        setter.prepare(pstmt);
        return pstmt;
    }

    /** Execute statement */
    public static ResultSet executeStatement(PreparedStatement pstmt, PreparedStatementExecutor executor) throws SQLException {
        return executor.execute(pstmt);
    }
}

Main.java:
public class Main {
    public static void main(String[] args) {
        final String SQL = "select * from NVPAIR where name=?";
        try (
            JdbcTriple triple = JdbcTriple.create(SQL, pstmt -> { pstmt.setString(1, "foo"); })
        ){
            while (triple.getResultSet().next()) {
                System.out.println(triple.getResultSet().getString("name") + "=" + triple.getResultSet().getString("value"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

While this doesn't handle cases where you may need to return an ID from insert or transactions, it does offer a quick way to run a query, set parameters and get a ResultSet, which in my case is bulk of the DB code.

A: A much cleaner solution would simply be to nest your try-with-resource calls
try (Connection connection = dataSource.getConnection())
{
    try (PreparedStatement stmt = connection.prepareStatement(query))
    {
        stmt.setString(1, value);

        try (ResultSet resultSet = stmt.executeQuery()) {
            // tickle your data here...
        }
    }
}
catch (Exception e) {
    log.error("Oopsie daisy!", e);
}


text:
Q: There is a 3-connected 5-regular simple $n$-vertex planar graph iff $n$ satisfies....? Is there any characterization on the set of integers $n$ such that there is a 3-connected 5-regular simple $n$-vertex planar graph?

A: There is a 3-connected 5-regular simple $n$-vertex planar graph if and only if $n=12$ or $n \ge 16$ is even.  See Recursive generation of 5-regular graphs by Mahdieh Hasheminezhad, Brendan D. McKay, Tristan Reeves in WALCOM: Algorithms and Computation, eds. Das and Uehara, Lecture Notes in Computer Science, vol 5431, Springer 2009.  The number of such graphs is given in OEIS A308489.
They use a set of 7 graphs that are irreducible under a system of expansions & reductions and, as is common for contemporary graph theory, computer assistance.  E.g., "The program completed execution in 21 seconds.  In total, 39621 induced subgraphs were found..."

A: There are no such graphs when $n$ is odd, by the handshaking lemma.
Conversely, for all even $n \geq 224$, we claim such a graph exists.
In particular, given two planar 5-regular graphs $G$, $H$ each drawn on the surface of a sphere, we can define the 'connected sum' of the graphs as follows:

*

*remove a small disk (containing one vertex) from the sphere on which $G$ is drawn;

*remove a small disk (containing one vertex) from the sphere on which $H$ is drawn;

*combine the two resulting hemispheres at their equator.

The resulting graph (which may depend on the chosen vertices) has $|G| + |H| - 2$ vertices, and inherits the planarity, 5-regularity, and 3-connectedness of $G$ and $H$.
Now, given an even integer $n \geq 224$, we can find integers $i, j \geq 0$ such that $n = 2 + 10i + 58j$. Then we can construct an $n$-vertex graph with the desired properties by taking the connected sum of $i$ copies of the icosahedron and $j$ copies of the snub dodecahedron.

This leaves finitely many values of $n$ to check, namely the even numbers between 14 and 222.


text:
Q: React: stopPropagation() does not seem to working? I have a footer component with a function to toggle a modal component. In the modal component I have a wrapper for a background and the modal nested inside that wrapper. I have set the toggleModal function as a prop and adding it to the wrapper of the modal. I don't want the modal itself to have this click function assigned to it so I used stopPropagation() in my function to stop the event bubbling although this does not seem to be working.
Footer component:
const Footer = () => {
  const [showModal, setShowModal] = useState(false);

  function toggleModal(e) {
    e.stopPropagation();
    setShowModal(!showModal);
  }
  return (

      <button onClick={toggleModal}>Modal toggle</button>
      <Modal show={showModal} toggle={toggleModal}>This is a modal</Modal>

  )
}

Modal component:
const Modal = () => {
  return (

         X

       {props.children}

  )
}

A:
to stop the event bubbling although this does not seem to be working.

Did you mean the event bubbling does not work, or just the modal not working in general? I found two code problems, which when fixed seem to make the modal work. In addition, you may want the behaviour of e.preventDefault(), but I'm not sure from your question.
Problems & Fixes:

*

*Missing props in method signature: const Modal = (props) => {

*Not using show prop to show/hide modal div: props.show &&

stopPropagation & preventDefault
To see the behaviour differences of stopPropagation and preventDefault, try adding this radio beneath your button. You'll need to refresh the page each time you need to reset the radio to experiment.
<input type="radio" name="gender" value="male" onClick={toggleModal}/>
preventDefault stops the radio from being set, it prevents the default behaviour of the radio component from setting a value.
stopPropagation will not stop the radio from being set, because it only stops the event bubbling up to parent elements. It would be useful on a text <input> to prevent events like the Enter key from affecting a parent <form> element to submit (if that were desired).
I hope this helps solve your issue.

A: Here's what happens:

*

*.modal or another element inside it is clicked. No listener is attached to the element, so the event continues bubbling up to the ancestors.

*The event reaches .modal__wrapper, which has a listener for the click event. The listener doesn't differentiate which element was the direct target of the event: the element itself or one of its descendants. props.toggle() is fired even though the target was another element inside the wrapper. The listener stops propagation. The event stops bubbling, but there's no one listening to it higher in the tree anyway.

I would suggest you attaching a ref to the wrapper and checking whether the event target was the wrapper itself.
The modal component would look like this:
const Modal = (props) => {
  const wrapperRef = useRef();

  const handleClick = e => {
    if(e.target === wrapperRef.current) {
      props.toggle(e);
    }
  };

  return (

         X

       {props.children}

  );
};


text: Q: Google Static Maps - Adding custom labels I have a Static Google Map (without the use of any JavaScript) with some markers. I would like to add some descriptions to the markers but since the label is only 1 character long, I don't know how to do it. Any idea?


text:
Q: Create a simple report with text strings and plots using loop in r I'm trying to find a way to loop through rows of a data frame to produce a report (preferably in PDF) that includes strings the length of a paragraph or longer, plots, and data values for each day of the year. I've exported PDFs of just plots in a loop before, but I can't find a solution to include text of any considerable length.
Imagine I have a data frame like this:
Date <- c("01/01/2014", "01/02/2014", "01/03/2014")
TextString <- c("imagine this is a paragraph or longer 1", "imagine this is a paragraph or longer 2", "imagine this is a paragraph or longer 3")
TableData1 <- c(10000, 9000, 8000)
TableData2 <- c(6, 5, 4)
PlotData3 <- c(22, 11, 21)
PlotData4 <- c(6, 7, 8)
PlotData5 <- c(21, 17, 14)
Report <- data.frame(Date, TextString, TableData1, TableData2, PlotData3, PlotData4, PlotData5)

And I would like the report to be structured something like this in the PDF:
01/01/2014
imagine this is a paragraph or longer 1
"TableData1:" 10000
"TableData2:" 6
*plot* pie(c(Report$PlotData3[1], Report$PlotData4[1], Report$PlotData5[1]))

01/02/2014
imagine this is a paragraph or longer 2
"TableData1:" 9000
"TableData2:" 5
*plot* pie(c(Report$PlotData3[2], Report$PlotData4[2], Report$PlotData5[2]))

01/03/2014
imagine this is a paragraph or longer 3
"TableData1:" 8000
"TableData2:" 4
*plot* pie(c(Report$PlotData3[3], Report$PlotData4[3], Report$PlotData5[3]))

Can anyone point me in the right direction? I looked at some tutorials for knitr since it seems applicable, but I wasn't sure it would loop through data in this manner.

A: This is easily done using R Markdown.  If you are using RStudio, this becomes extremely simple.  Follow these steps:

*

*Open a new R Markdown file. (File -> New File -> R Markdown...

*Pick a title and output format.  (These can also be modified in the resulting header)

*Paste the contents below into the R Markdown file.

*Click on the Knit button.

*RStudio automatically processes the R Markdown into the desired format.

The following .Rmd (R Markdown) file will generate what you want in HTML.  Changing the output line in the header to pdf_document should result in a PDF file if you have LaTeX installed on your computer.
---
title: "Test PDF"
author: "Daddy The Runner"
date: "Monday, January 05, 2015"
output: html_document
---

```{r echo=FALSE, comment=NA}
Date <- c("01/01/2014", "01/02/2014", "01/03/2014")
TextString <- c("imagine this is a paragraph or longer 1", "imagine this is a paragraph or longer 2", "imagine this is a paragraph or longer 3")
TableData1 <- c(10000, 9000, 8000)
TableData2 <- c(6, 5, 4)
PlotData3 <- c(22, 11, 21)
PlotData4 <- c(6, 7, 8)
PlotData5 <- c(21, 17, 14)
Report <- data.frame(Date, TextString, TableData1, TableData2, PlotData3, PlotData4, PlotData5, stringsAsFactors = FALSE)

for (i in 1:nrow(Report)) {
  cat(Report$Date[i], "\n")
  cat(Report$TextString[i], "\n")
  cat("TableData1: ", Report$TableData1[i], "\n")
  cat("TableData2: ", Report$TableData2[i], "\n")
  pie(c(Report$PlotData3[i], Report$PlotData4[i], Report$PlotData5[i]))
  cat("\n")
}
```


text:
Q: System.out.println Printing itself when printing I'm working with a list and I am trying to print the contents to see if I am getting the result that I need. But when I println it, the System.out.println prints itself in it's own print (see below)
09-08 12:18:23.482    7718-7718/com.example I/System.out﹕ IMAGES are: [
09-08 12:18:23.482    7718-7718/com.example I/System.out﹕ [ 09-08 12:18:23.482 7718: 7718 I/System.out ]
__,__IwjV3bxFh7ADUCcZFCLsczmadO90TKeg.jpg
09-08 12:18:23.482    7718-7718/com.example I/System.out﹕ [ 09-08 12:18:23.482  7718: 7718 I/System.out ]
__,__CmonqJYgM8hiy4mHU9UmWDbNNbI4jjcb.jpg,
09-08 12:18:23.482    7718-7718/com.example I/System.out﹕ [ 09-08 12:18:23.482  7718: 7718 I/System.out ]
__,__AonUsfgTZpcdHUg4njUtExFC53E6IKRq.jpg, , , ]

Here is the code where I print the list:
final List<String> images = db.getAPIImages();
    for (String e : images){
        System.out.println("IMAGES are: " + e);
    }

I'm not sure if this is just an issue with Android Studio, but when I look in my db, the System.out.println isn't being stored so I believe it's just a print issue. I'd greatly appreciate some help.
USING Log.d
When using Log.d, I get the following output:
09-08 12:29:15.925  13757-13757/com.example D/IMAGES are:﹕ [
n8iQYdmU4HQkVJRTvgJfen7I8mUZ7oWW.jpg
poCcNRCTKeVtxbmyGiIaq5OfFg3b5Vce.jpg, , , , ]

From looking at that, I'm guessing a new line character is present between the two jpgs. How can I test for that and replace with a ","?

A: Including temp1.replace(System.getProperty("line.separator"), has fixed my problem. Here is the full code:
for (String e : images){
        String temp = e.replaceFirst(strSeparator, "");
        String temp1 = temp.replace(strSeparator, ", ");
        String temp2 = temp1.replace(System.getProperty("line.separator"), "");
        System.out.println("IMAGES are: " + temp2);
    }


text:
Q: extract number from a string  i have the following string
Device Enabled (126):   1

can i extract in a variable VAR only 126 and NOT (126) ?
p.s 126 = random number
please help me !
EDIT
i paste my script so u can understand the solution
ID=`xinput list | grep -i TouchPad | awk -F= '{ print $2}' | awk '{print $1}'`
VALOREENABLE=`xinput list-props $ID | grep -i Enabled |awk '{print $3}'`
VALORESENSE=`xinput list-props $ID | grep -i Profile |awk '{print $3}'

in my case VALOREENABLE = (126)
and VALORESENSE (256)  i want 126, 256 only without () :(`

A: echo "Device Enabled (126):   1" | grep -P -o "[0-9]+" | head -1

*

*echo puts your string into the pipe

*that goes to grep, which is a program to apply regular expressions. The option -P enables PEARL like behaviour (which enables you to use the +), and the -o tells grep to only output the matching part of the string. Each match will be printed to a new line

*use head to pick the line you want. Since we want the first number, we will pick the first line. If you were interested in the one, you would do head -2.

A: One way using sed:
sed 's/.*(\([^)]*\)).*/\1/' <<<"Device Enabled (126):   1"

Result:
126

so for your script you could try:
#!/bin/bash

ID=`xinput list | grep -i TouchPad | awk -F= '{ print $2}' | awk '{print $1}'`
VALOREENABLE=`xinput list-props $ID | grep -i Enabled |awk '{print $3}'`
#VALORESENSE=`xinput list-props $ID | grep -i Profile |awk '{print $3}'`
VALORESENSE=`xinput list-props $ID | grep -i Profile | awk '{print $4}' | sed 's/.*(\([^)]*\)).*/\1/' `
echo $VALORESENSE

A: There are lots of ways to do it. Here's the one that first comes to mind for me:
VALOREENABLE=`xinput list-props $ID | grep -i Enabled | grep -o "(.*)" | tr -d '()'`
VALORESENSE=`xinput list-props $ID | grep -i Profile | grep -o "(.*)" | tr -d '()'`

A: OK, I will toss in my 2c, you can do it directly with awk
ID=`xinput list | grep -i TouchPad | awk -F= '{ print $2}' | awk '{print $1}'`
VALOREENABLE=`xinput list-props $ID | awk '/Enabled/ {print substr ($3, 2, 3) }'`
VALORESENSE=`xinput list-props $ID | awk '/Profile/ {print substr ($3, 2, 3) }'

A: The shell can do it:
str="Device Enabled (126):   1"
old_IFS=$IFS
IFS="()"
words=($str)
number=${words[1]}

Or, if you really like using awk, set the field separator to be either parenthesis
number=$(awk -F '[()]' '{print $2}' <<< "Device Enabled (126):   1")

Using your example code, I'd write:
ID=$(xinput list | awk -F= '/TouchPad/ {split($2, a, /[[:space:]]\+/); print a[1]}')
PROPS=$(xinput list-props $ID)
VALOREENABLE=$(awk -F '[()]' '/Enabled/ '{print $2}' <<< "$PROPS")
VALORESENSE=$(awk -F '[()]' '/Profile/ '{print $2}' <<< "$PROPS")

A: Extracting the ID could be simplified as so (note the use of $() instead of backticks):
ID=$(xinput list | awk '/TouchPad/{sub(/^.*id=/,"");sub(/\[.*/,"");print}')

Personally, I'd use perl in extracting the numbers:
VALOREENABLE=$(xinput list-props $ID | perl -ne 's/.*\((.*)\).*/$1/ and print if /Enabled/' )
VALORESENSE=$(xinput list-props $ID | perl -ne 's/.*\((.*)\).*/$1/ and print if /Profile/' )


text:
Q: How can I know from where are the current threads? I have a server in C# that uses sockets to communicate with its clients. The problem comes when on certain occasions the number of threads used by the server suddenly increases.
Use the following function to get the number of Themes:
Process.GetCurrentProcess().Threads.Count

I want to know if there is any way to know where they come from in order to fix the code. I have tried with the thread window in Debug mode in Visual Studio, but it does not give me any information about those threads, they have no name and no information.

A: You can name threads like this so you know where they came from:
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
Console.WriteLine("This is {0}", th.Name);

Make sure you have "using System.Threading;" in your program.
Example pulled from: https://www.tutorialspoint.com/csharp/csharp_multithreading.htm


text:
Q: How to build a typescript interface for autoNumeric.js I would like to create a typescript file for autoNumeric.js in the same fashion as accounting.d.ts. I cannot figure out the signature of the method autoNumeric. Thank you!

A: If its : https://github.com/BobKnothe/autoNumeric then a quick start:
interface JQuery{
    autoNumeric:any;
}

This will let you do:
$('someSelector').autoNumeric('init', {options});


text:
Q: Does the mySql WEEK() function work for columns with type DATE? Does the WEEK() function work for columns with type DATE or does it require a column to have type DATETIME?
Various SO searches suggest this should work, but this statement provides an empty result:
SELECT * FROM tbl_benutzer WHERE WEEK(dob,1) = WEEK(CURDATE(),1) ORDER BY id DESC

For example, a recordset where dob is 1972-07-09 is not recognised when today's date is 2014-07-07.
Many thanks for any help!

A: You can use the function DATE, it extract only the date part from a date/datetime value.
Your query will be like this:
SELECT * FROM tbl_benutzer WHERE WEEK(DATE(dob),1) = WEEK(CURDATE(),1) ORDER BY id DESC


text:
Q: Match text outside of html tags Before anyone says it I know I should use a proper parser but for my use case it is better to use a regular expression.
I have the following regex to try and match text outside of html tags:
(?<!<[^>]*)(?<Text>.+?)

However this seems to be matching the opening bracket of the tag, i.e. <. How can I fix this?
Example input:
some bold text

Expected:
some bold text

Got:
<some <bold< text<

Link to RegexStorm.

A: The problem is that you are using . that matches any character. Replace it with a negated character class, like [^<>] that matches any char but < and > and use a greedy quantifier * (to match 0 or more occurrences) or + (to match 1 or more occurrences):
(?<!<[^>]*)(?<Text>[^<>]*)

See the regex demo
BTW, using (?<Text>.+?) at the end of the pattern only makes the regex engine match 1 char since the +? is a lazy quantifier matching 1 or more occurrences but as few as possible (and since 1 is enough, it will always match just 1 char). Usually, there must be some other pattern after such a lazily quantified one, else, it usually does not fetch the right texts.


text:
Q: What pandas operation will help me do a groupby and aggregate by column combinations? Here's an example of what I am trying to do:
   bar  foo   o1   o2 thing
0    1    1  0.0  3.3     a
1    1    1  1.1  4.4     a
2    3    2  2.2  5.5     b
   foo_1_bar_3_o1  foo_1_bar_3_o2  foo_2_bar_3_o1  foo_2_bar_3_o2  \
0             NaN             NaN             NaN             NaN
1             NaN             NaN             2.2             5.5

   foo_1_bar_1_o1  foo_1_bar_1_o2  foo_2_bar_1_o1  foo_2_bar_1_o2 thing
0             1.1             7.7             NaN             NaN     a
1             NaN             NaN             NaN             NaN     b

The first is my input DataFrame and the second is my desired output DataFrame (NaNs could be substituted with 0's).
This should be some sort of a groupby (on column thing) and then some kind of an aggregating function on values in the columns o1 and o2 that aggregate based on all possible combinations of the values of foo and bar. Notice that foo_1_bar_2_o2 is 7.7 because it is the sum over the column o2 when foo == 1 && bar == 2 for the group 'a'.
I've tried researching dcast, crosstab, and pivot in pandas but none seem to satisfy what I am trying to do.
I wrote base Python code that does what I want, but, again, I would like to translate it to a more friendly format using already existing functions. I don't believe my use-case is obscure enough for this to not be possible.
Below is the base Python code for this operation.
import pandas as pd
import numpy as np
import itertools

df = pd.DataFrame({'thing': ['a', 'a', 'b'],
                   'foo': [1, 1, 2],
                   'bar': [1, 1, 3],
                   'o1': [0.0, 1.1, 2.2],
                   'o2': [3.3, 4.4, 5.5]})

key_columns = ['foo', 'bar']

key_value_pairs = [df[key].values.tolist() for key in key_columns]

key_value_pairs = list(set(itertools.product(*key_value_pairs)))

output_columns = ['o1', 'o2']

def aggregate(df):
  new_columns = []
  for pair in key_value_pairs:
    pair = list(zip(key_columns, pair))
    new_column = '_'.join(['%s_%d' % (key, value) for key, value in pair])
    for o in output_columns:
      criteria = list()
      for key, value in pair:
        criterion = (df[key] == value)
        criteria.append(criterion)
      new_columns.append('%s_%s' % (new_column, o))
      df[new_columns[-1]] = df[np.logical_and.reduce(criteria)][o].sum()
  return df.head(1)[new_columns + ['thing']]

things = df['thing'].value_counts().index.tolist()

groups = df.groupby('thing')

dfs = []
for thing in things:
  dfs.append(aggregate(groups.get_group(thing).reset_index()))
  #print(aggregate(groups.get_group(thing).reset_index(drop=True)))

print(df)
print(pd.concat(dfs).reset_index(drop=True))

A: I try create dynamic solution:
key_columns = ['foo', 'bar']
output_columns = ['o1', 'o2']

First add key_columns strings to values with radd:
df[key_columns] = (df[key_columns].astype(str)
                                  .radd(pd.Series(key_columns,index=key_columns) + '_'))

print (df)
     bar    foo   o1   o2 thing
0  bar_1  foo_1  0.0  3.3     a
1  bar_1  foo_1  1.1  4.4     a
2  bar_3  foo_2  2.2  5.5     b

Then aggregate by sum and reshape by unstack - get MultiIndex in columns:
df = df.groupby(['thing'] + key_columns)[output_columns].sum().unstack(key_columns)
print (df)
         o1          o2
bar   bar_1 bar_3 bar_1 bar_3
foo   foo_1 foo_2 foo_1 foo_2
thing
a       1.1   NaN   7.7   NaN
b       NaN   2.2   NaN   5.5

Create all possible combinations by MultiIndex.from_product for reindex, then reorder_levels and sort_index:
mux = pd.MultiIndex.from_product(df.columns.levels, names=df.columns.names)
print (mux)
MultiIndex(levels=[['o1', 'o2'], ['foo_1', 'foo_2'], ['bar_1', 'bar_3']],
           labels=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1],
                   [0, 1, 0, 1, 0, 1, 0, 1]],
           names=[None, 'foo', 'bar'])

df = df.reindex(columns=mux).reorder_levels(key_columns + [None], axis=1).sort_index(axis=1)

Last remove MultiIndex by map with join:
df.columns = df.columns.map('_'.join)
df = df.reset_index()
print (df)
  thing  foo_1_bar_1_o1  foo_1_bar_1_o2  foo_1_bar_3_o1  foo_1_bar_3_o2  \
0     a             1.1             7.7             NaN             NaN
1     b             NaN             NaN             NaN             NaN

   foo_2_bar_1_o1  foo_2_bar_1_o2  foo_2_bar_3_o1  foo_2_bar_3_o2
0             NaN             NaN             NaN             NaN
1             NaN             NaN             2.2             5.5

A: I think you'll still have to use itertools.product(), because Pandas isn't designed to think about data that don't exist.  But once you've got those extra combinations defined, you can use groupby() and unstack() to get the output you're looking for.
Using the key_value_pairs you defined:
for k,v in key_value_pairs:
    if not len(df.loc[df.foo.eq(k) & df.bar.eq(v)]):
        df = df.append({"foo":k, "bar":v, "o1":np.nan, "o2":np.nan, "thing":"a"}, ignore_index=True)
        df = df.append({"foo":k, "bar":v, "o1":np.nan, "o2":np.nan, "thing":"b"}, ignore_index=True)

df
   bar  foo   o1   o2 thing
0    1    1  0.0  3.3     a
1    1    1  1.1  4.4     a
2    3    2  2.2  5.5     b
3    3    1  NaN  NaN     a
4    3    1  NaN  NaN     b
5    1    2  NaN  NaN     a
6    1    2  NaN  NaN     b

Now groupby and unstack:
gb = df.groupby(["thing", "foo", "bar"]).sum().unstack(level=[1,2])
gb.columns = [f"foo_{b}_bar_{c}_{a}" for a,b,c in gb.columns]

Output:
       foo_1_bar_1_o1  foo_1_bar_3_o1  foo_2_bar_1_o1  foo_2_bar_3_o1  \
thing
a                 1.1             NaN             NaN             NaN
b                 NaN             NaN             NaN             2.2

       foo_1_bar_1_o2  foo_1_bar_3_o2  foo_2_bar_1_o2  foo_2_bar_3_o2
thing
a                 7.7             NaN             NaN             NaN
b                 NaN             NaN             NaN             5.5


text:
Q: Programmatically define WCF Endpoints with Behaviours Can anyone show me how to programmatically create WSHttpBindings with Endpoint behaviours?
This is what was generated from WCF Add Service references to 6 WebServices which I manually editted to add behaviours so that all the endpoints uses the same behaviour .

<system.serviceModel>
  <behaviors>
    <endpointBehaviors>
      <behavior name="epBehaviour">
        <clientCredentials>
          <clientCertificate findValue="This is my TEST Cert" storeLocation="LocalMachine" x509FindType="FindBySubjectName" storeName="My" />
        </clientCredentials>
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <bindings>
    <wsHttpBinding>
      <binding name="WSHttpBinding_IQuote" messageEncoding="Mtom">
        <security mode="TransportWithMessageCredential">
          <transport clientCredentialType="None" />
          <message clientCredentialType="Certificate" establishSecurityContext="false" />
        </security>
      </binding>
      <binding name="WSHttpBinding_ICommit" messageEncoding="Mtom">
        <security mode="TransportWithMessageCredential">
          <transport clientCredentialType="None" />
          <message clientCredentialType="Certificate" establishSecurityContext="false" />
        </security>
      </binding>
      <binding name="WSHttpBinding_IRetrieve" messageEncoding="Mtom">
        <security mode="TransportWithMessageCredential">
          <transport clientCredentialType="None" />
          <message clientCredentialType="Certificate" establishSecurityContext="false" />
        </security>
      </binding>
      <binding name="WSHttpBinding_IInfo" messageEncoding="Mtom">
        <security mode="TransportWithMessageCredential">
          <transport clientCredentialType="None" />
          <message clientCredentialType="Certificate" establishSecurityContext="false" />
        </security>
      </binding>
      <binding name="WSHttpBinding_IPurge" messageEncoding="Mtom">
        <security mode="TransportWithMessageCredential">
          <transport clientCredentialType="None" />
          <message clientCredentialType="Certificate" establishSecurityContext="false" />
        </security>
      </binding>
      <binding name="WSHttpBinding_ISearch" messageEncoding="Mtom">
        <security mode="TransportWithMessageCredential">
          <transport clientCredentialType="None" />
          <message clientCredentialType="Certificate" establishSecurityContext="false" />
        </security>
      </binding>
    </wsHttpBinding>
  </bindings>
  <client>
    <endpoint address="https://my.service.com/WCFServices/Info.svc" behaviorConfiguration="epBehaviour" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IInfo" contract="InfoWcfWS.IInfo" name="WSHttpBinding_IInfo" />
    <endpoint address="https://my.service.com/WCFServices/Quote.svc" behaviorConfiguration="epBehaviour" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IQuote" contract="QuoteWcfWS.IQuote" name="WSHttpBinding_IQuote" />
    <endpoint address="https://my.service.com/WCFServices/Commit.svc" behaviorConfiguration="epBehaviour" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ICommit" contract="CommitWcfWS.ICommit" name="WSHttpBinding_ICommit" />
    <endpoint address="https://my.service.com/WCFServices/Retrieve.svc" behaviorConfiguration="epBehaviour" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IRetrieve" contract="RetrieveWcfWS.IRetrieve" name="WSHttpBinding_IRetrieve" />
    <endpoint address="https://my.service.com/WCFServices/Purge.svc" behaviorConfiguration="epBehaviour" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IPurge" contract="PurgeWcfWS.IPurge" name="WSHttpBinding_IPurge" />
    <endpoint address="https://my.service.com/WCFServices/Search.svc" behaviorConfiguration="epBehaviour" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ISearch" contract="SearchWcfWS.ISearch" name="WSHttpBinding_ISearch" />
  </client>
</system.serviceModel>

Currently with the generated Proxy from the "Add Service"  and adding the behaviour "epBehaviour" which is referenced in the endpoints as a behaviourConfiguration, I can make calls to the endpoints.
Now, my next step is to define the behaviour part and the URL as configurations (May be in the  of the web.config) so that I can have different config for Staging and Production.
So my sample Staging config will have the URL defined as below

<appSettings>
  <add key="ServiceUrl.Tls12.Quote" value="https://my.service.com/WCFServices/Quote.svc" />
  <add key="ServiceUrl.Tls12.Commit" value="https://my.service.com/WCFServices/Commit.svc" />
  <add key="ServiceUrl.Tls12.Retrieve" value="https://my.service.com/WCFServices/Retrieve.svc" />
  <add key="ServiceUrl.Tls12.Info" value="https://my.service.com/WCFServices/Info.svc" />
  <add key="ServiceUrl.Tls12.Purge" value="https://my.service.com/WCFServices/Purge.svc" />
  <add key="ServiceUrl.Tls12.Search" value="https://my.service.com/WCFServices/Search.svc" />
</appSettings>

So if I'm consuming the "Info" WebService, my code should be something like
//Code is missing how to define all the specifics like behaviours.
WSHttpBinding binding = new WSHttpBinding();
                EndpointAddress endpoint = new EndpointAddress(new Uri(ConfigurationManager.AppSettings["ServiceUrl.Tls12.Info"]));
             InfoWcfWS.InfoClient proxyNew = new InfoWcfWS.InfoClient(binding, endpoint);

In Summary, given the generated config after an "Add Service", to generate my Proxy Classes, I would like to remove all the config generated by VS and define my own config which will hold the URL;  Everything else like endpoints URI, behaviours ..etc should be instantiated programmatically.
Thanks

A: You have to create instances of the behavior you need either from the System.ServiceModel.Description namespace or create them yourself and then add them to a ChannelFactory.
For your example you create a ChannelFactory for the interface you want and any binding you prefer. You then instantiate a ClientCredentials behavior, configure any of the settings you need on it and add it to the EndPointBehaviors of the ChannelFactory. Then you're ready to create a clientchannel that will give you an object that implements your service interface. You can use that similar as the generated client.
// binding
var binding = new WSHttpBinding();
// using System.ServiceModel
var channelFactory = new ChannelFactory<InfoWcfWS.IInfo>(binding);
// using System.ServiceModel.Description
var endpointClientbehavior = new ClientCredentials();
endpointClientbehavior.ClientCertificate
    .SetCertificate(
    "This is my TEST Cert",
    StoreLocation.LocalMachine,
    StoreName.My);
// add the behavior to the endpoint
channelFactory.Endpoint.EndpointBehaviors.Add(endpointClientbehavior);

// done configuring;
channelFactory.Open();
var endpoint = new EndpointAddress(
    new Uri(ConfigurationManager.AppSettings["ServiceUrl.Tls12.Info"]));
// create the clientChannel
var client = channelFactory.CreateChannel(endpoint);
client.Open();
// client implements the operations on InfoWcfWS.IInfo

A: In the end, I found a simpler way of achieving this - This is one of the method Info I'm accessing:
WSHttpBinding binding = new WSHttpBinding();
EndpointAddress endpoint = new EndpointAddress(new Uri("https://my.service.com/WCFServices/Info.svc"));

binding.Name = "WSHttpBinding_IInfo";
binding.MessageEncoding = WSMessageEncoding.Mtom;
binding.Security = new WSHttpSecurity();
binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
binding.Security.Transport = new HttpTransportSecurity();
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
binding.Security.Message = new NonDualMessageSecurityOverHttp();
binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
binding.Security.Message.EstablishSecurityContext = false;

InfoClient proxy = new InfoClient(binding, endpoint);

proxy.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My,                                              X509FindType.FindBySubjectName, "This is my TEST Cert");

object response = proxy.ServiceMethod();


text:
Q: EmberJS how to handle transitionTo I have the following code which calls an transitionToRoute('search') when a search-query is entered and the enter button is pressed or submit button is clicked.
However, my Router still won't show the searchQuery in the template where it says:

You searched for: "{{searchQuery}}"

and the URL looks like http://www.example.com/#/search/[object Object] when searching for something (which doesn't seem right to me).
(full code can be viewed over at: http://jsfiddle.net/Mn2yy/1/)
This is the relevant code:
Templates:

Application controller:
MyApp.ApplicationController = Ember.Controller.extend({
    // the initial value of the `search` property
    search: '',

    doSearch: function() {
        // the current value of the text field
        var query = this.get('search');
        this.transitionToRoute('search');
    }
});

and the Searchpage route:
MyApp.SearchRoute = Ember.Route.extend({
    setupController: function(controller) {
        controller.set('searchQuery', this.get('query'));
    },

    renderTemplate: function() {
        this.render('searchpage', { into: 'container' });
    }
});

A: First, you need to define the dynamic segment in the router for the search route:
MyApp.Router.map(function() {
    this.route("home", { path: "/" });
    this.route("search", { path: "/search/:query" })
});

Then you set the searchQuery property on the application in the doSearch action. You also pass the query variable to the transitionToRoute method, since it'll fill in the dynamic segment.
MyApp.ApplicationController = Ember.Controller.extend({
    // the initial value of the `search` property
    search: '',

    doSearch: function() {
        // the current value of the text field
        var query = this.get('search');
        this.set('searchQuery', query);
        this.transitionToRoute('search', query);
    }
});

Since you need to access this property from the App.SearchController instance, you need to wire the 2 controllers together by using the needs API:
MyApp.SearchController = Ember.Controller.extend({
    needs: ['application'],
    application: Ember.computed.alias('controllers.application')
});

Aliased the controllers.application property to just application, to avoid too much typing eg. in the template.
Then you bind to this property in the search template:

Last step: if you refresh the page at this point, searchQuery won't be automatically populated from the URL. Let's just fix that with the deserialize hook:
MyApp.SearchRoute = Ember.Route.extend({
    deserialize: function(params) {
        this.controllerFor('application').setProperties({
            searchQuery: params.query,
            search: params.query
        });
    },

    renderTemplate: function() {
        this.render('searchpage', { into: 'container' });
    }
});

This will get the params from the URL and set up the application controller with the value of the query key.
That's pretty much it, hope I didn't miss anything!


text:
Q: TextMesh Pro not compatible with LWRP So after switching to LWRP I'm having some issues with TextMeshPro. Any TextMeshPro object that's in world space get's all in one position when I use LWRP. HUD elements work just fine.
example:

the texts in center of screen each should be on the white space of airplanes...
It's seems to be a shader issue because if I switch the shader on my font mat to LWRP shaders they work as normal, except they look horrible.
when i try to upgrade the font material i get :

material was not upgraded. There's no upgrader to convert
  TextMeshPro/Mobile/Distance Field shader to selected pipeline

how can i fix this issue?


text:
Q: jquery slideToggle direction I am trying to slide jquery .slideToggle but i am not able to add direction left to right or right to left on click of a div (nav). Please help me out, below is my code.
    <!DOCTYPE html>

Nav

    This is the paragraph to end all paragraphs.  You

    should feel lucky to have seen such a paragraph in

    your life.  Congratulations!

I am new to jquery, help much appreciated.

A: The default behaviour of slideToggle in jquery is to "slide up" or "slide down". If you want your
 to "slide left" and "slide right", you could use the 'slide' effect available in jquery ui. The direction argument accepts 'up','down','left','right' as valid values. http://docs.jquery.com/UI/Effects/Slide

A: You need to add a parent to the text.

$('.nav').click(function() {
   $('.text p').css({
      'width': $('.text p').width(),
      'height': $('.text p').height()
   });
   $('.text').animate({
      'width': 'toggle'
   });
});
body {
   font-size: 10px;
   color: #333;
}

.nav {
   float: right;
   width: 50px;
   line-height: 38px;
   text-align: center;
   background: #ccc;
   border: 1px solid #333;
   cursor: pointer;
}

.text {
   overflow: hidden;
   float: right;
   margin: 0 5px;
   padding: 5px;
   background: #e4e4e4;
}

Nav

         This is the paragraph to end all paragraphs. You
         should feel lucky to have seen such a paragraph in
         your life. Congratulations!

You have a demo at: http://jsfiddle.net/o6rj51bm/

A: You could do this:
p { width:400px; position: absolute; background:#e4e4e4; margin:5px;padding:5px;}

(use position absolute instead of float right)
And this:
 $(document).ready(function() {
    var $elem = $("p");
    var docwidth =  $(document).width();
    var inileft = docwidth - $elem.outerWidth();
    $elem.css("left", inileft);  //Position element tho the right
    $("div").click(function () {  //This slides
      $elem.animate({
        left: (parseInt($elem.css("left"), 10) >= docwidth ?  inileft : docwidth)
      });
   });
 });

By using animate, you can do very custom animations.
Hope this helps. Cheers

A:


text:
Q: Gmail moves email to spam folder Recently decided to move away from google mail services and to establish private mail server. What I came up to was that email sent from one me@example.com to inbox@gmail.com and spam@gmail.com was put in Inbox and Spam folders accordingly.
Problem
Why is the mail distributed to different folders? Does the mail destination folder (*@gmail.com) depends on

*

*account settings - I was able to receive mail to Inbox from me@example.com when marked as non-spam in my gmail account ?

*service settings - some specific requisites for gmail, for example, headers like Received-SPF, DKIM-Signature ?

*global settings - superclass, other services (yahoo, hotmail, outlook), more/less headers ?

Message
Checked the pass'es in some header fields. That IMHO seems to be fine as well. The respective IP's are hidden.
Delivered-To: spam@gmail.com
Received: by [example.com] with SMTP id s194csp2015594wmd;
        Tue, 16 Jun 2015 03:43:40 -0700 (PDT)
X-Received: by 10.66.154.233 with SMTP id vr9mr57332135pab.124.1434451419946;
        Tue, 16 Jun 2015 03:43:39 -0700 (PDT)
Return-Path: <me@example.com>
Received: from mail.example.com (example.com. [[example.com]])
        by mx.google.com with ESMTP id hf2si854902pbb.140.2015.06.16.03.43.38
        for <spam@gmail.com>;
        Tue, 16 Jun 2015 03:43:39 -0700 (PDT)
Received-SPF: pass (google.com: domain of me@example.com designates [example.com] as permitted sender) client-ip=[example.com];
Authentication-Results: mx.google.com;
       spf=pass (google.com: domain of me@example.com designates [example.com] as permitted sender) smtp.mail=me@example.com;
       dkim=pass header.i=@mail.example.com;
       dmarc=pass (p=QUARANTINE dis=NONE) header.from=example.com
Received: from [spam@gmail.com] (unknown [[gmail.com]])
    by mail.example.com (Postfix) with ESMTPSA id 7D2CB12164B
    for <spam@gmail.com>; Tue, 16 Jun 2015 06:43:36 -0400 (EDT)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=mail.example.com;
    s=default; t=1434451416;
    bh=EmposAsl9Yoxe9cb6dijtNnJsjZ0DuYCuwTZhRF2GXU=;
    h=Date:From:To:Subject:From;
    b=cjR7tpLvJ1JFVPf/ddLM4rpooeo95kFlu3ybHSHW8IK6oOTA1QfKy/Q14U9CojrDL
     IDf9s2fqNIBBAhH81ivwdNQQFo64hw4/rstljealG1lNQRiIl0zUvD3bm8WbC1CfWb
     i3/d8CgiAYkixStNSYEYQhNaUEixWMmznk/bUJJg=
Message-ID: <557FFDD8.2070201@example.com>
Date: Tue, 16 Jun 2015 13:43:36 +0300
From: =?UTF-8?B?TcSBcnRpxYbFoSBFZ2zEq3Rpcw==?= <me@example.com>
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) Gecko/20100101 Thunderbird/31.7.0
MIME-Version: 1.0
To: spam@gmail.com
Subject: Some test subject
Content-Type: text/plain; charset=utf-8; format=flowed
Content-Transfer-Encoding: 7bit

This is some message, however the mail is put to Spam folder...

DNS
MX 50 mail.example.com.
TXT @ "v=spf1 a mx ip4:[example.com] -all"
TXT _dmarc "v=DMARC1; p=quarantine; rua=mailto:postmaster@example.com"
TXT default._domainkey.mail "v=DKIM1; k=rsa; p=[some_long_string]"

Outro
Was following an quite nice tutorial and related posts here and here. Also checked DNS setup with public tools - everything was fine.
Update
The same email sent to yahoo was put into Inbox folder...

A: The answer to the problem is this line:
TXT _dmarc "v=DMARC1; p=quarantine; rua=mailto:postmaster@example.com"
As stated here the policy can be one of

*

*none - the so-called monitor mode

*quarantine - to treat the message with suspicion according to the receiver capabilities

*reject - to reject the message outright


text:
Q: How can I build a link for a directory aside from one file? I run World of Warcraft on Windows 7 on one hard drive and Ubuntu on another. Until I can figure out how to get my wine version working at the same framerate as the Windows 7 version, I have to do large group content on my Windows installation.
I have two copies of the installation. As of now, I link the directories inside of the primary folder in the wine installation (i.e. the Interface folder is a symlink pointing to the Windows 7 installation folder). The reason I link the subdirectories instead of the main directory is because, 2 directories deep (/wow/WTF/config.wtf), there is a configuration file that I keep different for both installations. While this is pretty much okay, it means I will run into issues when I get either installation patched as the root installation folder has executable files.
Is there a way to build a symlink, but allow a file inside of the symlink to remain unlinked? Or, alternatively, is it safe to link *.exe files that I know will be altered / patched?

A: If you install the xutils-dev package, the lndir command will create a bunch of symbolic and hard links, for the files and directories, respectively. You can go inside the linked directories and remove any of the file links you don't want. However, removing some may break the game.
As for whether the .exe files are safe to link, I don't see a problem with it, unless you need to maintain different patch sets of the game for each version. If the only difference you need is the config file, everything else can be links on the Ubuntu partition, to the Windows partition install, with just the config file being a real file. If you need to run lndir again to update links for new files, the existing files won't get overwritten.


text:
Q: System.UnauthorizedAccessException was unhandled by user code in simple code I got this exception in very easy code and I have running with elevated privileges around it.
It in sharepoint 2010
private void ChangeVersioningOnDocumentLibrary(SPListItem item, SPItemEventProperties properties, SPSite site)
        {
            string sitename = item[MeetingsCommon.Constants.FIELDS_TEXT_TITLE_NAME].ToString();
            string prefix = item[MeetingsCommon.Constants.FIELDS_TEXT_TITLE_NAME].ToString().Substring(0, 2);
            bool isConfirmed = item.TaxonomyFieldValueIsGivenValue(properties.AfterProperties, MeetingsCommon.Constants.FIELDS_MEETINGSTATUS_NAME, MeetingsCommon.Constants.TERMVALUE_MEETINGSTATUS_CONFIRMED, 1033);
            bool isPublished = item.TaxonomyFieldValueIsGivenValue(properties.AfterProperties, MeetingsCommon.Constants.FIELDS_MEETINGSTATUS_NAME, MeetingsCommon.Constants.TERMVALUE_MEETINGSTATUS_PUBLISHED, 1033);

            if (isConfirmed)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPWeb web = site.OpenWeb(prefix + "/" + sitename))
                    {

                            if (web.Exists)
                            {
                                web.AllowUnsafeUpdates = true;
                                SPList agendaPoints = web.GetSafeListByName(MeetingsCommon.Constants.LISTS_AGENDAPOINTS_NAME);
                                agendaPoints.EnableModeration = true;
                                agendaPoints.DraftVersionVisibility = DraftVisibilityType.Author;
                                agendaPoints.Update();
                                web.AllowUnsafeUpdates = false;
                            }

                    }
                });
            }
            if (isPublished)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPWeb web = site.OpenWeb(prefix + "/" + sitename))
                    {
                        if (web.Exists)
                        {
                            web.AllowUnsafeUpdates = true;
                            SPList agendaPoints = web.GetSafeListByName(MeetingsCommon.Constants.LISTS_AGENDAPOINTS_NAME);
                            agendaPoints.EnableModeration = false;
                            agendaPoints.DraftVersionVisibility = DraftVisibilityType.Author;
                            agendaPoints.Update();
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
        }

A: the problem is that it was using an spsite object coming from outside the RunWithElevatedPriviliges, the spsite object has to be created again inside in order for this to work.


text:
Q: Why can't I use addition like this in foreach? Javascript's foreach equivalent:
for ( var i in products )
{
    document.write("Write" + i + 1 );
}

Output:
Write01

Edit:
I tried parsing i into an integer.
for ( var i in products )
{
    document.write("Write" + parseInt(i) + 1 );
}

A: Because i is a number, but gets cast to a string by the first +. Use this:
for ( var i in products ) {
  document.write(""); document.write("Write" + (i + 1) );
  // ------------------------------------------^
}

A: The issue here is operator precedence. As shown in that table, the + operator associates left-to-right.
So:
a + b + c

Is grouped as follows:
((a + b) + c)

So in your original code, the expression is grouped as follow:
("Write" + i) + 1

In other words, it's a string concatenation followed by another string concatenation. Since you intend to do the arithmetic addition (i + 1) first, you'd have to group them explicitly:
"Write" + (i + 1)


text:
Q: Not seeing any Fields for a Y-Axis aggregation in Kibana I have grok filter for apache logs as follows :
if [type] == "apachelogs" {
    grok {
      break_on_match => false
      match => { "message" => "\[%{HTTPDATE:apachetime}\]%{SPACE}%{NOTSPACE:verb}%{SPACE}/%{NOTSPACE:ApacheRequested}" }
match=> { "message" => "\*\*%{NUMBER:seconds}/%{NUMBER:microseconds}" }

       add_tag => "%{apachetime}"
       add_tag => "%{verb}"
       add_tag => "%{ApacheRequested}"
       add_tag => "%{seconds}"
       add_tag => "%{microseconds}"

I want to create a visualisation in kibana for search type="apachelogs". O am using filebeat.So my search query is
filebeat*type="apachelogs"

I want apachetime in X-axis and microseconds in Y-axis.But in Y
-axis, I am not getting any fields except default ones (sum,count,aggregation).
Please help.I dont know what I am doing wrong.


text:
Q: Java exception in Mathematica while trying to access MS Access I'm trying to make "Wolfram Mathematica" to manipulate a *.accdb file. I already established a connection (to a file with an empty "table1"):
Needs["DatabaseLink`"]
conn = OpenSQLConnection[]

Source: http://reference.wolfram.com/language/DatabaseLink/ref/SQLInsert.html
It works fine. If I make:
SQLSelect[conn, "table1"]

I get
 {}

Now I want to create a table with:
SQLCreateTable[conn,
  SQLTable["TEST"], {SQLColumn["COL1", "DataTypeName" -> "INTEGER"],
   SQLColumn["COL2", "DataTypeName" -> "DOUBLE"]}];

I get the exception:

Java::excptn: A Java exception occurred:
  java.lang.NullPointerException    at
  net.ucanaccess.jdbc.UcanaccessPreparedStatement.clearParameters(UcanaccessPreparedStatement.java:214)
    at
  com.wolfram.databaselink.SQLStatementProcessor.processSQLStatement(SQLStatementProcessor.java:311).

Sorry for bad english (but I tried).
Thank you guys!

A: I think you need to specify a database, e.g.
conn = OpenSQLConnection["demo"]

A: Sometimes if you "open the same connection" many times Mathematica doesn't understand what to do. Just
Quit

the Kernel and re-establish the connection. SQL will work properly.


text:
Q: Find whether an element occurs n/4 times in n element array I was asked this question. I tried to use the majority element method, but it didn't work for me. Please provide some hints.

A: *

*Find out the median in O(n) time.

*Partition the array based on that median using 3-way partition.

*if median itself is the required element then done
 else
 On both the partition (left and right to the median) apply the majority element algorithm. (In your case find the element which appears more than n/4 times in an array of n/2) . Both will run in O(n) time.

Total time would be 3*O(n)=O(n).
Hope this helps :)


text:
Q: Javascript if statement returning wrong value var checkHour = new Date();
checkHour.getHours();

If statement inside time() function seems to be returning Good Evening. At this present time it should be returning good morning. What am I doing wrong?
function time(){
    if((checkHour >= 0) && (checkHour <= 12)){
alert(" Good Morning");
    }else if((checkHour >= 12) && (checkHour <= 18)){
alert("Afternoon");
    }else{
      alert("Good Evening")
    }
}

time();

A: It looks like your checkHour variable is loaded with the date.  You never set it's value to the hours.
Perhaps you meant the second line to read: checkHour = checkHour.getHours();, so your corrected code would be:
var checkHour = new Date();
checkHour = checkHour.getHours();

function time(){
    if((checkHour >= 0) && (checkHour <= 12)){
    alert(" Good Morning");
    }else if((checkHour >= 12) && (checkHour <= 18)){
        alert("Afternoon");
    }else{
      alert("Good Evening")
    }
}

A: CheckHour is not assigned properly, it should be
var checkDate = new Date();
var checkHour = checkDate.getHours();


text:
Q: openssl library for Windows for Generating a Development Key Hash for Facebook login for Android app To ensure the authenticity of the interactions between my app and Facebook, I need to supply Facebook with the Android key hash for your development environment. I am trying to generate a Development Key Hash for my Android development environment. In the official Facebook documentation at https://developers.facebook.com/ for my account, I found the following information:

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\USERNAME\.android\debug.keystore" | "PATH_TO_OPENSSL_LIBRARY\bin\openssl" sha1 -binary | "PATH_TO_OPENSSL_LIBRARY\bin\openssl" base64

The problem for me is with "openssl-for-windows openssl library for Windows from the Google Code Archive" because that takes to a broken link:
https://code.google.com/archive/p/openssl-for-windows/downloads
Are there alternative sources or ways to install the "openssl library for Windows"? Thank you.
UPDATE 1:
I am using https://web.archive.org/web/20220623092750/https://code.google.com/archive/p/openssl-for-windows/downloads to access the broken link I mentioned.


text:
Q: How can I format a float with given precision and zero padding? I have looked at a couple of dozen similar questions - and I'm happy to just get a link to another answer - but I want to zero pad a floating point number in python 3.3
n = 2.02
print( "{?????}".format(n))
# desired output:
002.0200

The precision of the float is easy but I can't ALSO get the zero padding. What goes into the ????'s

A: You can do it using both old and new formatting method for strings::
In [9]: "%08.4f" %(2.02)
Out[9]: '002.0200'

In [10]: "{:08.4f}".format(2.02)
Out[10]: '002.0200'

A: You can use the format specifiers, like this
>>> "{:0>8.4f}".format(2.02)
'002.0200'
>>> print("{:0>8.4f}".format(2.02))
002.0200
>>>

Here, 8 represents the total width, .4 represents the precision. And 0> means that the string has to be right aligned and filled with 0 from the left.


text:
Q: async_connect blocks io_service::run_one() in boost::asio I'm trying to run following code:
some_sock.async_connect(...); // handle_connect() sets the 'condition' flag

boost::asio::deadline_timer t(ios, boost::posix_time::seconds(2));
while (t.expires_from_now() >= boost::posix_time::seconds(0))
{
  ios.run_one();
  if (condition) return;
}

Desirable behavior is return from run_one() after timer t is expired (after 2 seconds).
Actually, run_one() blocks until SYN-ACK or RST is received. If the server is not responding, run_one() will block for a much longer timeout than 2 seconds.
What should I do to wait specified amount of time for connect doing some work in background?
Thanks.

A: use io_service::run and deadline_timer::async_wait as described in the async tcp client example.

A: Call run_one() for connect() in another thread. On timeout call some_sock.cancel(). (Read its documentation first).