text:
Q: How to parse data from a no-name array json using jq in linux command? [
  {
    "id": 4738245,
    "project_id": 25486,
    "sha": "871c0484c3a7e72deea96fbcd48djdgh2",
    "ref": "",
    "status": "success",
    "created_at": "2022-01-06T04:44:40.372Z",
    "updated_at": "2022-01-06T04:50:36.663Z",
    "web_url": ""
  }
]

The above is the json response I get from an gitlab API. I am trying to use jq '.id' to parse the id from the json response.
The error I get is :jq: error (at <stdin>:0): Cannot index array with string "id"
I understand that it should be jq '.<arrayName> .id' to parse it. However, the response does not give any arrayName so I cannot use that method.

A: Evidently the element id is nested within an object such like the other ones by wrapper curly braces, then call that as
jq '.[].id'

in order to get the value 4738245


text:
Q: Combinations of integers in OpenCL I have a bunch of vectors (~500). I need to find triple products of all the combinations of the vectors in OpenCL. There are plenty of combination algorithms (r out of n things) in C++ but I am yet to find any implemented for GPU. I have seen quite a few parallel permutation algorithms in Cuda but I just want to know if there are any viable combination algorithms present?

A: I'll need to guess a bit here and there to answer your question.
I suppose you have an array V of n (~500) vectors. These vectors are all of same dimensionality m (probably m=3).
What you want is the component wise product of each 3 vectors vi, vj, vk where i,j,k in {0,..,n-1}.
Simple 3-dimensional example:
result[idx].x = V[i].x * V[j].x * V[k].x;
result[idx].y = V[i].y * V[j].y * V[k].y;
result[idx].z = V[i].z * V[j].z * V[k].z;

Now maybe your vectors are not 3-dimensional and maybe you don't want the component wise product but the sum of it (like in dot product), but I'm sure you're able to djust the code accordingly.
The real question here is how to compute all possible i,j,k and idx. Correct?
Now with CUDA you are in a very fortunate position. You can just launch n*n*n threads in a grid and therefore get i,j,k for free without having to think about ways to compute combinations or permutations at all. Just do the following:
dim3 grid, block;
block.x = n;
block.y = 1;
block z = 1;
grid.x = n;
grid.y = n;
grid.z = 1;

compute_product_kernel<<<grid, block>>>( V, result );

This way you'll launch n*n blocks of n threads. Computing i,j,k becomes trivial, computing idx is easy:
__device__ void compute_product_kernel( myVector* V, myVector* result)
{
    int i = blockIdx.x;
    int j = blockIdx.y;
    int k = threadIdx.x;
    int idx = i * gridDim.y * blockDim.x + j * blockDim.x + k;
    ...
}

Of course all of this only works because your n is within the limits of CUDA's block and grid range.
Two more things though:

*

*Maybe you want permutations instead of combinations. You could do that by skipping every combination where any two of i,j,k are the same. But I'd recommend keeping them anyway because computing when to skip is probably more expensive that doing the actual work. Also I'd advise against using the permutation to save memory for result because it would save you less that 1% and make the calculation much more complex.

*Are you sure you've got enough memory to actually do this? Storing the result requires n*n*n*m*sizeof(float) bytes. With n=500 and m=3 that would already be 1.5 GB. Is that really what you are looking for? Maybe the next step of your processing can be combined into the calculation so that storing the intermediate result is not neccessary.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I change the color of each of p in a div if a condition is met? How can I change the background color of a particular

' + SeatsLeft + ' seats left

when its employee.managerId is greater than 19.
The data loads from my database. This is what I've tried and it doesn't work

$.each(employees, function(index, employee) {
  var SeatsLeft = 20 - employee.managerId;
  $('#employeeList').append('
' +
    '' +
    '
' + employee.firstName + '
' +
    '
' + difference + '
' +
    '
' + SeatsLeft + ' seats left
' +
    '<button id="bookSea" class="bubble" data-difference="' + hoursMin + '" data-route="' + employee.firstName + '" data-busnum="' + employee.lastName + '" onclick="bookSeat(this);">' + '' + '</button>' +
    '<button data-diff="' + hoursMin + '" data-name="' + employee.firstName + '" class="bubble" style="margin-right:30px" onclick="setReminder(this);">' + '' + '</button>
');

  var x = document.getElementsByClassName("line3");
  var i;
  for (i = 0; i < x.length; i++) {
    if (employee.managerId > 19) {
      x[i].style.color = "red";
    }
  }

});

A: $.each(employees, function(index, employee) {
  var SeatsLeft = 20 - employee.managerId;
  var color = employee.managerId > 19 ? 'red' : 'green';

  $('#employeeList').append('
' +
    '' +
    '
' + employee.firstName + '
' +
    '
' + difference + '
' +
    '
' + SeatsLeft + ' seats left
' +
    '<button id="bookSea" class="bubble" data-difference="' + hoursMin + '" data-route="' + employee.firstName + '" data-busnum="' + employee.lastName + '" onclick="bookSeat(this);">' + '' + '</button>' +
    '<button data-diff="' + hoursMin + '" data-name="' + employee.firstName + '" class="bubble" style="margin-right:30px" onclick="setReminder(this);">' + '' + '</button>
');

});

A: Perhaps you meant
if (SeatsLeft === 0) $(".line3").css("color","red");

or
'
'
+ SeatsLeft + ' seat'+(SeatsLeft===1?"":"s")+' left
'


text:
Q: Linux create columns from row I have a text file with values, and I'm trying to create and fill a column from a specific row in the file. To be more precise, the input is the following:
<name>RELATIVE 1</name>
0.624790,-0.000000,0
0.493925,0.591035,0
0.363039,1.182079,0
<name>RELATIVE 2</name>
-24.621334,0.000000,0
-24.752199,0.591031,0
-24.883085,1.182072,0
<name>RELATIVE 3</name>
-49.868542,0.000000,0
-49.999397,0.591014,0
-50.130271,1.182033,0

and the expected output should be:
0.624790,-0.000000,0 <name>RELATIVE 1</name>
0.493925,0.591035,0 <name>RELATIVE 1</name>
0.363039,1.182079,0 <name>RELATIVE 1</name>
-24.621334,0.000000,0 <name>RELATIVE 2</name>
-24.752199,0.591031,0 <name>RELATIVE 2</name>
-24.883085,1.182072,0 <name>RELATIVE 2</name>
-49.868542,0.000000,0 <name>RELATIVE 3</name>
-49.999397,0.591014,0 <name>RELATIVE 3</name>
-50.130271,1.182033,0 <name>RELATIVE 3</name>

the solution could be in Bash, Awk or Sed.
Thanks in advance for the help.

A: Using awk:
awk '/^</{s=$0;next}{print $0,s}' file.txt

When a line begins with <, set the variable s to the contents of the line and skip to the next line. On other lines, print the contents of the line, followed by the contents of s.

A: you can try awk
awk '/name/{s=$0}!/name/{print $0,s}' file

A: sed '#n
 /<name>/ {h
   b
   }
 G
 s/\n/ /p' YourFile

add the latest name line to the current line using the holding buffer


text:
Q: How to prove a probability limit Suppose two people are playing a game with an infinitely generous agent who gives 1 coin at random between the two players.
The agent gives 1 coin to each player at the start. And then the agent proceeds to give coins randomly to each player with a probability proportional to how many coins they have already received.
So, for example: Players A and B start with 1 coin each. The agent assigns a coin to A and B with probability 1/2. Say the coin is given to B. Now B=2, A=1. Now the agent then gives the coin to B with probability 2/3, and A 1/3. And we start this infinite process.
My question is: Is one player 'expected' to run away from the other as the number of iterations approaches infinity? Or are they expected to switch places an infinite amount of times?
I'm 95% sure that they eventually run away from each other, since the expected value of the ratio B/A is still B/A after one iteration. But I'm looking for direction to prove this in a more rigorous way. Not really too sure where to start.

A: Let $C_t=|A_t-B_t|$, and see that $\mathbb{E}[C_{t+1}^2|\mathcal{F}_t]=\left(C_t+1\right)^2\frac{t+1+C_t}{2(t+1)}+\left(C_t-1\right)^2\frac{t+1-C_t}{2(t+1)}$. To see that the probabilities are correct, assume $A_t\leq B_t$, so that $B_t-A_t=C_t$, $A_t+B_t=t+1$, so that $B_t=\frac{C_t+t+1}{2}$. This simplifies to $\mathbb{E}[C_{t+1}^2|\mathcal{F}_t]=C_t^2\frac{t+3}{t+1}+1$. We can then prove by induction that $\mathbb{E}[C_t^2]=\sum_{i=3}^{t+1}\frac{(t+2)(t+1)}{(i+1)(i)}=\frac{(t+1)(t+2)}{3}-(t+1)$. Notice that this implies that $\mathbb{E}\left[\frac{C_t}{t+1}\right]\leq\frac{1}{\sqrt{3}}$. You can similarly show that $\mathbb{E}[C_{t+1}]=\frac{t+2}{t+1}\mathbb{E}[C_t]+\mathbb{P}[C_t=0]$, and therefore that $\mathbb{E}\left[\frac{C_t}{t+1}\right]\geq \mathbb{E}[\frac{C_2}{3}]=\frac{1}{3}$. Therefore the absolute difference in proportions can be seen to grow linearly in $t$, with linear constant varying between $\frac{1}{3}$ and $\frac{1}{\sqrt{3}}$. So although $A_t$ and $B_t$ diverge, one doesn't quite dominate in the long term.


text:
Q: OS X: Apply inheritable ACL permissions to pre-existing subfolders and files I have a folder with numerous ACL permissions set. Most of these include file_inherit and directory_inherit permissions and therefore should be, and are, automatically propagated to any new sub-folders and files I create within that folder.
However, there are some sub-folders and files that were already in the folder with the ACL permissions before the ACL permissions were set. Because of this, they don't have the inheritable permissions.
How can I make all the pre-existing sub-folders and files inherit the inheritable ACL permissions, as if they were newly created?


text:
Q: Adding "Accessed" and "Available from" for agsm bibliography style (Harvard Format) I'm writing a final year dissertation, and our university (University of Westminster, UK) requires us to use Harvard referencing format. I have followed this tutorial to include Harvard formatting into my Overleaf document.
As per the guidelines (5.4.1 in the document) provided by the university, when accessing online journals/research papers, it is required to have the Available from... and Accessed... information (See the image below).

I've tried doing what's stated in this thread for the following entry, and have gotten the output below.
Input:
@article{banbury2021micronets,
    title        = {Micronets: Neural network architectures for deploying tinyml applications on commodity microcontrollers},
    author       = {Banbury, Colby and Zhou, Chuteng and Fedorov, Igor and Matas, Ramon and Thakker, Urmish and Gope, Dibakar and Janapa Reddi, Vijay and Mattina, Matthew and Whatmough, Paul},
    year         = 2021,
    journal      = {Proceedings of Machine Learning and Systems},
    volume       = 3,
    url          = {https://proceedings.mlsys.org/paper/2021/file/a3c65c2974270fd093ee8a9bf8ae7d0b-Paper.pdf},
    note = "[Accessed 29th September, 2021]"
}
}

Output:

I would like to have it display as shown in the University Referencing guidelines in the link mentioned and shown above. How may I achieve it?


text:
Q: How would you remove a created node from one div and display it to another div using Vanilla JS? I created function add_item that listens for a click event. each time the button is clicked the function will create a div element and append a new div to the output div( parent node ) and when I click on one of the created divs that particular child will be removed using the delete_item function but what I really want to know now is how to take the removed item and add it into another div like onclick of a created node remove that precise one from output 1 and now display it to output 2 using Vanilla Js only not jQuery.

var add_item_button = document.getElementById(`add_item_button`);
var output = document.getElementById(`output`);

add_item_button.addEventListener(`click`, add_item);

function add_item() {
  let create_div = document.createElement(`div`);
  create_div.setAttribute(`class`, `added_div`);
  output.appendChild(create_div);

  create_div.addEventListener(`click`, delete_item);
  function delete_item(){
  output.removeChild(create_div);
  }
}
.added_div {
  background-color: #000;
  margin:5px;
  height: 50px;
  width:50px;
  display:inline-block;
}
<button id="add_item_button">add item</button>

A: You can do it with output2.appendChild(create_div);
Demo:

var add_item_button = document.getElementById(`add_item_button`);
var output = document.getElementById(`output`);
var output2 = document.getElementById(`output2`);

add_item_button.addEventListener(`click`, add_item);

function add_item() {
  let create_div = document.createElement(`div`);
  create_div.setAttribute(`class`, `added_div`);
  output.appendChild(create_div);

  create_div.addEventListener(`click`, delete_item);
  function delete_item(){
    output2.appendChild(create_div); // <-----------------------------
  }
}
.added_div {
  background-color: #000;
  margin:5px;
  height: 50px;
  width:50px;
  display:inline-block;
}
<button id="add_item_button">add item</button>

A: You just need to append the element to a new parent. Element references are exactly that, so unless you make a clone of the element, the element itself is moved.

var add_item_button = document.getElementById(`add_item_button`);
var output = document.getElementById(`output`);
var moved = document.getElementById('moved');

add_item_button.addEventListener(`click`, add_item);

function add_item() {
  let create_div = document.createElement(`div`);
  create_div.setAttribute(`class`, `added_div`);
  output.appendChild(create_div);

  create_div.addEventListener(`click`, delete_item);
  function delete_item(){
    //Just change the div. It's one object/element that is moved
    moved.appendChild(this);
  }
}
.added_div {
  background-color: #000;
  margin:5px;
  height: 50px;
  width:50px;
  display:inline-block;
}
<button id="add_item_button">add item</button>

Moved

Let's now take advantage of event bubbling so you don't have to bind an event listener every time you add an element.

var add_item_button = document.getElementById(`add_item_button`);
var output = document.getElementById(`output`);
var moved = document.getElementById('moved');

add_item_button.addEventListener(`click`, add_item);

function add_item() {
  let create_div = document.createElement(`div`);
  create_div.setAttribute(`class`, `added_div`);
  output.appendChild(create_div);

}

//Event listener on output element
output.addEventListener("click", function(event){
  //Check it is the added div that is clicked using CSS selector
  if(event.target.matches(".added_div")) {
    //Move the element
    moved.appendChild(event.target);
  }
});
.added_div {
  background-color: #000;
  margin:5px;
  height: 50px;
  width:50px;
  display:inline-block;
}
<button id="add_item_button">add item</button>

Moved


text:
Q: cakephp certificate printing Image to PDF writer and replace contents My client have pre-printed certificates. Now, we want a dynamic run time certificate printing options as per matches schedules into the Match arranged.
One option I have seen at .Net guys help, they have generated PDF of scanned Certificate Image with PDF Writer and created textbox like to replace Name, txtName, then Date as txtDate etc for replacing dynamic values run time.
However with PHP/CakePHP, Any idea, how can we achieve the same logic with our requirement.

A: You should install tcpdf, and explore more.
Create a template of pdf and all dynamic values replace with your cake values.
See image as background on tcpdf example. http://www.tcpdf.org/examples.php [51]


text:
Q: how to find the count of cell value and no of last continuous by pandas

Data frame 1 have 3 week code, and data frame 2 have 4th week means last week code, now how to find the two columns , first is total no of cell count and no of last continuous cell

A: It's easier to get more information about the week codes by turning them into columns with truth values.
>>> df1
  week1 week2 week3
0    bk    mm    xz
1    ck    ij    bk
2    ka    xz    zz
3    xz    dk    bv
4    ij    mn    ka
5    ik    ik    xy
6    bv    ka    xx
7    xy    xx    ck
8    mn    ck    ik

>>> df2
  week4
0    ka
1    bk
2    ck
3    xy
4    xz
5    zz
6    ik
7    xx
8    bv

Start by joining your two DataFrames to bring all the weeks data together.
df = df1.join(df2)

Now gather all unique week codes and generate a list of codes for each week. We can then combine these in a new DataFrame.
codes = np.unique(df)
weeks = df.T.apply(list, axis=1)

d = {c: [(c in w) for w in weeks] for c in codes}
newDf = pd.DataFrame(data=d, index=weeks.index)

>>> newDf
          bk     bv    ck     dk     ij    ik    ka     mm     mn     xx     xy    xz     zz
week1   True   True  True  False   True  True  True  False   True  False   True  True  False
week2  False  False  True   True   True  True  True   True   True   True  False  True  False
week3   True   True  True  False  False  True  True  False  False   True   True  True   True
week4   True   True  True  False  False  True  True  False  False   True   True  True   True

Now we can get total cell count easily and number of continuous cells using a neat 'cumsum' trick.
totals = newDf.sum()
continues = (newDf.cumsum() -
             newDf.cumsum().where(~newDf).ffill().fillna(0)).iloc[-1]

Finally you can fill in your total columns in DataFrame #2, using the above as lookup tables.
df2['Total Number of cell'] = df2['week4'].apply(lambda code: totals[code])
df2['No. of time last continuous'] = df2['week4'].apply(
    lambda code: continues[code]).astype(int)

results in
>>> df2
  week4  Total Number of cell  No. of time last continuous
0    ka                     4                            4
1    bk                     3                            2
2    ck                     4                            4
3    xy                     3                            2
4    xz                     4                            4
5    zz                     2                            2
6    ik                     4                            4
7    xx                     3                            3
8    bv                     3                            2


text:
Q: What's the difference between "til 9.00" and "before 9.00"? I was sent a text "I will be home til 9.00" and I understood it to mean before 9.00 but I can't explain how to use til, until, by or before. I thought til was used with negative words (I won't be home til 9.00) but that's not always true (eg I'll be at work til 9.00).

A: "I will be home til 9.00" means "I will be at home until 9.00", at which point they presumably are leaving.
"til" is a contraction of "until" and therefore should have an apostrophe like
I will be home 'til 9.00"
("I won't be home 'til 9:00" means "I will be out, ie not at home, until 9:00".)
"by" on the other hand, has almost the opposite meaning to "until" in this context:  if someone says "I'll be home by 9.00" they mean that "At some point before 9:00 I will arrive home": so it's like saying "I will be home from 9:00 onwards".
"I will be home before 9:00" could actually mean either of the above things:  it could mean "I will be home during the period which is before 9:00" or it could mean "I will arrive home before 9:00".
I think the second usage is more common, but there's no way to definitively say which is which: it's an example of where you need to use the context to make a judgement about what someone means.


text:
Q: How to loop through Firebase data How to loop through Firebase data (childs) which are actually objects and access to their properties in Swift 4?
As a beginner with Swift, I am trying to loop through data I am retrieving from Firebase, and I am trying to access to properties of those objects. Seems much more complicated then it should be in swift (just my subjective opinion)
As per documentation on the Firebase site this is what I have
_commentsRef.observe(.value) { snapshot in
    for child in snapshot.children {
        // Access to childs here ...
    }
}

Now, combining this above and as per tutorials and explanations (btw was not able to find neither one which explains this fully) which I found on net, this is what I have:
ref.child("activities").child("list").observeSingleEvent(of: .value, with: { (snapshot) in
    // The list i got here is the list of the childs which are objects
    // Lets loop through that list and pull properties we need
    for child in snapshot.children.allObjects as! [DataSnapshot] {
        print(child.value)
    }
})

The print in the loop will properly display object with all of its properties, but I am not able to access to these properties. Accessing to it with something like "child.value.title" is resulting with error "Value of type 'Any' has no member 'title'"
Do I need to convert child.value to something else, maybe to cast it or to convert it somehow to property accessible JSON or something like that?

A: If you call value on a snapshot that contains multiple properties, what you get back is a NSDictionary with the property names as the keys. So to get the value of the title key you'd do:
for child in snapshot.children.allObjects as! [DataSnapshot] {
    print(child.value)
    let dict = child.value as? [String : AnyObject] ?? [:]
    print(dict["title"])
}

Alternatively you can use the other members of DataSnapshot to navigate to the title property and then call .value on that:
for child in snapshot.children.allObjects as! [DataSnapshot] {
    print(child.value)
    print(child.childSnapshot(forPath: "title").value)
}

See DataSnapshot.value and the first sample in the Firebase documentation on reading data.


text:
Q: Trouble understanding the supersymmetric localization argument A standard technique in supersymmetric quantum field theory is localization. Due to supersymmetry, one can show that only a small subset of the space of all field configurations contributes to the path integrals which define correlation functions, thus simplifying their calculation enormously. There are two standard arguments that supersymmetric path integrals localize.
The first localization argument is basically a sort of fixed point theorem, see for example Section $5$ of This paper by Witten. This argument makes it quite clear that the subset of fields on which these integrals localize is the set of fixed points of the supercharge $Q$, i.e. those for which the SUSY variation of all fields vanish. From here, it is clear to me that the integrals should localize to configurations for which the fermions and their $Q$-variations all vanish.
The second argument is more direct, and lends itself better to calculation. For a theory with a $Q$-invariant action $S$, one can show that the following path integral is independent of the parameter $t$
$$
Z_{t}
=
\int[\mathcal{D}X]e^{-S[X]-tQV[X]}
$$
for any "not too extreme", functional $V$.
It is then clear that (given good enough convergence properties), we can compute the original integral by taking $t\to\infty$. In this limit, the only field configurations which provide a non-zero contribution to the integral will be those for which $Q\cdot V=0$. To proceed with actual calculations, one must make a choice of $V$, the canonical choice (see for example here, here, here, here or here), is:
$$
V
=
\sum_{\psi\in\{\text{fermions}\}}
\left(
(Q\psi)^{\dagger}\psi
+
\psi^{\dagger}(Q\psi^{\dagger})^{\dagger}
\right)
$$
This is where I have a little bit of a problem. All of the sources which I linked state that with this choice of $V$, the integral localizes to field configurations for which
$$
Q\psi=Q\psi^{\dagger}=\psi=\psi^{\dagger}=0
$$
although I don't understand quite why this is.
Clearly $QV$ includes the terms:
$$
\sum_{\psi\in\{\text{fermions}\}}\left(|Q\psi|^{2}+|Q\psi^{\dagger}|^{2}\right)
$$
and the sources seem to say that this is the "bosonic piece", and thus $Q\psi=Q\psi^{\dagger}=0$, but since $V$ is entirely fermionic, isn't $QV$ entirely bosonic? And furthermore, I see no reason that this implies that the fermions themselves vanish!
Obviously the two arguments have to lead to the same result, and I would really appreciate it if anybody could help me see how this happens.


text:
Q: Build Definition cURL Protocol "D" not supported or disabled in libcurl Currently, I'm using cURL to FTP file from VS Team Services to Azure AppService.
But the log returned the following message: Protocol "D" not supported or disabled in libcurl
Am I missing any cURL parameter to FTP?
Note: I'm able to execute cURL from my local machine and file is able to upload.

A: I can reproduce this issue with hosted build agent if uploading multiple files through cURL, but it works fine to upload a single file. (Both cURL Upload file step/task and call cURL command via Command Line step/task have the same issue)
I submit a feedback here: vsts cURL Protocol "D" not supported or disabled in libcurl
The workaround is that you can queue build with on premise build agent.

*

*Add curl to environment variable of your build agent machine (path environment variable)

*Restart build agent

*Queue build with this build agent.


text:
Q: C++: How to compute an integral with interval bounds? I am both tired, new to C++ and real bad at dealing with polynomials. That's a bad combo for my assignment. Nevertheless I am trying to solve it. Please note that I might have misunderstood certain parts both mathematically and language-wise. Maybe even terminology.
The first task of my assignment was to create a class for storing polynomials. I figured the important parts were coefficiants and the degree of the polynomial. As such I have a polynomial class that (partly) looks like this:
class Polynomial {

private:
    double* Coefficients;  //Array of coefficients in order of ascending power
    int Degree; //The degree of the polynomial

...

The class should have a method for finding the integral of the polynomial within a lower and upper bound. But I really do not know how to work with it.
Since it's bad practise not to show what I've done, this is what I currently have, and it probably does not make a lot of sense, but please, if you can, point me in the right direction?
Polynomial Polynomial::ComputeIntegral(double lower, double upper) {
    //Values needed to create new polynomial
    //degree will be one more than the original polynomial
    int degree = Degree + 1;
    double* coefficients = new double[degree + 1];

    coefficients[0] = 0;

    for (int i = 0; i < degree +1; i++) {
        coefficients[i + 1] = Coefficients[i] / (double)(i + 1);
    }

    Polynomial integral(degree, coefficients);
    return integral;
}

That I can see myself, it is messed up because a) I do not use the bounds, and b) I am pretty sure per the assignment description I should end up with a value rather than a new polynomial.
Google tells me there are algorithms to deal with finding integrals (Trapezoid for example), but I can not wrap my head around matching that with my representation of a polynomial.

A: A few pointers:

*

*Use std::vectors instead of pointers and new. (If you are new to C++, there are very few circumstances when you actually need to use new.)

*ComputeIntegral(double, double) will need to return a double, since it is obviously computing a definite integral. (The function you have at the moment would be something like GetPrimitive(), as it returns the primitive of the polynomial, which is another poly.

*The definite integral is the difference of the primitive evaluated at the bounds (First Fundamental theorem of calculus).

*There are a number of ways you could represent the polynomial as a data structure, but I would suggest a single std::vector<double> coeffs that represents all of the coefficients up to the degree of the poly, then the degree can be calculated at coeffs.size(). In some cases there may be zeroes in that coeffs though.

A: In the general case, it is possible to use the boost library to compute integrals: https://www.boost.org/doc/libs/1_77_0/libs/math/doc/html/quadrature.html
There is also the library ALGLIB that I have used to compute integrals. Here is an example to compute integrals with ALGLIB: Integrate a public but non static member function with ALGLIB


text:
Q: eclipse link without any class or mapping file as you can see in this tutorial http://www.vogella.com/tutorials/JavaPersistenceAPI/article.html when you declare an entity like Person then you must add it in persistence.xml  likes <class>de.vogella.jpa.eclipselink.model.Person</class> or you can define a mapping file and put your classes in there, but when you use hibernate as you can see here http://www.alexecollins.com/tutorial-hibernate-jpa-part-1/ after entity declaration you don't need to add anything in persistence.xml as class. or maybe I misundrestood.
I want eclipe link does the same way that hibernate does, means I should use eclipse link and I don,t want to declare class or use any mapping file, does it possible or it doesn't?
thanks

A: You wanted to ignore <class> annotation from persistence.xml & you wanted your eclipse to auto detect annotated class files right? Then try the following,
Right click on the project, click Properties, select JPA, in the Persistence class management select Discover annotated classes automatically.

Referred link: Do I need <class> elements in persistence.xml?


text:
Q: vba excel copy only visible cells on key press ctrl+c for protected sheet I'm trying to replace ctrl+c so it will copy only visible cells on a protected sheet. Trying to solve this problem I stumbled on this post (vba excel copy only visible cells on key press ctrl+c)
The following code (suggested by Siddharth-Rout) works but only for a non-protected sheet:
Private Sub Workbook_Open()
     Application.OnKey "^c", "Copy"
End Sub

Sub Copy()
    Dim rng As Range

    On Error GoTo Whoa

    If Not Selection Is Nothing Then
        Set rng = Selection.Cells.SpecialCells(xlCellTypeVisible)
        rng.Copy
    End If

LetsContinue:
    Exit Sub
Whoa:
    MsgBox Err.Description, vbCritical, "Error Number : " & Err.Number
    Resume LetsContinue
End Sub

I tried unprotecting, copying, and then reprotecting but it removes the copy. I need the final sheet to be protected. Any help would be appreciated.

A: Ah! A blast from the past :P
You need to unprotect and protect just before you copy. Also I am using ActiveSheet for demonstration purpose. Change that to the relevant sheet if required.
Is this what you are trying?
Sub Copy()
    Dim rng As Range
    Dim MyPassword As String

    '~~> Change password as applicable
    MyPassword = "Sid"

    On Error GoTo Whoa

    If Not Selection Is Nothing Then
        ActiveSheet.Unprotect MyPassword
        Set rng = Selection.Cells.SpecialCells(xlCellTypeVisible)
        ActiveSheet.Protect MyPassword

        rng.Copy
    End If

LetsContinue:
    Exit Sub
Whoa:
    MsgBox Err.Description, vbCritical, "Error Number : " & Err.Number
    Resume LetsContinue
End Sub


text:
Q: Using JQuery with dynamically added controls (MVC) I have a set of radio buttons that are dynamically generated (via JSON call):
StringBuilder sbEligAll = new StringBuilder();

sbEligAll.Append("
");
sbEligAll.Append("  <input type='radio' name='selectalldepartment' id='radCurrent' value='0' />Current");
sbEligAll.Append("  <input type='radio' name='selectalldepartment' id='radFuture' value='1' />Future");
sbEligAll.Append("  <input type='radio' name='selectalldepartment' id='radCurrentAll' value='2' />Current All");
sbEligAll.Append("  <input type='radio' name='selectalldepartment' id='radFutureAll' value='3' />Future All");
sbEligAll.Append("
");

Then:
return Json(new { TableList = sbElig.ToString() }, JsonRequestBehavior.AllowGet);

Is there a way to get jQuery to be able to interact with these?
For example:
$("input[name=selectalldepartment]").change(function() {
     var str = $('input[name=selectalldepartment]:checked').val();
     $(".radiolist[value='" + str + "']").attr("checked", true);
});

I've tried everything I know how to do, but the jQuery just doesnt fire. (I've added alerts to the jQuery code to see if it actually gets called, and it does not).
Any thoughts?!
Thanks!

A: Use .live() like this:
$("input[name=selectalldepartment]").live('change', function() {
     var str = $('input[name=selectalldepartment]:checked').val();
     $(".radiolist[value='" + str + "']").attr("checked", true);
});

When you run your current code it looks for that selector, and attaches an event handler to those elements...the new elements weren't there to attach to when it was run.  The other option is when you're adding the controls, add the handler there to the new ones matching the same selector in the response, something like this:
$.ajax({
    url: blah.aspx...
    success: function(data) {
      //do stuff
      $("input[name=selectalldepartment]", data).change(function() {
        //Code or a function to keep it tidy
      });
    }
});


text:
Q: How to change the content of a JavaScript function dynamically? The problem I have is that I am trying to change the image from a canvas tag when the client selects a different radio button.
The content of the canvas is stored in the database with the code of the draw which I got from Illustrator (a lot of code).
What I did first was to change the data from a script tag by id where I created the function that paints the canvas.
It worked well, it painted the draw correctly. The problem is that when I select another radio button, even when the content of the script changes and so does the function, it draws the same painting and not the updated one.
I think that this happens because JavaScript does not update the content of the function after this has been already called once. Am I wrong?
If it is the problem I have, is it possible to change the content of the function after it has been called?
This is the html code:
<canvas id="myCanvasDel" height="600" width="600" style="max-width:600px;"></canvas>
<script id="scriptjs"></script>

This is the JavaScript one when I click on the radio button:
function mostrarCanvas(codiprd, codicol) {
    $.ajax({
        dataType: "html",
        type: "POST",
        url: "ajaxcanvas.php",
        data: {
            codiprd: codiprd,
            codicol: codicol
        },
        success: function (datos) {

            $('#scriptjs').html(datos);

            var canvasDel = document.getElementById("myCanvasDel");
            var ctxDel = canvasDel.getContext("2d");
            drawDel(ctxDel);
        },
        error: function (e) {
            alert('Ha habido un error: ' + e);
        }
    });
    return false;
}

And this is the PHP that the ajax file calls:
$codiprd=$_POST['codiprd'];
$codicol=$_POST['codicol'];
$querycnv = "SELECT CANVAS "
        . "FROM MYTABLE PC "
        . "WHERE PC.CODIPRD=$codiprd AND PC.CODICOL=$codicol "
        . "GROUP BY PC.CODIPRD,PC.CODICOL;";

$resultcnv = mysqli_query($conn, $querycnv)or die(mysqli_error());
$canvas = mysqli_fetch_array($resultcnv);

echo $canvas['CANVAS']);

A: You can redefine the function as you can redefine any varible.
function foo(){
    console.log("blah");
}

can be redefined with
foo = function(){
    console.log("blah,blah");
}

A function is just another object, and thus can be used like any referenced variable.
You can create a function from a string
var funcStr = 'return "hi there!";';  // the function body
var func = new Function(funcStr);  // create the function
console.log(func()); // >> hi there

You set arguments with
var funcStr = 'return "hi there " + name;';  // the function body with arg name
var func = new Function("name",funcStr);  // create the function with the argument name
console.log(func("Me")); // >> hi there Me

You can also create a script tag and add it to the DOM
    var scriptSource = "//Source code;\nconsole.log("Script run");"
    var script = document.createElement("script");
    script.async = true;
    script.text = scriptSource;
    document.body.appendChild(script);
    // in time the console will read
    // >> Script run

You need to wait for the script to be parsed which will not happen until you exit the current execution. After the script has loaded, it is first parsed and then run. If you wish you can just have the function body in the script tag and let it run by itself.


text:
Q: "Collection was modified error", but only on Key press and not Button click with same method call It seems like the "Collection was modified; enumeration operation may not execute" error has popped up a lot here, but none of them seem to solve the issue I'm having. The odd problem I'm having is that the exception only presents itself when I press a Key which is bound to a command, and not when I click a button tied to the same command.
XAML:
<Window.InputBindings>
    <KeyBinding Key="F4" Command="{Binding UpdateItemsA}"/>
    <KeyBinding Key="F5" Command="{Binding UpdateItemsB}"/>
</Window.InputBindings>
<DockPanel>
    <Button Content="Update A" Command="{Binding UpdateItemsA}" />
    <Button Content="Update B" Command="{Binding UpdateItemsB}" />
    <ListBox ItemsSource="{Binding ItemsList}"
             IsSynchronizedWithCurrentItem="True">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="3" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ListBoxItem}" >
                            <Grid Background="{TemplateBinding Background}">
                                <Border BorderThickness="5" BorderBrush="{TemplateBinding BorderBrush}">
                                    <ContentPresenter />
                                </Border>
                            </Grid>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsSelected" Value="True">
                                    <Setter Property="BorderBrush" Value="Yellow" />
                                    <Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}" />
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>
</DockPanel>

And here's the code-behind of an ItemStuff class:
bool canExecute;
ICommand updateItemsA, updateItemsB;
List<string> _itemsList;
List<string> ItemsA;
List<string> ItemsB;

public ItemStuff()
{
    canExecute = true;
    ItemsA = new List<string> { "item A", "item B", "item C" };
    ItemsB = new List<string> { "item D", "item E", "item F" };
    ItemsList = ItemsA;
}

public ICommand UpdateItemsA
{
    get
    {
        return updateItemsA
                ?? (updateItemsA = new CommandHandler(() => UpdateMainItemsA(), canExecute));
    }
}

public ICommand UpdateItemsB
{
    get
    {
        return updateItemsB
                ?? (updateItemsB = new CommandHandler(() => UpdateMainItemsB(), canExecute));
    }
}

void UpdateMainItemsA()
{
    ItemsList = ItemsA;
}

void UpdateMainItemsB()
{
    ItemsList = ItemsB;
}

public List<string> ItemsList
{
    get
    {
        return _itemsList;
    }
    set
    {
        _itemsList = value;
        OnPropertyChanged("ItemsList");
    }
}

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;

    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class CommandHandler : ICommand
{
    private Action _action;
    private bool _canExecute;

    public CommandHandler(Action action, bool canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _action();
    }
}

I've identified the following three areas in the XAML where if I remove them, the exception doesn't occur.
<ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="3" />
            </ItemsPanelTemplate>
</ListBox.ItemsPanel>

<ListBox IsSynchronizedWithCurrentItem="True" />

<Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}" />

So I think the problem might have something to do with the listbox having keyboard focus and then pressing a key to switch items, because like I mentioned when you click the button to switch items there is no problem. Keyboard focus is a requirement for the app which the user should be able to navigate without ever using the mouse.

A: There is a part in your code which we can't see here obviously and you are doing some work with that "ImageDatabase[CurrentSelection].ImagePaths" while the code is in foreach loop.. you can use .ToList() in foreach line OR you can copy your ImagePaths to a temporary variable and start your foreach loop with that temp variable.. But these are not the correct things you should do, find where do you modify this list while the program is in foreach loop


text:
Q: Catch: what symbol can I use to personalize code for unit-testing I am using the Catch C++ test framework. I have a separate test-code file, where I have
#define CATCH_CONFIG_MAIN
#include "catch.hpp"

#include "my_own_headers.h"

TEST_CASE( "test of thisnthat", "[thisnthat]" )
{
   SomeStuff a(42);
 ...

Is there some symbol that Catch defines at build time that I can use it to change my code definition?
An example:
Say I have some struct that needs to having some special constructor but only for testing purposes, for some specific test case. I want to be able to use this constructor when I build my test code, but the regular build should not enable this function.
// someheader.h
struct SomeStuff
{
   int someValue;
 #if BUILD_IS_TEST_MODE
   SomeStuff( int a ), someValue(a) {}
 #endif
};

What symbol can I use ?
I had a look on https://github.com/philsquared/Catch/blob/master/docs/configuration.md but couldn't find anything relevant.


text:
Q: Make android layout child wider than parent? My code is:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="30dp"
    android:layout_marginRight="30dp">

    <View
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_gravity="center"
        android:background="#00ff00"/>
</android.support.v7.widget.CardView>

My output is

I want to green view to match the whole screen parent width.
Is this possible?
I want to use the card view as a parent, because it will have elevation.

A: Here's your solution...
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <CardView
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        />
    <View
        android:id="@+id/fab"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_centerVertical="true"
        android:background="#00ff00"
        />
</RelativeLayout>


text:
Q: Updating product name/description (that has group prices) via model causes Integrity constraint violation (in catalog_product_entity_group_price) I have this simple code, which tries to update the product's name & description like this:
$productID = Mage::getModel('catalog/product')
    ->getIdBySku($product->Sku);

if ($productID)
{
    $p = Mage::getModel('catalog/product');
    $p->load($productID);
    $p->setName($product->Name);
    $p->setDescription($product->Description);
    $p->save();
    $p = null;
}

This causes the following error to occur:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
  '3596-0-1-0' for key 'CC12C83765B562314470A24F2BDD0F36', query was:
  INSERT INTO catalog_product_entity_group_price (entity_id,
  all_groups, customer_group_id, value, website_id) VALUES (?,
  ?, ?, ?, ?)

I've noticed this error only occurs IF the product has group_price set on it (even though I am not updating this).
Any ideas? I am on magento 1.9.x

A: Okay, I have solved it like this: hope this helps someone else with similar issue...
// Update Existing Product
$productAction = Mage::getSingleton('catalog/product_action')
    ->getResource();
$productAction->updateAttributes(array($productID), array(
    'name' => $product->Name,
    'description' => $product->Description
), 0); // 0 = store id (default scope)
$productAction = null;


text:
Q: Write handler methods for dynamically generated buttons and text boxes I have this small data on JSP form. I use JSTL to iterate over data. In each row, I have two dynamically generated textboxes and a button. Question is: how do I write a generic handler method for this data, which handles dynamically generated textboxes and buttons. Here is my JSP
<c:forEach items="${menus}" var="menu" >

    ${menu.getMenuId()}
    <input type="text" name="menu_name" value="${menu.getMenuName()}"/>
    <input type="text" name="menu_price" value="${menu.getMenuPrice()}"/>
    <c:out value="${menu.getIsAvailable()}" />
    <input type="submit" value="Add Item ${menu.getMenuId()}">

</c:forEach>

Add Product

 Name: <input type="text" name="chosen_menu_name" />
 Price: <input type="text" name="chosen_menu_price" />
 <input type="submit" value="Add to cart">

And here is my controller (though I dont know what to put it there - at the moment I am using two seperate textbox and a button for taking the input)
@RequestMapping(method = RequestMethod.POST)
public ModelAndView AddMenu(@RequestParam("chosen_menu_name") String mymenu, @RequestParam("chosen_menu_price") String menu_price, @ModelAttribute("cart") ArrayList<Menu> mycart, Model model)
{
    Menu menu = new Menu();
    menu.setMenuId(0);
    menu.setMenuName(mymenu);
    menu.setMenuPrice(Double.parseDouble(menu_price));

    model.addAttribute("menus", GetMenus());
    mycart.add(menu);

    return new ModelAndView("edit_menu");
    //return "show_menu";
}

As one can see from the JSP, I am using two seperate textboxes and a button for taking input and passing it to the controller. How do I write a generic handler method for this data, which handles dynamically generated textboxes and buttons?

A: I'm assuming that you don't want those other two field and button. You want to add items directly from table.
You have to make each and every row as one form like below :
<c:forEach items="${menus}" var="menu" >

<form method="POST" action="controllerName">

        ${menu.getMenuId()}
        <input type="hidden" name="menu_id" value="${menu.getMenuId()}"/>

        <input type="text" name="menu_name" value="${menu.getMenuName()}"/>

        <input type="text" name="menu_price" value="${menu.getMenuPrice()}"/>

        <c:out value="${menu.getIsAvailable()}"/>

        <input type="submit" value="Add Item">

</form>

</c:forEach>

And controller like below:
@RequestMapping(method = RequestMethod.POST)
public ModelAndView AddMenu(@RequestParam("menu_id") String menuId, @RequestParam("menu_name") String mymenu, @RequestParam("menu_price") String menu_price, @ModelAttribute("cart") ArrayList<Menu> mycart, Model model)
{
    Menu menu = new Menu();
    menu.setMenuId(menuId);
    menu.setMenuName(mymenu);
    menu.setMenuPrice(Double.parseDouble(menu_price));

    model.addAttribute("menus", GetMenus());
    mycart.add(menu);

    return new ModelAndView("edit_menu");
    //return "show_menu";
}


text:
Q: Writing a program to determine a palindrome. I have to use toUppercase and toLowercase to make it case insensitive I feel like I'm only missing a few steps. I'm not looking for someone to finish it.. just need help in the right direction.
The problem with it is it still says that for example, "Noon" isn't a palindrome.
I'm not sure how to convert it any further.
Scanner input = new Scanner(System.in);

    System.out.println("Please enter a string of 8 or less characters: ");
    String s = input.nextLine();

    int low = 0;

    int high = s.length() - 1 ;

    boolean isPalindrome = true;

    while(low < high){
        if(s.charAt(low) !=s.charAt(high))
        {
            isPalindrome = false;
            break;
        }
    low++;
    high--;
}

    String upper = s.toUpperCase();
    String lower = s.toLowerCase();

    if(high>8)
    {
        System.out.println("Too Long!");
    }
    else if(isPalindrome)
    {
        System.out.println(s + " is a Palindrome");
    }
    else if((isPalindrome)&&s.toUpperCase().equals(s.toUpperCase()))
    {
        System.out.println(s + " is a Palindrome");
    }
    else
        System.out.println(s + " is not a Palindrome");

A: change the logic to check the characters like below n try.
it will make it case insensitive.
 while(low < high){
            if(s.toUpperCase().charAt(low) != s.toUpperCase().charAt(high))
            {
                isPalindrome = false;
                break;
            }
        low++;
        high--;
    }

A: package javaprograme;

import java.util.Scanner;

public class PalindromStringExample {
    public static boolean palidrom(String name)
    {
        char[] ch = name.toCharArray();
        for(int i=0,j=ch.length-1; i<(ch.length/2); i++,j--)
        {
            if(ch[i]!=ch[j])
            {
                return false;
            }
        }
        return true;

    }

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        String s = input.nextLine();
        if(s.length()>8)
        {
            System.out.println("Too Long!");
        }
        else
        {
            boolean value =palidrom(s);
            s.toUpperCase();
            if(!value)
            {
                System.out.println("Given String is not a palindrom");
            }
            else
            {
                System.out.println("Given String is a palindrom");
            }
        }
    }
}


text:
Q: How to Show message when anonymosuser post something in Django I used this method to show message when user send post request.
this method works until the user is authorized ... but if anonymous user send post request , something is wrong here....
cause the request is not valid anymore... belong error occurs for me on this line
messages.error(request, "Error. Message not sent.")

The view shop.views.add_to_cart didn't return an HttpResponse object. It returned None instead.
Then I tried to pass a HttpRequest... not working again
How can I show message when anonymosuser post something in Django ?


text:
Q: Find an Exact Tuple Match in a List of Tuples and Return Its Index I am trying to figure out how to determine if a tuple has an exact match in a list of tuples, and if so, return the index of the matching tuple. For instance if I have:
TupList = [('ABC D','235'),('EFG H','462')]

I would like to be able to take any tuple ('XXXX','YYYY') and see if it has an exact match in TupList and if so, what its index is. So for example, if the tuple ('XXXX','YYYY') = (u'EFG H',u'462') exactly, then the code will return 1.
I also don't want to allow tuples like ('EFG', '462') (basically any substring of either tuple element) to match.

A: I think you can do it by this
TupList = [('ABC D','235'),('EFG H','462')]
if ('ABC D','235') in TupList:
   print TupList.index(i)

A: Use list.index:
>>> TupList = [('ABC D','235'),('EFG H','462')]
>>> TupList.index((u'EFG H',u'462'))
1


text:
Q: How to prevent an imported module from 'importing' sys.argv[1:] I am a python newbie.  To pose my question in a comprehensible manner, I created two scripts.  One script is named: called_script.py   The other script is named: calling_script.py
The following two lines are the code in called_script.py
 import sys
 print str(sys.argv[1]) + '\n\n' + str(dir(sys.argv[1]))

The following two lines are the code in calling_script.py
 import sys
 import called_script

If I feed 'foo' as a command line argument to 'calling_script.py', foo will appear as sys.argv[1] in 'called_script.py'
Is there any code that I could add to 'called_script.py' so that 'called_script.py' could ascertain
whether sys.argv[1] was passed to it from the command line, or whether sys.argv[1] was passed to it from 'main'?
Also, I am curious to know whether it is possible to prevent e.g., sys.argv[1] from being passed from main to an imported module, and where I could find some reading on this topic.
Thank you for any help.  It is much appreciated.
                      Marc

A:
Is there any code that I could add to 'called_script.py' so that
  'called_script.py' could ascertain whether sys.argv[1] was passed to
  it from the command line, or whether sys.argv[1] was passed to it from
  'main'?

Fundamentally, no, because command line arguments aren't passed to modules, they're passed to Python, which puts them in sys.argv.  Since all the modules are sharing the same sys, they'll all see the same sys.argv, and that's that.
That said, you can take advantage of __name__, which is set to __main__ only for the main script:
~/coding$ python calling_script.py fred
called_script says __name__ is: called_script
calling_script says __name__ is: __main__

So you could use something like
args = sys.argv if __name__ == '__main__' else [whatever_you_want]

and then use args to get the equivalent of a module-specific sys.argv.  Similarly, you could branch on __name__ at the very start of calling_script.py, stash sys.argv, and then modify the one in sys (ick).
But generally speaking, you shouldn't need to use sys.argv anywhere outside your main program anyway.  If you need access to sys.argv in multiple places your interface probably isn't separated enough from your routines.


text:
Q: ssh -o options hang client on windows 10 clients connecting to linux servers This hangs on a windows 10 client, but I really do need to use windows 10 client lately:
ssh -4 -X -i my.pem ga@192.168.1.111 -o ConnectTimeout=604800

Contrastingly, this worked good on a linux ubuntu client in the past:
ssh -X -o ConnectTimeout=604800 -i "my.pem" ga@192.168.1.111

The microsoft docs link to the OpenBSD docs. However the problem seems to be windows 10 specific. I really need to stay connected a long time.
There was no effect by moving parameters around, nor by the -4 presence or absence, nor by removing the = character.
This interestingly worked good on a windows 10 client, but is missing the option that I require:
ssh -4 -X -i my.pem ga@192.168.1.111
Welcome to Ubuntu 16.04.5 LTS (GNU/Linux 4.4.0-142-generic x86_64)

The big question is, what is the right format for the family of command line options "-o" here on windows 10 clients?  And why isn't it identical to linux clients?
I understand there might be a file to contain these options (-o options are a long list of possible strings).  However the OpenBSD docs do not and would not be able to describe where to put this file on windows 10. The file name and directory on windows 10 to use would be a mystery to me for now.  I imagine the bsd docs might explain the format of this file though.
UPDATE:
I tried making a config file with the setting in it, same format as command line, and then launched it 4 different ways and still hang:
ssh -F .config -4 -X -i my.pem ga@192.168.1.111 -o ConnectTimeout=604800
ssh -F ".config" -4 -X -i my.pem ga@192.168.1.111 -o "ConnectTimeout=604800"
ssh -F .config -4 -X -i my.pem ga@192.168.1.111
ssh -F ".config" -4 -X -i my.pem ga@192.168.1.111

Docs:
https://man.openbsd.org/ssh
https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_overview
More:
Another ssh command I will be needing (below) also hangs.  I need to do port forwarding, so I can run a browser process in my client computer, but use the server's web server to host my jupyter notebooks for machine learning projects.  It's a different ssh command but it has the same hanging problem.  Maybe the ssh isn't really supported on windows 10, and if that's true, I going to abandon windows 10 and go back to building myself a linux workstation for a client, because I know it works right.  This makes me mad, as it's such a time waster.
ssh -i my.pem -N -f -L localhost:8889:localhost:8889 ga@192.168.1.111

UPDATE:  With -vvv parameter it shows to be hanging where port 22 is not sending something back to the client:
ssh -4 -X -i my.pem ga@192.168.1.111 -o ConnectTimeout=604800 -vvv
OpenSSH_for_Windows_7.7p1, LibreSSL 2.6.5

debug3: Failed to open file:C:/Users/mrcod/.ssh/config error:2

debug3: Failed to open file:C:/ProgramData/ssh/ssh_config error:2

debug2: resolve_canonicalize: hostname 192.168.1.111 is address

debug2: ssh_connect_direct: needpriv 0

debug1: Connecting to 192.168.1.111 [192.168.1.111] port 22.

debug2: fd 3 setting O_NONBLOCK

Has anyone been able to connect to a unix server from windows 10 yet via ssh? They must have. This isn't an unusual task in 2019, with AWS being the innovating flagship of cloud systems, and web sites using linux servers in the majority globally.  I'm not sure why nobody appears to know anything. My english here isn't weak either.
I'm not seeing any real help from the LAST items coming out of the debug output.
For lack of any other ideas submitted here, a next step seems to be to experiment smore more with putting another config file in additional places (directories) that the debug output is saying it was looking for it and see if any settings look possible for fixing the hanging on port 22 problem here. I don't think there is much to go on here really, so I'm pessimistic unless someone chimes in that actually uses ssh on windows 10, since openbsd is what this software was compiled from on windows 10 according to microsoft links I've provided.

A: Windows OpenSSH is very new (beta) and only enabled by default on Windows 10 after April 2018 Update. (https://www.howtogeek.com/336775/how-to-enable-and-use-windows-10s-built-in-ssh-commands/). It has known issues such as only supporting ed25519 key.
I would use SuperPuTTY  and PuTTY, which is the defacto SSH client for Windows for years (IMO). But, from reading this GitHub thread (https://github.com/PowerShell/Win32-OpenSSH/issues/973), it seems the GitHub version of Windows 10 OpenSSH has improvements/feature fixes that might not be available via default installation. Try using the GitHub version! --> https://github.com/PowerShell/openssh-portable/releases
https://www.liquidweb.com/kb/using-ssh-client-windows-10/
https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html
https://github.com/jimradford/superputty/releases/tag/1.4.0.9


text:
Q: Shiny IO Account Info SLL Error I am trying to publish an app on Shiny. I have been able to do this on my home computer but not my work computer for some reason.
install.packages('shiny')
install.packages('devtools')
install.packages('httr')
install.packages('rsconnect')
library(shiny)
library(devtools)
library(httr)
library(rsconnect)

httr::set_config(config(ssl_verifypeer = 0L))
devtools::install_github('rstudio/shinyapps')
rsconnect::setAccountInfo(name='name', token='token', secret='secret')

ui = fluidPage(
   sliderInput(inputId = "num",
          label = "Choose a number",
          value = 25, min = 1, max = 100),
   plotOutput("hist")
)

server = function(input, output){
   output$hist = renderPlot({
      hist(rnorm(input$num))
   })
}

shinyApp(ui = ui, server = server)

Error in function (type, msg, asError = TRUE)  :
SSL certificate problem: self signed certificate in certificate chain
Timing stopped at: 0.04 0 1.81

I have looked at https://curl.haxx.se/libcurl/c/CURLOPT_CAINFO.html but this is a over my head from a technical perspective.


text:
Q: Javascript character conversion The javascript function charCodeAt() will convert a character to the UNICODE numeric.
If, instead, I want to find the windows-1252 numeric code of a character, how can I do that?
Thanks,

A: Are you looking for Windows1251 to Unicode:
var winEncToUni = [
    0, 1, 2, 3, 4, 5, 6, 7,
    8, 9, 10, 11, 12, 13, 14, 15,
    16, 17, 18, 19, 20, 21, 22, 23,
    24, 25, 26, 27, 28, 29, 30, 31,
    32, 33, 34, 35, 36, 37, 38, 39,
    40, 41, 42, 43, 44, 45, 46, 47,
    48, 49, 50, 51, 52, 53, 54, 55,
    56, 57, 58, 59, 60, 61, 62, 63,
    64, 65, 66, 67, 68, 69, 70, 71,
    72, 73, 74, 75, 76, 77, 78, 79,
    80, 81, 82, 83, 84, 85, 86, 87,
    88, 89, 90, 91, 92, 93, 94, 95,
    96, 97, 98, 99, 100, 101, 102, 103,
    104, 105, 106, 107, 108, 109, 110, 111,
    112, 113, 114, 115, 116, 117, 118, 119,
    120, 121, 122, 123, 124, 125, 126, 127,
    8364, 129, 8218, 402, 8222, 8230, 8224, 8225,
    710, 8240, 352, 8249, 338, 141, 381, 143,
    144, 8216, 8217, 8220, 8221, 8226, 8211, 8212,
    732, 8482, 353, 8250, 339, 157, 382, 376,
    160, 161, 162, 163, 164, 165, 166, 167,
    168, 169, 170, 171, 172, 173, 174, 175,
    176, 177, 178, 179, 180, 181, 182, 183,
    184, 185, 186, 187, 188, 189, 190, 191,
    192, 193, 194, 195, 196, 197, 198, 199,
    200, 201, 202, 203, 204, 205, 206, 207,
    208, 209, 210, 211, 212, 213, 214, 215,
    216, 217, 218, 219, 220, 221, 222, 223,
    224, 225, 226, 227, 228, 229, 230, 231,
    232, 233, 234, 235, 236, 237, 238, 239,
    240, 241, 242, 243, 244, 245, 246, 247,
    248, 249, 250, 251, 252, 253, 254, 255
];

use for example as String.fromCharCode(winEncToUni[65]) (returns A)
or perhaps Unicode to Windows1251?
function toWindows1252(string, replacement)
{
    var ret = new Array(string.length);
    var i, ch;

    replacement = typeof replacement === "string" && replacement.length > 0 ? replacement.charCodeAt(0) : 0;

    for (i = 0; i < string.length; i++)
    {
        ch = string.charCodeAt(i);

        if (ch <= 0x7F || (ch >= 0xA0 && ch <= 0xFF))
        {
            ret[i] = ch;
        }
        else
        {
            ret[i] = toWindows1252.table[string[i]];

            if (typeof ret[i] === "undefined")
            {
                ret[i] = replacement;
            }
        }
    }

    return ret;
}

toWindows1252.table = {
    '\x81': 129, '\x8d': 141, '\x8f': 143, '\x90': 144,
    '\x9d': 157, '\u0152': 140, '\u0153': 156, '\u0160': 138,
    '\u0161': 154, '\u0178': 159, '\u017d': 142, '\u017e': 158,
    '\u0192': 131, '\u02c6': 136, '\u02dc': 152, '\u2013': 150,
    '\u2014': 151, '\u2018': 145, '\u2019': 146, '\u201a': 130,
    '\u201c': 147, '\u201d': 148, '\u201e': 132, '\u2020': 134,
    '\u2021': 135, '\u2022': 149, '\u2026': 133, '\u2030': 137,
    '\u2039': 139, '\u203a': 155, '\u20ac': 128, '\u2122': 153
};

document.write(toWindows1252('Hello World àèéìòù'));

I have shortened the table quite much: the first half of the codes (0x00-0x7F) are equal in all the codepages (and in Unicode), and the sequence 0xA0-0xFF are equal in Unicode and Windows-1252.


text:
Q: ATG & Flex via AMF? How easy might it be to build a front end with flex, and have ATG as the backend and do all communication / integration via AMF, using BlazeDS or Live Cycle Data Services?
Thanks!

A: It is very simple in the coming ATG version 10. There were several demos of Flash based and Swing based clients done by ATG using the not-yet-released ATG 10.
If you are working on some home-grown solution, with arrival of v 10 it my become obsolete.
See also https://community.atg.com/docs/DOC-1638 - Flex based catalog browsing demo.


text:
Q: How to apply a SAN SSL Certificate to multiple subdomains on a single IP (Same Server) in Apache Web Server on Windows I have a SAN SSL Certificate which covers about 4 subdomains. Os is windows.
abc.mydomain.com
xyz.mydomain.com
pqr.mydomain.com
jkl.mydomain.com

The common name for the certificate is abc.mydomain.com
How can I apply this certificate in Apache so that it could provide SSL security to all the four domains. I mean how should I configure Apache in this case.


text:
Q: If two VMs are on the same ESXi server, and they access each others files, is the file access optimized some how? If you have two physical machines on a physical network, in order to share files, they have to traverse the network, and network equipment to get to each other.  Even if you have two VMs on two separate ESXi's I would imagine they'd have to do this.
Now if you have two VMs on the same ESXi that access each others files, since they're both basically just software running on the same server, I would think there would be room here for a different algorithm underlying the abstraction in which they could access each others' files faster using what appears to the VMs themselves to be the same protocol of SMB.
Does VMWare do this?  Because it appears to me that files are transferred faster between two VMs on the same ESXi than in the other two cases.

A: Network traffic between virtual machines on the same host and connected to the same virtual switch port group doesn't traverse the physical network, so yes it should be faster in that scenario.


text:
Q: Ggplot2: Label X-Axis To be What I Want Insted of What It Is I want the x-axis to be labeled with elements of the lb column from the dataframe df1.
df1 <- read.table(text =
                    "method1  9 0.2402482
                     method2  9 0.1023012
                     method3  8 0.2031448
                     method4 4 0.2654746
                     method5 9 0.4048711")

colnames(df1) <- c("Methods", "lb", "RMSE")

df1 |>
  dplyr::mutate(colour = forcats::fct_reorder(Methods, RMSE)) |>
  ggplot2::ggplot(ggplot2::aes(Methods, RMSE, colour = colour)) +
  ggplot2::geom_point(size = 4) +
  ggplot2::geom_segment(aes(Methods, xend = Methods, yend = RMSE, y = 0)) +
  ggplot2::scale_color_manual(values = c("green", "yellowgreen", "yellow", "orange", "red")) +
  ggplot2::theme_bw() + labs(color = "Method")

Here is what I have is
What I actually want looks like

A: You can use the labels param of the scale_x_discrete() function, like this:
df1 |>
  dplyr::mutate(colour = forcats::fct_reorder(Methods, RMSE)) |>
  ggplot2::ggplot(ggplot2::aes(Methods, RMSE, colour = colour)) +
  ggplot2::geom_point(size = 4) +
  ggplot2::geom_segment(aes(Methods, xend = Methods, yend = RMSE, y = 0)) +
  ggplot2::scale_color_manual(values = c("green", "yellowgreen", "yellow", "orange", "red")) +
  ggplot2::theme_bw() + labs(color = "Method") +
  ggplot2::scale_x_discrete(labels = function(x) df1[df1$Methods==x, "lb"])


text:
Q: How do I generate a 403 error when someone tries to access a particular page I may be barking up completely the wrong tree here but what I would like to do is protect my .js pages by having them return a 403 Forbidden http error status page if someone tries to access them directly via http. I use them to support my index.html page but would like for them to remain hidden.
The helpdesk guys at my ISP basically say they don't know if it's possible but it may be something you could do with a web.config file (which is not something I have used before).
Any help at all would be gratefully received - I am a bit out of my comfort zone with this one

A:
I would like to […] protect my .js pages by having them return a 403 Forbidden http error status page if someone tries to access them directly via http.

Please note that if you include some resource, for example a script via the <script>-tag in HTML or an image via the <img>-tag, the browser does nothing else than simply run another HTTP request to get that resource. The whole communication already happens over HTTP.
While a browser may include additional details in its HTTP request when requesting additional resources, like the Referer-header, it definitely is not required to do so. So if you look out for the Referer-header, be advised that you may lock out other valid clients which do not send the Referer-header in their requests.
Also note that this will not give you any protection whatsoever. One can simply construct HTTP headers when requesting things, so "faking" requests your server would allow (because it thinks they are correct) is not a problem at all. And even without that; every resource you tell the client to use to make your website work will be downloaded by the client. And after that, the client can do whatever he wants with it. It can cache them on the hard disk, or allow the user to quickly look at it without having to run another request.
So if you want to do this for protecting your code, then just forget about it, and make it easier for everyone by just not adding a non-optimal protection. Code you put on the web can be made difficult to read, but if you want the user to see the end result, then you also give out your code in the same step.

A: In php you can do this with:
header("HTTP/1.0 403 Forbidden");


text:
Q: CSS-only formatting of variable-sized cropped field I have a text string and a numeric ID that I want to display next to each other:
This is a String [123]
Seems simple enough, but I can't control the length of the string or the size of the container that I'm placing this in.  The first challenge is getting these to line up next to each other and I used a trick I found on SO:

This is a long string that should be cropped.

[123]

Applying this CSS, I get the two strings next to each other:
* { font-size: 12px; }  /* Just for testing. */

.label, .id {
    display: table-cell;
}

Now I can display This is a long string that should be cropped. [123]
The problem is if the outermost DIV is a fixed width that is too small (which it often is):

This is a long string that should be cropped.

[123]

The output will look now like this:
This is a long string  [123]
that should be
cropped.

And what I want is This is a long string   [123]
I have tried everything I could think of, setting the heights of the DIVs to 12px (so it matches the font height) and setting overflow to hidden, using a full-fledged table, I even considered using Flash.  I've tried a ton of options - so far I've been at this for three or four hours.
I've been getting so many helpful answers by googling and finding helpful posts on SO, I decided to join and try asking my own question.
A few things to note (not sure if these hurt or help the situation):

*

*I can't control the value of the ID, it might be [1] or [9999999] - I don't want to hard-code the width of that (or the "display_field" or the "label" for that matter.  Even percentages will cause issues.

*This environment might not have JavaScript enabled (I wish, I'd use a jQuery plugin!)

*The container might be any type of tag, but will usually be a DIV.  I don't really have control of the markup outside of my "display"field".

*I control the markup of the "display_field" and can use SPAN tags or any other HTML that gets the job done.

*I'm only writing this for FireFox (3 is required) and Chrome, other compatibility with crappy browsers isn't necessary (yes, I'm looking at you IE).

*The "id" field will always be a number in square brackets, so there's no white space to worry about.

*There's no need to put ellipsis in where the cropped text ends.  It's a nice feature, but I don't see any way to get it working on FireFox (there's a hack for 3.x, but nothing for version 4).

A: How about the following? It is mostly based on the extracts you provided.
.cropped_field
{
    height:1.4em;
    overflow:hidden;
}

Take a look at the demo fiddle.


text:
Q: How to create new table with nested schema entirely in BigQuery I've got a nested table A in BigQuery with a schema as follows:
    {
    "name": "page_event",
    "mode": "repeated",
    "type": "RECORD",
    "fields": [
        {
            "name": "id",
            "type": "STRING"
        }
    ]
    }

I would like to enrich table A with data from other table and save result as a new nested table. Let's say I would like to add "description" field to table A (creating table B), so my schema will be as follows:
    {
    "name": "page_event",
    "mode": "repeated",
    "type": "RECORD",
    "fields": [
        {
            "name": "id",
            "type": "STRING"
        },
        {
            "name": "description",
            "type": "STRING"
        }
    ]
    }

How do I do this in BigQuery? It seems, that there are no functions for creating nested structures in BigQuery SQL (except NEST functions, which produces a list - but this function doesn't seem to work, failing with Unexpected error)
The only way of doing this I can think of, is to:

*

*use string concatenation functions to produce table B with single field called "json" with content being enriched data from A, converted to json string

*export B to GCS as set of files F

*load F as table C

Is there an easier way to do it?

A: To enrich schema of existing table one can use tables patch API
https://cloud.google.com/bigquery/docs/reference/v2/tables/patch
Request will look like below
PATCH https://www.googleapis.com/bigquery/v2/projects/{project_id}/datasets/{dataset_id}/tables/{table_id}?key={YOUR_API_KEY}

{
 "schema": {
  "fields": [
   {
    "name": "page_event",
    "mode": "repeated",
    "type": "RECORD",
    "fields": [
     {
      "name": "id",
      "type": "STRING"
     },
     {
      "name": "description",
      "type": "STRING"
     }
    ]
   }
  ]
 }
}

Before Patch

After Patch


text:
Q: How to use auth middlware in livewire I trying to use middleware but it seems not to work.I Want to prevent direct access of components via url. am using the auth
    Route::get('/', \App\Http\Livewire\Login::class)->name('login');
Route::get('/login', \App\Http\Livewire\Login::class)->name('login');
Route::get('analytics',\App\Http\Livewire\Analytics::class)->name('analytics')->middleware('auth');
Route::get('members',\App\Http\Livewire\Members::class)->name('members')->middleware('auth');;

Here is my login component.
    <?php

namespace App\Http\Livewire;

use Livewire\Component;

class Login extends Component
{

    public $user;

    public function mount(){
    }
    public function login(){
        return redirect()->route('analytics');
    }
    public function render()
    {
        return view('livewire.login');
    }
}


text:
Q: Sort each column in a data frame and get common in the top 50 percentage I have a file format like this
data<-mtcars[,c("mpg","drat","wt")]
data<- tibble::rownames_to_column(data, "Names")

I need to sort (Ascending) all the columns and filter to the top 50 %.
Then from this data, I need to get the common one.
For this purpose, I am using the following code
mpg<-data %>% dplyr::select(Names,mpg)%>%mutate_if(is.numeric, round,digits=3) %>% arrange(desc(mpg))%>% filter(row_number() / n() <= .5)
drat<-data %>% dplyr::select(Names,drat)%>%mutate_if(is.numeric, round,digits=3) %>% arrange(desc(drat))%>% filter(row_number() / n() <= .5)
wt<-data %>% dplyr::select(Names,wt)%>%mutate_if(is.numeric, round,digits=3) %>% arrange(desc(wt))%>% filter(row_number() / n() <= .5)

The code above will sort and filter the top 50 percentage
join_all(list(mpg,drat,wt),by = 'Names', type = 'inner')

This will print the common in the top 50 percent from all columns.
Is there any way to do this via some package or function like a single line?

A: Sure you can. Here's a single-line dplyr solution:
library(dplyr)

filter(data, if_all(c(mpg, drat, wt), ~rank(-., ties.method = "first")/n() <= 0.5))

#>      Names  mpg drat   wt
#> 1 Merc 280 19.2 3.92 3.44

A: Simply use
data %>% filter(mpg>=median(mpg) & drat>=median(drat) & wt >= median(wt))
     Names  mpg drat   wt
1 Merc 280 19.2 3.92 3.44


text:
Q: Editing a post shown in the "Low Quality Posts" page of the new review system redirects me to the question page after I am done Today, I edited two posts that were shown in the "Low Quality Posts" page for the new review system. After I clicked on "Save Edits," I was asked if I wanted to leave the page, or stay on that page. Thinking it was a revival of a bug that was reported before, I clicked on "Leave page," and I was redirected to the page showing the question, with the edited post highlighted.
I noticed this only today. Before, I was not redirected to other pages, when editing low quality posts.
The edits I have done were saved, though. It is just a matter of being redirected to a different page when it is not supposed to happen.

A: We recently introduced a javascript bug (by using strict while missing a var), which broke the submission flow on certain browsers. This caused the edit form to be submitted normally, as opposed to via ajax. It's fixed now; thanks for the report.


text:
Q: What is regularity of solution of Dirichlet problem with Dirac distribution as boundary data? I was thinking if we have Dirac distribution as boundary condition, then what will be regularity of solution. Problem is following,
$$
\left\{\begin{matrix}
\nabla_x(\gamma(x)\nabla_x u(x,y))=0 & in~\Omega\\
u(x,y)=\delta_y(x) & on ~\partial \Omega
\end{matrix}\right.
$$
where $x,y\in \mathbb R^n , \gamma(x)>c>0 $. $\Omega$ is with smooth boundary.
Any help or  reference is greatly appreciated.

A: For a regular enough boundary function $\psi$ the solution of the first BVP can be written as
$$
u(x)=\int_{\partial \Omega}\frac{\partial G(x,y)}{\partial \bar n_y}\gamma(y)\psi(y)\,dy,
$$
where $G(x,y)$ is the Green function of the corresponding first BVP and $\bar n_y$ is a unit normal vector to $\partial\Omega$. It follows from the Green's third identity written out for your operator.
Substituting $\psi(x)=\delta_y(x)$ gives $u(x)=\gamma(y)\frac{\partial G(x,y)}{\partial n_y}$. In some cases this function  is also called the Poisson kernel. Estimates for the Green function are known (for smooth enough coefficients and bounded domains they are the same as for a fundamental solution) and it follows that
$$
|u(x,y)|\le C|x-y|^{1-n} \quad x\in \Omega,\ y\in \partial \Omega.
$$


text:
Q: Sencha Touch 2 and Blackberry OS 7: TabPanel Buttons Misrendering The Problem
The Tab Panel buttons in my Sencha Touch 2 app are displaying incorrectly within my Blackberry OS 7 device.  This is what they look like:

Environment Details

*

*Blackberry Torch 9810

*Blackberry OS 7.0

*Sencha Touch 2.0.1

Troubleshooting

*

*I ran the web site in the Blackberry OS 10 Simulator successfully.  The tab icons look fine

*The buttons look fine in Android and iOS apps.

Solutions
I've upgraded my Blackberry Torch I'm testing the site on from 7.0 to 7.1 and the buttons are rendering correctly now, however, that does not solve my problem for folks still on v7.0.  Has anyone gotten this working correctly in 7.0?
Thanks for your help with this!


text:
Q: Different presentation of WPF application - runtime vs designer Why do I get different presentations of my WPF application with the Visual Studio 2012 Designer versus the application at runtime?
See numbers 1 and 2 in my screenshot.
How can I avoid that behaviour?

A: For the window style does not apply you can check out the solution here Windows Style from ResourceDictionary don't apply
And as for the inconsistency theres nothing you can do to avoid it. Since the designer is doing some static analysis and make the best guess of what will show up, but in reality the load order is never that easy to predict.


text:
Q: Call Btn is giving wrong number I set an IBAction fucntion in Swift 3 Xcode 10.1 and this code bellow, using back end db as back4app where i store data and numbers
but after hitting call button that should retrieve numbers from columns it give me word like this Optional(6788899)
instead of the number only to be able to make the call via the mobile phone, what can cause this word to appear any help please
//check for missing data
if(phone == nil || phone == 0){
    let alert = UIAlertController(title: "", message: "No phone available", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
    self.present(alert, animated: true, completion: nil)
}else{
    let url:URL = URL(string: "tel://" + String(describing:phone))!
    UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
}

A: You have to unwrap the optional phone.
let url = URL(string: "tel://" + String(describing:phone!))!

However this is a swiftier way to do that.
And please don't misuse String(describing:
//check for missing data
if let phoneNumber = phone, phoneNumber != 0 {
    let url = URL(string: "tel://\(phoneNumber)")!
    UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
} else {
    let alert = UIAlertController(title: "", message: "No phone available", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
    self.present(alert, animated: true, completion: nil)
}


text:
Q: New Terminal At Folder service in El Capitan doesn't use my Terminal profile settings I have my Terminal preferences set to use the "Pro" profile. When I launch a Terminal session from the dock, it uses the "Pro" profile (black background). However when I launch a Terminal session from "Services -> New Terminal at Folder" in Finder, it uses the "Basic" profile (white background). How can I set it to always use the "Pro" profile?

A: After launching Terminal.app the active profile of the shell  window is determined by the settings chosen in: Preferences > General > On startup open...
The profile of the next Terminal window opened or the one launched by Services -> New Terminal at Folder uses a default profile which can be configured here: Preferences > Profiles > Text: choose a profile in the left pane and hit the default button at the bottom.


text:
Q: Success function is not called in ajax form $('#upload').on('click',function(){
$('#upload_form').ajaxForm({
    url:insert_url,
    type:'post',
    target:'#preview',
    beforeSubmit:function(e){
        console.log('before');
        $('.progress').show();
    },
    success:function(res, status, xhr, form){
        console.log('che');
        $('.progress').hide();
    },
    error:function(e){
        console.log('error');
    }
}).submit();

I have a post form, but I was wondering how to get Success function to work if my photos are uploaded.  It seems the function is not called at all.
Please help me out if you know.

A: Are you using jQuery form plugin? If so, make sure it's source added to the HTML and loaded without errors.
Your code seems incomplete, is it because you just have other stuff inside of $('#upload').on('click',function(){? If not, make sure that you close the function, here's what I mean (I also fixed the indentation):
$('#upload').on('click', function() {
    $('#upload_form').ajaxForm({
        url: insert_url,
        type: 'post',
        target: '#preview',
        beforeSubmit: function(e) {
            console.log('before');
            $('.progress').show();
        },
        success: function(res, status, xhr, form) {
            console.log('che');
            $('.progress').hide();
        },
        error: function(e) {
            console.log('error');
        }
    }).submit();
});

Also make sure that insert_url is defined before this code.
If it still doesn't work, does the console show "before", "che" or "error"?


text:
Q: DROP table using Room persistence library Is there any way to drop tables directly while using Room . I have tried the below code under DAO class
@Query( "DROP TABLE IF EXISTS 'tablename'" )
    void dropFavoriteShowEpisodeTable();
But I am unable to build and error is

UNKNOWN query type is not supported yet. You can use:DELETE, UPDATE, SELECT

I understand that during migration , I can directly drop tables using
database.execSQL( "DROP TABLE IF EXISTS 'tablename' );

But what if I want to drop a table at a later stage. How to achieve that ?
Thanks in advance

A: No Room doesn't support Drop at all. You need to delete all the records by using
DELETE * FROM TABLENAME


text:
Q: Additive and multiplicative identites help our new maths teacher (BSc Hons) just started a topic. He wrote all these theorems but I'm unable to understand them and prove the statements.
They are as follows:
Theorem: The addition axioms for field imply the following statements:

*

*If x+y = x+z, then y=z

*If x+y =x, then y = 0

*If x+y = 0, then y= -x

*-(-x) = x

Eg, my teacher has proved the first statement by doing this:

*

*If x+y = x+z, then y=z

Y= 0+Y
=(-x+x) + y    (Inverse)
=-x + (x+y)    (Associative)
=-x + (x+z)    (Given)
=(-x+x) + z    (Inverse)
=(0) + z       (Identity)
=z
I've tried so hard to understand, can anyone give me an idea how to solve them? If you want, I can write all of the proofs if anyone is willing to make me understand them.


text:
Q: Magento CE 1.8 zoom function in Products.js from Product.Zoom is causing problems with scaling (missing statement) In the new version of Magento CE 1.8 there is a problem with the zoom function in that it only scales the height, and not the width.  Scaling worked before this. I chased it down to the template/catalog/product/view/media.phtml file where there is a call to Product.Zoom on the image in Products.js.
Well I after hours of debugging I found the solution to this problem.  When looking at older versions of magento, I compared the Products.js file and it seems that in the Product.Zoom.prototype function the line "this.containerDim.ratio = this.containerDim.width/this.containerDim.height" was deleted from the new version of 1.8.  Its missing.
Once I added that line, it worked again.  I decided to post this question in case anyone wants to fix it fast in the future.  Thanks.


text:
Q: php search string in encoded json I want to search a particular string like "Booking Time" in encoded json object and want to print,
please check with encoded json example:-
{"1":["Booking Time","08-Oct-2017 23:18","Booking ID","ATO055GMEUZ"]}

A: You need to format your JSON like below:-
{
  "1": {
    "Booking Time": "08-Oct-2017 23:18",
    "Booking ID": "ATO055GMEUZ"
  }
}

You can convert from json to array and do a loop to search.
$json = json_decode($str);


text:
Q: How to Scroll textbox automatically in Scrollviewer when press left/right arrow keys? I am wrapping the textbox with scrollerviewer. The problem is when there is enough text to scroll horizontally, and we use the left/right arrow to move through text, the cursor moves beyond the display area, but it doesn't auto scroll the content.
<Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <ScrollViewer Grid.Row="0" Grid.Column="0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <TextBox x:Name="Text1" AcceptsReturn="True" MinWidth="150" MinHeight="150"/>
        </ScrollViewer>
    </Grid>

Any expert here?

A: Dont wrap your TextBox with a ScrollViewer. TextBox has already scrolling-support.
Do the following with your TextBox:
<TextBox x:Name="Text1" Grid.Row="1" AcceptsReturn="True" MinWidth="150" MinHeight="150" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible"
                 ScrollViewer.VerticalScrollBarVisibility="Auto"
                 ScrollViewer.HorizontalScrollBarVisibility="Auto" />

Here an Example, that shows the difference:
<Grid Width="100" Height="300">
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>

        <ScrollViewer Grid.Row="0" Grid.Column="0" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Margin="0,20,0,0">
            <TextBox x:Name="Text2" AcceptsReturn="True" MinWidth="150" MinHeight="150"/>
        </ScrollViewer>
        <TextBox x:Name="Text1" Grid.Row="1" AcceptsReturn="True" MinWidth="150" MinHeight="150" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible"
                 ScrollViewer.VerticalScrollBarVisibility="Auto"
                 ScrollViewer.HorizontalScrollBarVisibility="Auto" />

    </Grid>

Hope this helps!


text:
Q: Año Bisiesto con DateDiff SQL Deseo conseguir en un procedimiento almaceando que al ingresar el año me arroje si tiene los 365 del año o los 366 si es año bisiesto
    CREATE PROCEDURE PruebasDeAñoBisiestos
    -- Add the parameters for the stored procedure here
@Año int

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT DATEDIFF(DAY, '@Año/01/01', '@Año/12/31') AS Diferencia;
END
GO

A: Podrías hacer lo siguiente:
DECLARE @Year INT
SELECT  @Year = 2012

SELECT DATEDIFF(DAY, CONVERT(VARCHAR, @Year)+'0101', CONVERT(VARCHAR, @Year+1)+'0101')

Recuerda que el el datediff no es inclusivo de los límites, es decir si haces: DATEDIFF(DAY, '20180521', '20180522') te retornará 1 cuando para lo que buscas el resultado debiera ser 2. Por eso el cáculo debe hacerse desde el primero de enero de un año al mismo día del otro.


text:
Q: "javascript" bar graph that breaks down annual columns to monthly I would like the make a bar or column graph using daily data, and by default user should get annual representation of the data, then if the user clicks on a column of a specific year, they get a monthly break down of that year.
Please help
Thanks

A: Also add the desire plugin to it
<script>
window.onload = function () {

var chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,

    title:{
        text:"Fortune 500 Companies by Country"
    },
    axisX:{
        interval: 1
    },
    axisY2:{
        interlacedColor: "rgba(1,77,101,.2)",
        gridColor: "rgba(1,77,101,.1)",
        title: "Number of Companies"
    },
    data: [{
        type: "bar",
        name: "companies",
        axisYType: "secondary",
        color: "#014D65",
        dataPoints: [
            { y: 3, label: "January" },
            { y: 7, label: "Febrary" },
            { y: 5, label: "March" },
            { y: 9, label: "April" },
            { y: 7, label: "May" },
            { y: 7, label: "June" },
            { y: 9, label: "Jult" },
            { y: 8, label: "August" },
            { y: 11, label: "September" },
            { y: 15, label: "October" },
            { y: 12, label: "November" },
            { y: 15, label: "December" },
        ]
    }]
});
chart.render();

}
</script>


text:
Q: ERROR: configuration failed for package 'gsl' I am trying to install R package gsl and I get
configure: error: Need GSL version >= 1.16
ERROR: configuration failed for package 'gsl'

There is a similar post here, but the solution suggested there didn't work and I don't know where to look for the cause of the problem.
I am working on Ubuntu. I have GSL version 2.3
gsl-config --version
2.3

A: I found this online and it worked (signature from the original poster):

*

*download the source package

*uncompress/unarchive the package

*delete the 2 configure scripts

*in src, rename Makevars.in Makevars

*edit Makevars, replace @GSL_CFLAGS@ with the output of 'gsl-config —cflags' and replace @GSL_LIBS@ with the output of 'gsl-config —libs'

*R CMD INSTALL the gsl directory

Hope that works,
Kjell

There are also instructions in the manual of the package (for version 2.1-7.1 they are on page 33). The 2 sets of instructions are very similar, but those from the manual alone didn't work for me.
This is how my Makevars file looks like

GSL_CFLAGS = -I/usr/local/include

GSL_LIBS   = -L/usr/local/lib -lgsl -lgslcblas -lm

#combine to standard arguments for R

#PKG_CPPFLAGS =  $(GSL_CFLAGS) -I.

#PKG_LIBS = $(GSL_LIBS)

PKG_LIBS=-L/usr/local/lib -lgsl -lgslcblas -lm

PKG_CPPFLAGS = -I/usr/local/include


text:
Q: Consider mysql pivot table? SELECT T.fromP,T.toP,T.value,T.type FROM CELLPROPERTYFACT F
INNER JOIN DIM_TIMING T ON T.timingID = F.timingID
WHERE T.cellID = '1'
AND (type = 'cell_rise' or type = 'cell_fall');

+-------+------+----------+-----------+

| fromP | toP  | value    | type      |

+-------+------+----------+-----------+

| ZN    | A1   | 0.168072 | cell_fall |

| ZN    | A1   | 0.176866 | cell_rise |

| ZN    | A2   | 0.177704 | cell_fall |

| ZN    | A2   | 0.176244 | cell_rise |

+-------+------+----------+-----------+

I get above result...is it possible to make it become
+-------+------+------------+-----------+

| fromP | toP  | cellRise   | cellFall  |

+-------+------+------------+-----------+

| ZN    | A1   | 0.176866   | 0.168072  |

| ZN    | A2   | 0.176244   | 0.177704  |

+-------+------+----------+-------------+

Edit:
SELECT T.fromP,T.toP,value,type,
case when type = "cell_rise" then value end as CellRise,
case when type = 'cell_fall' then value end as CellFall,
FROM CELLPROPERTYFACT F
INNER JOIN DIM_TIMING T on T.timingID = F.timingID
WHERE F.cellID = '1'
AND (T.type='cell_Rise' or T.type='cell_fall') ;

 +-------+------+----------+-----------+---------------------+---------------------+
| fromP | toP  | value    | type      | CellRise            | CellFall            |
+-------+------+----------+-----------+---------------------+---------------------+
| ZN    | A1   | 0.168072 | cell_fall |                NULL | 0.16807200014591217 |
| ZN    | A1   | 0.176866 | cell_rise | 0.17686599493026733 |                NULL |
| ZN    | A2   | 0.177704 | cell_fall |                NULL | 0.17770400643348694 |
| ZN    | A2   | 0.176244 | cell_rise | 0.17624400556087494 |                NULL |
+-------+------+----------+-----------+---------------------+---------------------+

This is the best i can get...how to merge the same fromP and toP? if using group by only can show either cell rise or cell fall


text:
Q: Want the prototype method to be extended I have the following code:
    var defaults = {
        test: function () {
            alert('Test');
        }
    };

    function Foo(options) {
        o = $.extend({}, defaults, options);
        Foo.prototype.test = o.test;
    }
    Foo.prototype.test = defaults;

I want that the test method should be extensible and I want it to be used as:
    var f = new Foo({
        test: function() {
            alert('Test2');
        }
    });

    var f1 = new Foo({
        test: function () {
            alert('Test3');
        }
    });

    f.test();//alert(test2) should be called
    f1.test(); //alert(test3) should be called

Edit: I am not getting what I have written in the comments as the output.

A: You're kind of mixing metaphors there. Three options for you:

*

*Functional

*Simple constructor functions, override per instance (what you were trying to do)

*Reusable prototypical inheritance

Functional
It sounds like you'd like the form of functional inheritance that Douglas Crockford likes, which does away with prototypes in favor of what he calls "maker" functions:
var f = makeFoo({
    test: function() {
        alert('Test2');
    }
});

var f1 = makeFoo({
    test: function () {
        alert('Test3');
    }
});

f.test();
f1.test();

...where makeFoo is:
function makeFoo(options) {
    return $.extend({}, makeFoo.defaults, options);
}
makeFoo.defaults = {
    test: function() {
        alert("Default test");
    }
};

Live example | source
I'm not a huge fan of it myself, but there are many who are and certainly like most things, it has advantages and disadvantages. One of the advantages is how simple it is.
Simple constructor functions, override per instance
But you can do it with constructor functions, much as you tried; you apply the options to this rather than creating your own separate object:
function Foo(options) {
    $.extend(this, options);
}
Foo.prototype.test = function() {
    alert("Default test");
};

var f = new Foo({
    test: function() {
        alert("Test2");
    }
});

var f2 = new Foo({
    test: function() {
        alert("Test3");
    }
});

f.test();
f2.test();

Live example | source
Reusable prototypical inheritance
If you want to go further and have proper hierarchies based on prototypical inheritance (so you can create more than one object with a specific override test function), there's more plumbing to do, but you have the advantage that doing things like calling into a "super"'s version of a function can be quite straight-forward. The plumbing is sufficiently complex that I use a library for it, in my case my own library called Lineage, but Prototype has something similar called Class and there are several others out there.
When doing prototypical inheritance, you have constructor functions and then construct instances with them. The above might look something like this with Lineage:
var ParentFoo = Lineage.define(function(p) {
    p.test = function() {
      alert("Default test");
    };
});

var FooChild1 = Lineage.define(ParentFoo, function(p) {
    p.test = function() {
      alert("Test2");
    };
});

var FooChild2 = Lineage.define(ParentFoo, function(p) {
    p.test = function() {
      alert("Test3");
    };
});

Live example | source

A: couldn't you just do this?
function Foo(options) {
    o = $.extend({}, defaults, options);
    this.test = o.test;
}


text:
Q: Is it possible to - on:hover pause css3 animation and change its background color? I'm using keyframes to constantly change the font-color of an <a> link. On :hover I want to be able to stop the animation and define the font-color .
@-webkit-keyframes fontt {
  0%, 100% {font-size:50px;color:black;}
  50% {color:red;}}
#box a {-webkit-animation: fontt 2s infinite;}
#box a:hover {color:#4480e8;-webkit-animation-play-state: paused;
}

Is it possible to pause the keyframes and also change the font color?
I tried using !important,
I tried putting the color:red; on different naming conventions (a:hover, #box a:hover, #box:hover a
Will having paused keyframes override my :hover? Is there a way to set priority?
Example: http://jsfiddle.net/rvBS2/

A: Rules set by the keyframe seem to have higher importance in the cascade.  I'm not sure if this should be the case, but @media rules have the highest level of importance.  @keyframes either should too or this is a bug.  The cascade spec does not mention them specifically.
Instead of using pause, you can remove the animation entirely.
#box a:hover {-webkit-animation: none;color:red; font-size: 50px;}

http://jsfiddle.net/rvBS2/1/

A: -webkit-animation-play-state: paused and -webkit-animation-play-state: running