text:
Q: Finding $x$ values of $\cos 6x + 1 = \frac{3}{2} + \frac {1}{2} \cos 3x $
Solve $$\cos 6x + 1 = \frac{3}{2} + \frac {1}{2} \cos 3x $$ for $0^\circ<x<120^\circ$

I simplify it to
$$2 \cos 6x + 2 = 3 + \cos 3x $$
There is $\cos 6x $ and $\cos 3x$ how do I merge them together? To solve the equation from $0^\circ$ to $120^\circ$?

A: Hint: Use the identity
$$\cos 2y=2\cos^{2}y-1$$
with $y=3x$.

A: Here's what I got...(EDIT: $3 \cos 3x$ is incorrect in the third line; the correct quantity is $\cos 3x$.).
$$\cos 6x + 1 = \frac {3}{2} + \frac {1}{2} \cos 3x$$
Multiplying by $2$ we get
$$2 \cos 6x + 2 = 3 + \cos 3x$$
Swapping constants and bringing over $\cos 3x$ we then get
$$2 \cos 6x - \cos 3x = 1$$
Using the double angle identity $\cos 6x = 2 \cos^2 3x - 1$ we get
$$4 \cos^2 3x - 2 -  \cos 3x = 1$$
Adding 2 to each side gives us
$$4 \cos^2 3x -  \cos 3x = 3$$
Now we can factor out $\cos 3x$ on the left to get
$$\cos 3x (4 \cos 3x - 1) = 3$$
We now have two equations.  Since $\cos 3x = 3$ has no solution, we concentrate on $4 \cos 3x - 1 = 3$; this yields
$$4 \cos 3x = 4$$ or $$\cos 3x = 1$$
Taking the inverse cosine of both sides we get
$$3x = 0 + 360\times k$$ (k in degrees)
and then dividing by 3 we get
$$x = 0 + 120 \times k$$
For the condition $x \in (0, 120)$ we arrive at the answer, $$\bbox [yellow] {x=120}$$.
CHECK: $\cos 6(120) + 1 \rightarrow 1 + 1 \rightarrow 2$ and $\frac {3}{2} + \frac {1}{2} \cos 360 \rightarrow \frac {3}{2} + \frac {1}{2} \rightarrow \frac {4}{2} \rightarrow 2 \checkmark$
Alternative answer (as suggested by Lab Bhatterchajee):
Instead of factoring out as above, substitute $u = \cos 3x$ and subtract $3$ from both sides gives us
$$4u^2 - u + 3 = 0$$
Using the quadratic equation $x = \frac {-b \pm \sqrt {b^2-4ac}}{2a}$ we have
$$u = \frac {-1 \pm \sqrt {1^2-4(4)(-3)}}{(2)(4)}$$, which leaves us with
$$u = \frac {1 \pm 7}{8}$$
Bringing back $u = \cos 3x$ we have two solutions:
$$\cos 3x = -\frac {3}{4}, 1$$
Since we are looking for values from $0$ to $120$, we discard the negative value and continue on from $\cos 3x = 1$ from before - yielding the same answer as above, avoiding an extraneous solution.


text:
Q: Second Lync application built on Managed SIP Application API is not receiving SIP messages We have the same application built on the Managed SIP Application API that we wish to run twice on the same Front End server. They're using the same name, the same MSPL script and the same code except their configuration (.config) is slightly different.
What happens is the first instance we start works fine and is receiving SIP messages, but as soon as the second instance is started the first instance is no longer receiving any SIP messages and now only the second instance is receiving SIP messages. We would like for both of our instances to handle all the SIP messages which we've been unsuccessful in so far.
The MSPL script we're using to dispatch the SIP messages is:
<?xml version="1.0"?>
<r:applicationManifest
 r:appUri="http://example.com/ProgramName"
 xmlns:r="http://schemas.microsoft.com/lcs/2006/05">

  <!-- Handle incoming requests to Lync server -->
  <r:requestFilter methodNames="ALL"
                   strictRoute="true"
                   registrarGenerated="true"
                   domainSupported="true"/>

  <!-- Handle outgoing requests to Lync server-->
  <r:responseFilter reasonCodes="ALL"/>

  <r:splScript>
    <![CDATA[

if (sipRequest)
{
  //Ignoring benotify events.
  if(sipRequest.Method =="BENOTIFY")
  {
    return;
  }

  Dispatch("OnRequest");
}
else
{
  Dispatch("OnResponse");
}

]]>
  </r:splScript>
</r:applicationManifest>

which are handled by the following OnRequest and OnResponse messages:
public void OnRequest(object sender, RequestReceivedEventArgs evt)
{
  // Do some stuff with evt.Message

  evt.ServerTransaction.EnableForking = false;
  evt.ServerTransaction.CreateBranch().SendRequest(message.Message as Request);
}

public void OnResponse(object sender, ResponseReceivedEventArgs evt)
{
  // Do some stuff with evt.Message

  evt.ClientTransaction.ServerTransaction.SendResponse(message.Message as Response);
}

Here's how these programs are registered as server applications (output from Get-CsServerApplication):
Identity   : Service:Registrar:FQDN/ExampleProgramName
Priority   : 12
Uri        : http://example.com/ProgramName
Name       : ExampleProgramName
Enabled    : True
Critical   : False
ScriptName :
Script     :

Identity   : Service:Registrar:FQDN/ExampleProgramName
Priority   : 13
Uri        : http://example.com/ProgramName
Name       : ExampleProgramName
Enabled    : True
Critical   : False
ScriptName :
Script     :

We've also tried registering the same application under different names. For example, we renamed one of the two instances to ExampleProgramName2 in the MSPL script as well as in New-CsServerApplication which did not work either.
In particular, we are unsure about the requestFilter in the MSPL script and the particular SendResponse/SendRequest method calls as well as the EnableForking property.

A: Register the server application with different names:
New-CsServerApplication -Identity FQDN/ExampleProgramName1 -Uri http://example.com/ProgramName1 -Critical $False
New-CsServerApplication -Identity FQDN/ExampleProgramName2 -Uri http://example.com/ProgramName2 -Critical $False

As well as give each program their unique name in MSPL matching the value given in the Uri parameter of New-CsServerApplication:
<r:applicationManifest
  r:appUri="http://example.com/ProgramName1"

<r:applicationManifest
  r:appUri="http://example.com/ProgramName2"

This should be enough.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP Mail() sent to Outlook breaks code I've looked around here but could not find an answer regarding the problem that I am facing.
Most similar to my problems are in this: emails sent with php mail don't show up correctly in outlook , but I checked and the solution did not work for me.
I am basically writing a PHP script that sends out emails, with a table in it. The problem however, is that if I receive it in gmail, the email shows up fine, but it does not even come through to Outlook at all.
Examining the source code of emails that do make it through to Outlook, shows a line break for some reason (again not present in gmail)
Eg:
<td>  xyz@aaa
tt.com </td>

When it should show up as:
<td>  xyz@aaatt.com </td>

In my php code, I even try to remove the line returns and spaces (as there should be no spaces in emails)
$rmv = array("\n");
$lead_email = str_replace($rmv, "", $lead_email);

$rmv = array("\r");
$lead_email = str_replace($rmv, "", $lead_email);

$rmv = array(" ");
$lead_email = str_replace($rmv, "", $lead_email);

For reference, my mail header is as follows:
$headers  = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\n";
$headers .= 'From: helpdesk@viatechcrm.com' . "\n";

Btw should I use iso-8859-1 or utf-8? I occasionally encounter names with European characters.
Any help greatly appreciated!
EDIT: So I was examining the source code, and found something interesting. The message is really long, but it only shows 3-4 lines. I found that it gets cut off right about 991 characters, thus the email breaking up.. Is this something to do with the Mime-Version 1.0?
How can I increase the number of characters it can receive? I tried adding '\r\n' after every table row, but one of the 4 emails still does not show up for some reason
EDIT 2: Thanks everyone for the help! I finally figured it out, in a forum post dated back in 2009. For future reference, refer to the last posting:
http://forums.devarticles.com/php-development-48/formatting-a-newline-line-break-in-php-html-output-5274.html

A: You should use UTF-8 if you have non-alphanumeric characters. You should end each header line with a "\r\n", not just a plain "\n". Not sure if this will fix your problem as I can't test, but it is something that you should fix nontheless.

A: It sounds like you have only added "\r\n" to the HTML part of your message. All header lines must end in "\r\n", not just the lines in the body. Some clients and servers will cope with just "\n" but they really don't have to (see RFC 2822), hence the inconsistencies between Gmail and Outlook.


text:
Q: Can't find the recorded file using Media.startRecord i am using the Media class to record from device mic, is sucessful recorded but i can't find the audio file(myrecording.amr) on my android device.
function recordAudio() {
    var src = "myrecording.amr";
    var mediaRec = new Media(src, onSuccess, onError);
    // Record audio
    mediaRec.startRecord();
    // Stop recording after 10 sec
    var recTime = 0;
    var recInterval = setInterval(function() {
        recTime = recTime + 1;
        setAudioPosition(recTime + " sec");
        if (recTime >= 10) {
            clearInterval(recInterval);
            mediaRec.stopRecord();
        }
    }, 1000);
}

function onDeviceReady() {
    app.enabled("btnRecord", true);//IDE widget

}
// onSuccess Callback
//
function onSuccess() {
    app.alert("recordAudio():Audio Success");//IDE widget
    //app.setValue("labelmobile1", mediaRec.); IDE widget
}

// onError Callback
//
function onError(error) {
    alert('code: '    + error.code    + '\n' +
          'message: ' + error.message + '\n');
}

// Set audio position
//
function setAudioPosition(position) {
    app.setValue("label1", position);//IDE widget
}

Where i can find it?

A: Try this
var filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,<directoryName>);
var src=file.getAbsolutePath()+""myrecording.amr"

Your file will be created inside <directoryName>

A: My guess that it's created in your Android app home directory, since you are using relative path.
You can check here how to find your home directory:
Android Get Application's 'Home' Data Directory
However, I agree with Mukund. It's much better to specify absolute path in this case.

A: If you do not specify a path then the Media.startRecord() method will default to putting your file at the location specified by Environment.getExternalStorageDirectory(). Check for it in /sdcard or /mnt/sdcard.

A: you can find it in the sdcard and the path will be:
"/sdcard/myrecording.amr"


text:
Q: Unable to change dropdown value using Reactjs I am working on Reactjs/Nextjs and right now I am trying to change the dropdown value (working on the update module).
I tried the following code but it's not working.
const Post =  function(props) {
    const [content2, setContent2] = useState('');
    }

useEffect(()=>{
    setContent2(post?.cat_name);
},[])

 <select value={post?.cat_name} className="form-control" name="cat_name" id="cat_name" onChange={(con2) =>
    {
        setContent2(con2);
    }}>

 <option value="">Select Category</option>
    <option value="pined"  >Pined</option>
 </select>

Any help would be great.

A: use content2 as value
value={content2}

A: you can initialize content2 in declaration
 const [content2, setContent2] = useState(post? post.cat_name : "");

then the value attribute in select should be content2 also in onChange try to use event
<select
  value={content2}
  className="form-control"
  name="cat_name"
  id="cat_name"
  onChange={(event) => {
    setContent2(event.target.value);
  }}
>
  <option value="">Select Category</option>
  <option value="pined">Pined</option>
</select>


text:
Q: Every invertible linear transformation can be perturbed a bit without destroying invertbility, Neumann series
*

*Let $T: V \to V$ be any linear transformation on a real or complex vector space $V$. Show that there exists $\epsilon_0 > 0$ $($depending on $T$$)$ so that $I + \epsilon T$ is invertible for any $|\epsilon| < \epsilon_0$.

*Now suppose $S: V\to V$ is an invertible linear transformation and let $T$ be as in $(1)$. Show that there exists $\epsilon_0 > 0$ $($depending on $S$ and $T)$ so that $S + \epsilon T$ is invertible for any $|\epsilon| < \epsilon_0$.

For such a fundamental fact in the study of linear algebra I cannot find a proof of this anywhere... can anyone supply a proof or refer me to a place where I can find one?

A: *

*A matrix is invertible iff the determinant is not equal to zero.

*Determinant is a continuous function of the entries of a matrix.

A: 1.
We first talk a bit about the underlying method of the proof. We want look for $(I + \epsilon T)^{-1}$ as an infinite series, similar to the way we would expand $1/(1+x)$ into a power series for $|x| < 1$ over the real or complex field. We then show that our infinite series of operators converges. Along the way, we need to use the fact that $\|TS\| \le \|T\|\|S\|$ where $\|\cdot\|$ is the operator norm.
Now for the proof. If $\|T\| < 1$, then the sum $$\sum_{n=0}^\infty T^n$$ converges, since$$\sum_{n=0}^\infty \|T^n\| \le \sum_{n=0}^\infty \|T\|^n.$$Thus$$(I-T)\sum_{n=0}^\infty T^n = \lim_{k \to \infty}(I - T) \sum_{n=0}^k T^n = \lim_{k \to \infty} \left(I - T^{k+1}\right) = I.$$So for $\|T\| < 1$, $\left(I + T\right)^{-1}$ exists and equals $$\sum_{n=0}^\infty (-1)^nT^n.$$For general $T$, pick $\epsilon$ such that $\|-\epsilon T\| < 1$ and apply what we just did.
2.
The underlying method of proof for this part is to reduce to $(1)$ by pulling out $S$. We have $S + \epsilon T$ is invertible if and only if $(S + \epsilon T)S^{-1}$ is, i.e. if and only if $I + \epsilon(TS^{-1})$ is. Now use $(1)$.

A: Let us assume that $V$ is complete (otherwise, this is probably false). Note that finite dimensional normed vector spaces are always complete.
Also, let us assume that $T$ is not an arbitrary linear transformation, but a bounded linear transformation, which means that
$$
\Vert T \Vert := \sup_{\Vert x \Vert \leq 1} \Vert Tx \Vert < \infty. \qquad (\dagger)
$$
If $\Vert T \Vert < 1$, then the Neumann series (which is mentioned in the title of your question)
$$
S := \sum_{n=0}^\infty T^n
$$
is convergent (even absolutely) in the Banach(!) space $B(V)$ of linear bounded maps $V \to V$ equipped with the norm $\Vert \cdot \Vert$ defined in $(\dagger)$.
It is an easy exercise to show that $(I-T) S = S(I-T) = I$. Hence, $I-T$ is invertible.
Now apply this to $-\varepsilon T$ instead of $T$. For $|\varepsilon|$ small enough, you will have $\Vert -\varepsilon T \Vert < 1$, so that $I + \varepsilon T = I - (-\varepsilon T)$ is invertible by the above argument.
Now, let $S$ be invertible (and also bounded). By the above (applied to $S^{-1}T$ instead of $T$), we know that $I + \varepsilon S^{-1} T$ is invertible for $|\varepsilon|$ small enough.
But compositions of invertible maps are invertible, so that
$$
S \cdot (I + \varepsilon S^{-1}T) = S + \varepsilon T
$$
is also invertible for $|\varepsilon|$ small enough.


text:
Q: Speed up double summation Is there any way how to speed up this double summation?
(*Define Function*)
a = -0.07;
b = -0.45;
c = 2.;
d = 3.;
tau = 2.;
dt=10.^-2;
e = c*tau;
ft[t1_] = a*Exp[-t1/d] - b*Exp[-t1/e];
g[t1_, t2_, t3_] = ft[t1]*ft[t2]*ft[t3];

factor[x_, y_] := factor[x, y] = g[0., x*dt, y*dt]
sumfactor[h_, g_] := Sum[factor[x, y], {x, 0, h}, {y, 0, g}]

Module[{k = 3000}, sumfactor[k, k]]

For arguments like 3000 in the function sumfactor this is pretty slow unfortunately.

A: There is a much faster way. Since the sumand is quite simple, you can get an analytic expression of your sum.
There are two ways, either with Rationalize or without.
 su[h_, g_] =Sum[Rationalize[factor[x, y], 0], {x, 0, h}, {y, 0, g}]

 su2[h_, g_] = Sum[factor[x, y], {x, 0, h}, {y, 0, g}]

Results not schown here, because to long.
Then you don't need to sum up, but just evaluate the calculated functions su or su2
 N[su[2000, 2000], 30] // Timing

 (*     {2.47025*10^-15, 9486.97325178896101045672676230}    *)

 N[su2[2000, 2000], 30] // Timing

 (*    {8.32667*10^-17, 9486.97}     *)

Exactly the same as your result
 N[sumfactor[2000, 2000], 30] // Timing

 (*    {17.688, 9486.97}    *)

A: In version 12.1, you can speed up the accepted answer from Szabolcs with FunctionCompile:
cf = FunctionCompile[
  Function[{Typed[k, "MachineInteger"]},
   Module[{a, b, c, d, tau, dt, e, ft, g, factor, xx, yy},
    a = -0.07;
    b = -0.45;
    c = 2.0;
    d = 3.0;
    tau = 2.0;
    dt = 0.01;
    e = c*tau;
    xx = ConstantArray[N@Range[0, k], k + 1]; yy = Transpose[xx];
    Typed[
      KernelFunction[
       Total], {TypeSpecifier["PackedArray"]["Real64", 2],
        "MachineInteger"} ->
       "Real64"][(a*Exp[0.0] - b*Exp[0.0])*(a*Exp[-xx*dt/d] -
        b*Exp[-xx*dt/e])*(a*Exp[-yy*dt/d] - b*Exp[-yy*dt/e]), 2]
    ]]]

cf[3000] // AbsoluteTiming

I get about a 3x speed up this way.

A: Use vectorization.
factor[x_, y_] = g[0., x*dt, y*dt]

Assuming h=g=3000:
xx = ConstantArray[N@Range[0, 3000], 3001];
yy = Transpose[xx];

Total[factor[xx, yy], 2] // AbsoluteTiming
(* {0.375605, 253819.} *)

The key is to pass in a vector (or matrix) containing all possible x, y values, and operate on the entire array at once. This works well if you only use scalar operations, like here.  If you use any vector operations, like Dot, you must be careful to ensure that the operation does what you expect, even on a matrix.

Your code for comparison:
factor[x_, y_] := factor[x, y] = g[0., x*dt, y*dt]
sumfactor[h_, g_] := Sum[factor[x, y], {x, 0, h}, {y, 0, g}]

Module[{k = 3000}, sumfactor[k, k]] // AbsoluteTiming
(* {88.9004, 253819.} *)

A: I'd recommend doing the whole calculation with symbols and substituting only at the end:
ft[t1_] = a*Exp[-t1/d] - b*Exp[-t1/e];
g[t1_, t2_, t3_] = ft[t1]*ft[t2]*ft[t3];
factor[x_, y_] = factor[x, y] = g[0, x*dt, y*dt];
sumfactor[h_, g_] = Sum[factor[x, y], {x, 0, h}, {y, 0, g}] // FullSimplify
(*    (1/((-1 + E^(dt/d))^2 (-1 + E^(dt/e))^2))(a - b) E^(-((dt (d + e) (g + h))/(d e))) (a E^((dt g)/e) (-1 + E^(dt/e)) (-1 + E^((dt (1 + g))/d)) - b E^((dt g)/d) (-1 + E^(dt/d)) (-1 + E^((dt (1 + g))/e))) (a E^((dt h)/e) (-1 + E^(dt/e)) (-1 + E^((dt (1 + h))/d)) - b E^((dt h)/d) (-1 + E^(dt/d)) (-1 + E^((dt (1 + h))/e)))    *)

sumfactor[3000, 3000] //. {a -> -0.07, b -> -0.45, c -> 2, d -> 3, tau -> 2, dt -> 10^-2, e -> c*tau}
(*    9617.85    *)

In this way the calculation is accurate and immediate.


text:
Q: Groovy script not able to execute external process I'm trying to execute a python external process from my Groovy script but it doesn't produce any output.
So as a small sanity test I tried simply outputting the python version:
    def command = """ /usr/local/bin/python -V """
    def proc = command.execute()
    proc.waitFor()
    println "This is output: " + proc?.in?.text

The above doesn't produce any output, however, from my command line I AM able to run /usr/local/bin/python -V
What is weird is that if I modify the script to run identify then it does produce an output.
    def command = """ /usr/local/bin/identify --version """
    def proc = command.execute()
    proc.waitFor()
    println "This is output: " + proc?.in?.text

What can be causing this behavior?

A: python -V command prints the version number to standard error instead of standard output.
$ python -V
Python 2.7.8
$ python -V 2>/dev/null
$

So, to get the output, redirect the stderr (2) to stdout (1):
def command = """ /usr/local/bin/python -V 2>&1 """
def proc = command.execute()
proc.waitFor()
println "This is output: " + proc?.in?.text

Alternatively, you can use err instead of in to get standard error output:
def command = """ /usr/bin/python -V """
def proc = command.execute()
proc.waitFor()
println "This is output: " + proc?.err?.text


text:
Q: Save excel file to disk after binding from repeater I'm creating an excel file from a repeater control and allowing the user to save the file. After generating the excel file how can I save this to disk. I want to send this as an attachment inside of an email
Dim output As String = WebUI.RenderControl(plcList)
Response.AppendHeader("content-disposition", "attachment;filename=report_dd_rejection.xlxs")
Response.Write(output)
Response.End()

Any help with this would be appreciated.
Thanks
Chris

A: I'm not sure if I understood your question.
But if already have the Excel data being sent to the user browser, you just need to write the data to disk
Dim filePhysicalFolder = Environment.CurrentDirectory()
Dim output As String = WebUI.RenderControl(plcList)

Using outputFile As New StreamWriter(Path.Combine(filePhysicalFolder, "report_dd_rejection.xlxs"))
    outputFile.Write(output)
End Using

Response.AppendHeader("content-disposition", "attachment;filename=report_dd_rejection.xlxs")
Response.Write(output)
Response.End()


text:
Q: How does shifting make this function odd? [Supply current of 3 phase semi converter]

I've been told that shifting this waveform left by 30 + a/2 will make it odd.
Odd means f(a) = -f(a), right? So, how it that happening here?
Or am i missing something? Signal shown is the supply current waveform of a 3 phase semi controlled rectifier.

A:
Function $f$ is said to be even if $f(-x)=f(x)$ for all such $x$ that both sides of equality are defined. From graphic point of view even functions are symmetric about the y-axis.
Function $f$ is said to be odd if $f(-x)=-f(x)$ for all such $x$ that both sides of equality are defined.

Now let $f$ be the function from your sketch (with 3 humps). Obviously it's neither odd nor even. But if we consider function $g$ obtained from $f$ by left shift to meet the following plot:

we'll see that $g$ is even. As you may observe, there's no such shift that would make function $f$ odd. However by some shifts you can obtain such function $h$ that its restriction to an interval $(-a,a)$ for some $a$ would be odd. The most meaningful ways to do this are like this

or like this

Pink background indicates the chosen interval.


text:
Q: Swing - invisible column throwing exception when accessing Background
I have a JTable called table, and I have a column that is not part of the DefaultTableModel so its invisible:
final JTable table = new JTable(new DefaultTableModel(new Object[]{"Title", "Artist",
"Album", "Time"}, 0)

I add the respective rows like this:
int upTo = songList.size();
    int idx = 0;
    while (idx < upTo) {
        SongObject curSong = songList.get(idx);
        model.addRow(new Object[]{
curSong.toString(),
curSong.getArtist(),
"-",
curSong.getDuration(),
curSong});
        idx++;
    }

Where curSong is the the current song object that it is adding, the SongObject contains all data about the song. The toString() returns the title of the song.
Problem:
The problem is that when I try to access the column like this:
SongObject songToPlay = (SongObject) table.getModel().getValueAt(table.getSelectedRow(), 4);

It throws a java.lang.ArrayIndexOutOfBoundsException: 4 >= 4 exception.
Can anyone explain why and propose a solution?
Thanks in advance :)

A: DefaultTableModel.addRow() somewhere down the chain executes private justifyRows() method, which trims the unused columns from the row to the size equal to getColumnCount(). So the fifth column is never added to the model. As a result, you get ArrayIndexOutOfBoundsException when you're attempting to access this column.
If you need access to the actual SongObject then you can have a custom model that would return SongObject for a given row index. Make an extension of AbstractTableModel. See How to Use Tables tutorial for examples.
As an alternative, you can still use SongObject in a visible column. Just use a custom renderder that would renderer SongObject as a string for example. See Using Custom Renderers for details. You can reuse DefaultTableModel in this case.

A: Thanks to Aqua I overrode the following:
final JTable table = new JTable(new DefaultTableModel(new Object[]{"Title", "Artist", "Album", "Time"}, 0) {

        @Override
        public void addRow(Object[] rowData) {
            Vector blah = DefaultTableModel.convertToVector(rowData);
            insertRow(super.getRowCount(), blah);
        }

        @Override
        public void insertRow(int row, Vector data) {
            super.dataVector.insertElementAt(data, row);
            super.fireTableRowsInserted(row, row);
        }
    });

Then I accessed the item in the fifth column (which is not part of the model!) like this:
SongObject songToPlay = (SongObject) table.getModel().getValueAt(table.convertRowIndexToModel(
                                table.getSelectedRow()), 4); //get the value at the VIEW location NOT THE MODEL collection

Sorry for the messy code but it worked. Home I could help someone with a similar problem. The solution just misses the justifyRows() method found in DefaultTableModel


text:
Q: Messenger Hubs : How do they do it? I was wondering how is it possible to create messenger hubs like BlackBerry Hub and Disa as they consolidates Facebook Messenger's messages, WhatsApp messages and many other messenger's messages in the single App.
They all are third-party apps and there's no open APIs available for it.  And yet they are on App store. So it must be some ethical way to doing it. I have digged stackoverflow out but couldn't find a satisfactory answer.
Please note that I'm not expecting code blocks here. Any effort will be highly appreciated.
Thank you.

A: Regarding FB:

To make Facebook Chat available everywhere, we are using the
  technology Jabber (XMPP), an open messaging protocol supported by most
  instant messaging software, including iChat, Pidgin, Adium, Miranda
  and more.

Taken here.
I assume there may be similar possibilities for other applications you need to integrate. Looks like WhatsApp basically uses XMPP too, probably with minor differences. There is a  tool for interconnecting it with plain XMPP.


text:
Q: Unable to get links from html - jsoup With the following code I am able to get the desired text from the website but am unable to get the associated link of the text. Tried several method permutations and combinations. At most what I get is the entire outer html as given below:

Abacavir

Abacavir is an antiviral drug that is effective against the HIV-1 virus.

Here is the code:
   public static void main(String[] args) throws Exception {
        Map<String,String> drugLinks = new LinkedHashMap<String,String>();
        final int OK = 200;
        //String currentURL;
        //int page = 1;
        int status = OK;
        Connection.Response response = null;
        Document doc = null;
        String[] keywords = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
        //String keyword = "a";
        for (String keyword : keywords){
            final String url = "https://www.medindia.net/doctors/drug_information/home.asp?alpha=" + keyword;
                response = Jsoup.connect(url)
                        .userAgent("Mozilla/5.0")
                        .execute();
                status = response.statusCode();

                    doc = response.parse();

                            Element tds = doc.select("div.related-links.top-gray.col-list.clear-fix").first();

                            Elements links = tds.select("li[class=list-item]");

                                for (Element link : links){
                                    System.out.println("generic::"+link.select("a[href]").text());
                                    System.out.println("link::"+link.attr("abs:a"));
                }

            }
        }

Output
generic::Abacavir
link::
generic::Abacavir Sulfate and Lamivudine
link::
generic::Abacavir Sulfate, Lamivudine and Zidovudine
link::
generic::Abaloparatide
link::
generic::Abarelix
link::

How do i get the absolute links from the given HTML?

A: To get the link from the element, you can use:
link.select("a").attr("href")

However, that will only give you the relative link.
The full link will be:
"https://www.medindia.net/doctors/drug_information/" + link.select("a").attr("href")


text:
Q: Will Laravel 5.4 run on PHP 5.6.3? I know that laravel 5.4 need to meets PHP >= 5.6.4. I try to find XAMPP with php 5.6.4 but i have nothing. I just have xampp with php 5.6.3 installed. Will laravel 5.4 run on php 5.6.3?

A: Server requirements for laravel 5.4:
PHP >= 5.6.4
OpenSSL PHP Extension
PDO PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension
XML PHP Extension
Laravel Installation Server Requirements


text:
Q: How do i display only 5 Li's and have a button that displays 5 more I have 500 li's but I only want to show 5 at first, then I can click a button and that shows me more li's and maybe at the end there are no more li's but not all of them just another 5?

A: var $li = $("li"),
    chunk = 5;

$li.slice(chunk).hide();

$("button").click(function() {
    $li.filter(":hidden").slice(0, chunk).show();
});

jsFiddle.
There are more efficient ways to write this code, but this one is fairly readable.

A: You could dynamically add a "more" button after your ul and show 5 li's at a time until all are shown. Then you could hide the more button:
var vis = 5;
$('li').slice(vis).hide();

var $more = $('test')
$more.click(function(){
    $('li:hidden').slice(0,vis).show();
    if($('li:hidden').length == 0)
        $more.hide();
});
$('ul').after($more);

Live example: http://jsfiddle.net/JKWtP/


text:
Q: i want to communicate with 'TestEquity1000' temperature chamber by using 'pyserial' i want to set and get temperature of serial device (testequity1000) by using pyserial but not able to communicate.
cable used RS232
python 3.7
import serial
port = 'COM20'

`   serial_comunication = serial.Serial(port, baudrate=9600, timeout=1)
answer = serial_comunication.read(400)

print(answer)
NEW_TEMPERATURE=45
set_temp=serial_comunication.write(b'NEW_TEMPERATURE')
print(set_temp)
abc=serial_comunication.close()
print(abc)
results:
b''
15
None
can't understand these result

A: Your device seems to be able to communicate on the RS232 bus but you have to use Modbus instead of the raw serial.
Quoting from the manual:

The F4 Temperature Controller has an RS-232C interface. A DB-9
connector is located on the rear panel. It is wired to accommodate a
null-modem cable. To communicate with the controller from a PC, you
need to run software that uses the Modbus RTU protocol. Each
controller function has a "register" number which can be read or
written to (when applicable). These registers are listed Chapter Seven
of the "Series F4 User's Manual". RS-232C Modbus programming resources
and LabVIEW drivers can be downloaded from
http://chamber.testequity.com/rs232.html
Common Modbus Registers
-Actual chamber temperature reading is register 100 (Input 1 Value).
-Actual chamber humidity reading is register 104 (Input 2 Value).
-Static temperature set point is register 300 (Set Point 1).
-Static humidity set point is register 319 (Set Point 2). •
-Temperature set point during a profile is register 4122 (Set Point 1, Current Profile Status).
-Humidity set point during a profile is register 4123 (Set Point 2, Current Profile Status).
-Decimal points are implied. For example, 1005 is actually 100.5 and -230 is -23.0.

Based on these details you can use pymodbus instead. A good starting point is this example.
You can install the package with: pip install pymodbus
So, if you want to read the Actual Chamber Temperature you need to write something similar to this:
#!/usr/bin/env python

# Pymodbus Synchronous Client Examples

# --------------------------------------------------------------------------- #
# import the various server implementations
# --------------------------------------------------------------------------- #
from pymodbus.client.sync import ModbusSerialClient as ModbusClient

# --------------------------------------------------------------------------- #
# configure the client logging
# --------------------------------------------------------------------------- #
import logging
FORMAT = ('%(asctime)-15s %(threadName)-15s '
          '%(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s')
logging.basicConfig(format=FORMAT)
log = logging.getLogger()
log.setLevel(logging.DEBUG)

UNIT = 0x1

# ------------------------------------------------------------------------#
# choose the client you want
# ------------------------------------------------------------------------#
client = ModbusClient(method='rtu', port='COM20', timeout=1, baudrate=19200)
client.connect()

# ----------------------------------------------------------------------- #
# example requests
# ----------------------------------------------------------------------- #
rr = client.read_holding_registers(100, 1, unit=UNIT) #Actual chamber temperature reading
print(rr.registers[0])

# ----------------------------------------------------------------------- #
# close the client
# ----------------------------------------------------------------------- #
client.close()

You might need to change the default baudrate (according to the manual 19200) and/or the Modbus UNIT ID (UNIT 1 is the default value).

A: Hello I actually just finished using a little something in python. TestEquity chamber for the RS-232 you need to use modbus RTU protocol.
I'm using minimalmodbus. The other thing is that you need to make sure that you are using a null modem Tx and Rx need to be swapped in the DB9 connector.
Check the baudrate and slave address in setup, communications.
My code is here:
import minimalmodbus

 TE1007C = minimalmodbus.Instrument("COM5", 1)
 # Set baudrate
 TE1007C.serial.baudrate = 9600
 temp = TE1007C.read_register(100, 1, signed=True)
 print(temp)

To set a temperature use write_register(). There are other registers that can be use.


text:
Q: How to extract specific characters in characters with repeating anchor points in R using str_extract Context
I got a vector a.
a = 'TITLE     Distribution and characteristics of Beilong virus among wild
            rodents and shrews in China
     JOURNAL   Infect. Genet. Evol. 85, 104454 (2020)
       messy text
       messy text
       messy text
       messy text
     TITLE     Direct Submission
     JOURNAL   Submitted (24-FEB-2020) State Key Laboratory of Pathogen and
               Biosecurity, Beijing Institute of Microbiology and Epidemiology, 20
               Dong-Da Street, Fengtai District, Beijing 100071, China
       messy text
       messy text'

Question
I want to extract TITLE_1, JOURNAL_1, TITLE_2 and JOURNAL_2. It should like this:
TITLE_1 =  'Distribution and characteristics of Beilong virus among wild
            rodents and shrews in China'

JOURNAL_1 = 'Infect. Genet. Evol. 85, 104454 (2020)'

TITLE_2 = 'Direct Submission'

JOURNAL_2 = 'Submitted (24-FEB-2020) State Key Laboratory of Pathogen and
               Biosecurity, Beijing Institute of Microbiology and Epidemiology, 20
               Dong-Da Street, Fengtai District, Beijing 100071, China'

It's easy to extract JOURNAL_1 and TITLE_2.
JOURNAL_1 = str_extract(a, '(?<=JOURNAL   ).*')
[1] "Infect. Genet. Evol. 85, 104454 (2020)"

TITLE_2 = str_extract(a, '(?<=TITLE     ).*')
[1] "Distribution and characteristics of Beilong virus among wild"

But I don't know how to extract JOURNAL_2 and TITLE_1.
What I've done
# All failed
JOURNAL_2 = str_extract(a, regex('(?<=JOURNAL   ).*(?=messy text)', dotall = T))
[1] "Infect. Genet. Evol. 85, 104454 (2020)\n       messy text\n       messy text\n       messy text\n       messy text\n     TITLE     Direct Submission\n     JOURNAL   Submitted (24-FEB-2020) State Key Laboratory of Pathogen and\n               Biosecurity, Beijing Institute of Microbiology and Epidemiology, 20\n               Dong-Da Street, Fengtai District, Beijing 100071, China\n       messy text\n       "

TITLE_1 = str_extract(a, regex('(?<=TITLE     ).*(?=JOURNAL)', dotall = T))
[1] "Distribution and characteristics of Beilong virus among wild\n            rodents and shrews in China\n     JOURNAL   Infect. Genet. Evol. 85, 104454 (2020)\n       messy text\n       messy text\n       messy text\n       messy text\n     TITLE     Direct Submission\n     "

A: Here's a tidy approach:
library(tidyverse)
data.frame(a) %>%
  # clean up string:
  mutate(a = gsub("\\s+", " ", a)) %>%
  # separate elements of interest into rows:
  separate_rows(a, sep = "\\s(?=[A-Z]{2,})") %>%
  # split string:
  mutate(a = str_split(a, "(?<=[A-Z]{2,10})\\s", simplify = TRUE))
# A tibble: 4 × 1
  a[,1]   [,2]
  <chr>   <chr>
1 TITLE   Distribution and characteristics of Beilong virus among wild rodents and shrews in China
2 JOURNAL Infect. Genet. Evol. 85, 104454 (2020) messy text messy text messy text messy text
3 TITLE   Direct Submission
4 JOURNAL Submitted (24-FEB-2020) State Key Laboratory of Pathogen and Biosecurity, Beijing Insti…

A: This solution is a bit dirty, but it works well.
library(stringr)
a = 'TITLE     Distribution and characteristics of Beilong virus among wild
            rodents and shrews in China
     JOURNAL   Infect. Genet. Evol. 85, 104454 (2020)
       messy text
       messy text
       messy text
       messy text
     TITLE     Direct Submission
     JOURNAL   Submitted (24-FEB-2020) State Key Laboratory of Pathogen and
               Biosecurity, Beijing Institute of Microbiology and Epidemiology, 20
               Dong-Da Street, Fengtai District, Beijing 100071, China
       messy text
       messy text'

A <-
a |>
  str_split("TITLE\\s+|JOURNAL\\s+") |>
  unlist()

TITLE_1 <-
A[2] |>
  str_replace("\\n\\s*", " ") |>
  str_replace("\\n", "")

JOUNAL_1 <-
A[3] |> str_extract("(^.+)\\n") |>
  str_replace("\\n\\s*", "")

TITLE_2 <-
A[4] |>
  str_replace("\\n\\s*", "")

JOUNAL_2 <-
A[5] |>
  str_replace("\\n\\s*", " ") |>
  str_replace("\\n\\s*", " ") |>
  str_extract("^.+China")

TITLE_1
#> [1] "Distribution and characteristics of Beilong virus among wild rodents and shrews in China     "
JOUNAL_1
#> [1] "Infect. Genet. Evol. 85, 104454 (2020)"
TITLE_2
#> [1] "Direct Submission"
JOUNAL_2
#> [1] "Submitted (24-FEB-2020) State Key Laboratory of Pathogen and Biosecurity, Beijing Institute of Microbiology and Epidemiology, 20 Dong-Da Street, Fengtai District, Beijing 100071, China"

Created on 2022-09-10 with reprex v2.0.2


text:
Q: How do I cross time series in pandas? Let's say I've got a dataframe with an integer index:
pd.DataFrame([[4,5],[7,8],[9,10]],columns=['a','b'])

    a   b
0   4   5
1   7   8
2   9   10

I'd like to create a matrix of ratios for each of a cross b, for each index, so I get a series of matrices of the form:
a/a a/b
b/a b/b

for each index. Ultimately, I'll want to unfurl these into four columns.
Is there an easy way? If there's an easy numpy solution doing this, that might be better.

A: Easy way:
pd.DataFrame({f'{x}/{y}': df[x] / df[y] for x in df for y in df})

Slightly complicated way (might be faster if you have large number of columns):
a = df.values[None].T / df.values
pd.DataFrame(np.hstack(a), columns=(f'{x}/{y}' for x in df for y in df))

Result
   a/a    a/b       b/a  b/b
0  1.0  0.800  1.250000  1.0
1  1.0  0.875  1.142857  1.0
2  1.0  0.900  1.111111  1.0


text:
Q: Query between two times with mongodb First of all, sorry if my question is obvious, but i'm having some troubles to do a specific query with mongodb.
Let's assume i have a collection with the following documents :
+----+--------+---------------------+
| ID |  user  |     record_date     |
+----+--------+---------------------+
|  1 | Frank  | 2017-05-10 12:13:15 |
|  2 | Ian    | 2017-05-10 13:15:18 |
|  3 | Ian    | 2017-05-10 17:45:34 |
|  4 | Lip    | 2017-05-10 18:53:12 |
|  5 | Frank  | 2017-05-10 18:54:23 |
|  6 | Fiona  | 2017-05-10 20:12:48 |
|  7 | Debbie | 2017-05-11 05:05:12 |
|  8 | Ian    | 2017-05-11 08:17:38 |
|  9 | Debbie | 2017-05-11 08:30:57 |
| 10 | Carl   | 2017-05-11 14:17:18 |
+----+--------+---------------------+

I'm trying to get any document that have a record_date between a time interval, not a date interval : for example, all documents where the record_date time is between 17:00 and 19:00.
With postgres or mysql, this was kinda easy : i converted the date value to a number (ex for the first document : 1213) and a simple query like record_date BETWEEN(1700,1900), but i'm having troubles getting the same results with mongo.
Does anyone have an idea to do such a request ?
Thanks a lot !
Jim

A: db.times.aggregate([{"$project": {time : {"$dateToString": {format : "%H",
date : "$record_date"}}}}, {"$match" : {time: {"$gte":"17","$lte":"19"}}}])

This aggregation pipeline takes out the time part(specifically the Hour part using the format "%H") using $dateToString aggregation operator in the project phase and then uses a match phase to filter the results.
Ref - $dateToString
If you need to know more about how the aggregation pipeline works - Aggregation Pipeline

A: try this one:
db.record.aggregate([
    {
      $match:{
         $and: [
          {
            record_date: {
              $gte: "2017-05-10 17:00:00",
            },
          },
          {
            record_date: {
              $lte: "2017-05-10 19:59:59",
            },
          },
        ]
      }
    }
    ])


text:
Q: JQuery: Can I use a Dialog to open up an external web page? Can I use a JQuery Dialog to open up an external web page, and if so - how?
Essentially, I want to replicate the abilities of LightWindow using JQuery (LightWindow is based on scriptalous).
www.stickmanlabs.com/lightwindow/index.html
Ideally, I want to use something that is apart of the JQuery core. If it need to be a JQuery plug-in, that's fine but I would really like to have it be apart of the core functionality of such features already exist.

A: In JQueryUI you are using a DIV as a Dialog.
$(function() {
  $("#dialog").dialog();
});

So you can use an iframe inside DIV:

Edit:
If you want every LINK in your page to be displayed on JQueryUI Dialog here it is:
JavaScript:
$("a").click(function(event){
  event.preventDefault();
  $("#frame").attr("src", $(this).attr("href"));
  $('#dialog').dialog('open');
});

HTML:

A: Just to expand on JCasso's great answer, you can handle this all in JavaScript:
$("a").click(function (event) {
    event.preventDefault();
    var page = $(this).attr("href");
    var title = $(this).text();
    $('

')
        .html('')
        .dialog({
            autoOpen: true,
            modal: true,
            height: 800,
            width: 400,
            title: title
    });
});

Now any links on the page will be opened in inside of an iframe in a dialog box.
Working Demo in jsFiddle


text:
Q: How can I connect wires to my breadboard? I am building a couple of data acquisition fixtures. I'm locating the USB daq hardware and a breadboard inside an enclosure with panel mount sockets for the external connections. Nice and clean, nothing fancy.
I had originally planned on using through hole screw terminal blocks in the breadboard to make the connections between the panel mount connectors and the data acquisition hardware.

There are some voltage dividers and other small circuits that I planned to implement on the breadboard. So the idea is:

*

*I would go from enclosure mounted connectors (e.g. 2mm pin female socket)

*Solder wire to the connector and connect the other end to the breadboard

*Implement basic circuitry in breadboard

*connect wires from breadboard to DAQ (DAQ hardware has screw terminal blocks for connections)

I've run into a snag where the 3.8mm leads on the terminal block aren't long enough to properly seat in the breadboard. Now I'm trying to decide how I can easily workaround this with another design, here is what I've thought of:

*

*Basic headers and plugs (the crimp on type that take a ribbon cable, usually)

*Header and solder wires to the header pins

*Wire wrap to something (never done it)

I'd like to avoid purchasing special tools to crimp specialized molex tpye connectors. I'm looking for a solution that will let me easily "hook up" my panel connections to my breadboard and disconnect them when I need to make changes or service something.
I'm asking the community here if you have any tricks or other suggestions?

A: I will listen to the wisdom in the comments and NOT plan on using the breadboard in production, small as it may be. I will use a breadboard for experimentation but will use a PCB in the actual enclosure.
I'm not sure if Answering my own question is the right way to handle this, but I wanted to wrap it up and share my change of heart. If there is a better way to handle a basically invalid question, please share.


text:
Q: Bounding box coordinates and strange WMS behavior I'm having trouble with using OpenLayers to render a GeoServer WMS layer.
I have searched about it on the internet but have found no workaround yet.
I intend to provide as much as I know on this issue, that's why my post is quite long!
I am trying to render a shp layer which is located inside a donnees_validees workspace (in GeoServer). I am using a 1.1.0 version for Web Map Service (WMS). I can reach this layer on GeoServer; the SRC is "EPSG:3857" :

And it looks like this :

This is the URL used by GeoServer to access it:
http://localhost:8080/geoserver/donnees_validees/wms?
service=WMS&
version=1.1.0&
request=GetMap&
layers=donnees_validees%3Ashp&
bbox=4.7153439%2C44.6334029%2C5.1199732%2C45.6618753&
width=330&
height=768&
srs=EPSG%3A3857&
format=application/openlayers

It tells us the bounding box is the following:
4.7153439,44.6334029,5.1199732,45.6618753
My problem is that when using OpenLayers (v3) library to render that, I'm getting nothing on my screen even though the page have been reached. It might come from a wrong view initialization, but I'm not sure.

On top of that, my request has been modified meanwhile; it now turned to:

http://localhost:8080/geoserver/donnees_validees/wms?SERVICE=WMS&VERSION=1.1.0&REQUEST=GetMap&FORMAT=image%2Fpng8&TRANSPARENT=true&LAYERS=donnees_validees%3Ashp&SRS=EPSG%3A3857&BBOX=-21846.05200578905%2C-21805.38973278905%2C21855.544965789053%2C21896.20723878905&STYLES=&FORMAT_OPTIONS=dpi%3A81&WIDTH=1&HEIGHT=1

You can notice my bounding box parameter turned to:
-21846.05200578905,-21805.38973278905,21855.544965789053,21896.20723878905.
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import {Image as ImageLayer, Tile as TileLayer} from 'ol/layer.js';
import ImageWMS from 'ol/source/ImageWMS.js';
import OSM from 'ol/source/OSM.js';

var mysource = new ImageWMS
({
  url: 'http://localhost:8080/geoserver/donnees_validees/wms',
  params: {'VERSION': '1.1.0',
             'LAYERS': 'donnees_validees:shp',
             'SRS': 'EPSG:3857',
             'FORMAT': 'image/png8',
             'BBOX':'4.713221,45.393568,4.779739,45.423938'
             },
            serverType: 'geoserver',
});

var layerlist = [ myUpperLayer ];
var myview = new View
({
    center: [4.55, 45.4009],
    zoom: 2
});

var map = new Map
({
  layers: layerlist,
  target: 'map',
  view: myview
});

In my case, trying to force the weight and height arguments (which have changed as well) didn't work out.
I can't tell why has my bbox parameter changed but I would like to keep the bounding box with the same SRC I have given in the imageWMS constructor.
Does someone have a clue about that?
Is it the cause of my blank screen?

After reviewing answers from Ian Turton♦, and Mike, I have put back the good CRS in the Geoserver Interface.
I have also tweaked my code to set up a projection in my view.
I tried to set the projection as 'EPSG:4326' in my ImageWMS but it resulted in a suspicious request
http://localhost:8080/geoserver/donnees_validees/wms?SERVICE=WMS&VERSION=1.1.0&REQUEST=GetMap&FORMAT=image%2Fpng8&TRANSPARENT=true&LAYERS=donnees_validees%3Ashp&SRS=EPSG%3A4326&STYLES=&FORMAT_OPTIONS=dpi%3A81&WIDTH=1&HEIGHT=1&BBOX=-0.1962464241397277%2C-0.1958811487264987%2C0.19633170085032303%2C0.19669697626355204
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import {Image as ImageLayer, Tile as TileLayer} from 'ol/layer.js';
import ImageWMS from 'ol/source/ImageWMS.js';
import OSM from 'ol/source/OSM.js';

var myextent =  [4.713221,45.393568,4.779739,45.423938]; //  bbox
var mycenter =[(myextent[0] + myextent[2])/2 ,(myextent[1] + myextent[3])/2]; // center (x;y)

var mysource = new ImageWMS
({
  url: 'http://localhost:8080/geoserver/donnees_validees/wms',
  params: {
            'VERSION': '1.1.0',
            'LAYERS': 'donnees_validees:shp'
          },
  serverType: 'geoserver'
});

var myUpperLayer = new ImageLayer
({
  extent: myextent, // REMOVING THIS LINE DID THE TRICK !
  source: mysource
});

var layerlist = [myUpperLayer ];

var myview = new View
({
    projection: 'EPSG:4326',
    center: [4.73, 45.408],
    zoom: 2
});

var map = new Map
({
  layers: layerlist,
  target: 'map',
  view: myview
});

The request is now : http://localhost:8080/geoserver/donnees_validees/wms?SERVICE=WMS&VERSION=1.1.0&REQUEST=GetMap&FORMAT=image/png8&TRANSPARENT=true&LAYERS=donnees_validees:shp&SRS=EPSG:4326&STYLES=&FORMAT_OPTIONS=dpi:81&WIDTH=1&HEIGHT=1&BBOX=4.5501909375,45.212463937500004,4.9427690625,45.605042062500004
I end up with a bbox quite close from the "myextent" variable, which seems fine !
I still have this blank page problem .. Perhaps it's a css problem. Mine is currently embedded into the html page of my app :
(edited)
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title> My title</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" type="text/css"> -
  </head>
  <body>
    <div id="map" style="height:400px; width:600px;">
    <script src="./index.js"></script>
  </body>
</html>

I am now sure the problem is related to the CSS.
I've added  this line since :

If I manually enter a "png " request with decent parameters for width and height.. ( http://localhost:8080/geoserver/donnees_validees/wms?SERVICE=WMS&VERSION=1.1.0&REQUEST=GetMap&FORMAT=image%2Fpng8&TRANSPARENT=true&LAYERS=donnees_validees%3Ashp&SRS=EPSG%3A4326&STYLES=&FORMAT_OPTIONS=dpi%3A27&WIDTH=500&HEIGHT=500&BBOX=4.1605425%2C44.822815500000004%2C5.3324175%2C45.994690500000004 ) .. I get a nice image .. But something is going wrong with width and height when I go through OL. (cf commentary)

A: Your data is in lat/lon (EPSG:4326) not Web mercator(EPSG:3857). Try not to lie to GeoServer about projections as it will believe you and it won't work.


text:
Q: how restart java process in linux form batch file? I want to restart process in linux server.
I use loop for kill and start process.
!/bin/bash

pgrep -f java | while read x;
do
    addr= pwdx x | awk '{print $2}'
    echo "$addr"
    kill -9 $x
    nohup sh $addr/start.sh >/dev/null 2>&1
done

I store address in a veriable.Then i kill that process and use nohup for start that process.
But process not start.
I think this line is wrong.
nohup sh $addr/start.sh >/dev/null 2>&1

A: I see few errors in the script. Line:
!/bin/bash

must be
#!/bin/bash

the assignment to addr variable is wrong. Instead of this
addr= pwdx x | awk '{print $2}'

it must be
addr=$(pwdx x | awk '{print $2}')

Also its wise to redirect STDOUT to file, not to /dev/null as this can help debugging and monitoring the app. And you forget to put this in background
nohup sh $addr/start.sh >/path/to/standard.log 2>/path/to/error.log &


text:
Q: amazon-dynamodb and filtering by date I have a dynamodb table which has a GlobalSecondaryIndex with a date field as attribute of keytype "range". Values are stored in ISO-format "YYYY-MM-DD".
I want to access in node only records with dates greater than a certain date.
It seems to work with a parameter for my query:
KeyConditionExpression: 'myDate >= :myDate',
ExpressionAttributeValues: {
    ':myDate': '2017-11-17'
}

However I do not quite understand. The date is technically speaking a string. Is it reliable to trust the string comparison or should it be done in a different way?

A: Yes, you can relay on this as long as the date is stored in YYYY-MM-DD format.
DynamoDB doesn't have a separate data type for Date. Date can be stored either as String or Number.
Date    S (string type). The Date values are stored as ISO-8601 formatted strings.

Storing date as String:-

You can use the string data type to represent a date or a time stamp.
  One way to do this is by using ISO 8601 strings, as shown in these
  examples:

*

*2016-02-15

*2015-12-21T17:42:34Z

*20150311T122706Z
Storing date as Number:-

You can use the number data type to represent a date or a time stamp.
  One way to do this is by using epoch time—the number of seconds since
  00:00:00 UTC on 1 January 1970. For example, the epoch time 1437136300
  represents 12:31:40 UTC on 17 July 2015.

Data types


text:
Q: Proving the group of homomorphisms is isomorphic to matrices I'm trying to understand this theorem:
If $f, g: R^n \to R^m$ are given by the matrices $A, B \in R_{m,n}$ then $f + g$ is given by $A + B$. Thus, $\operatorname{Hom}_R (R^n, R^m)$ and $R_{m,n}$ are isomorphic as additive groups. If $R$ is commutative, they are isomorphic as $R$-modules.
How would I go about proving it? I know the last bit follows from observing that $x+x=x*2$, so we can say they are $\mathbb Z$-modules. I'm not sure about the rest though.

A: Let $e_j = (0,\dots,1,\dots,0) \in R^n$ be the standard generators of $R^n$ as a free $R$ module, for $j = 1, \dots, n$. Similarly, let $f_i$ be the standard generators of $R^m$. Then any homomorphism of $R$-modules $f: R^n \rightarrow R^m$ gives a matrix $A_f = (a_{ij}) \in R_{m,n}$, where $f(e_j) = \Sigma_{1 \leq i \leq m} a_{ij}f_i$. If $g \in Hom_R(R^n, R^m)$ with matrix $B_g = (b_{ij})$, then for all $j = 1, \dots n$, $f + g (e_j)$ $= f(e_j) + g(e_j)$ $= \Sigma_{1 \leq i \leq m} (a_{ij} + b_{ij})f_i$. Thus, the matrix of $f + g$ is $(a_{ij} + b_{ij}) = A_f + B_g$.
Now define $\varphi: Hom_R(R^n,R^m) \rightarrow R_{m,n}$ as follows: $\varphi(f) = A_f$, where $A_f$ is as above. Then what we showed above is that $\varphi$ is a group homomorphism. Now, given a matrix in $R_{m,n}$ can you define a linear map $R^n \rightarrow R^m$. Can you then define a map $R_{m,n} \rightarrow  Hom_R(R^n,R^m)$ which is an inverse of $\varphi$? This will show that $\varphi$ is an isomorphism.
Verify that if $f \in Hom_R(R^n,R^m)$, then for any $r \in R$, the matrix of $rf$ is just $rA_f$. This shows that $\varphi$ is also an $R$-linear map.


text:
Q: Gradle build - works from sub-project, not from root project I have a set of gradle projects that are all sub-projects of another "master" project. I'm trying to reproduce with a small example, but have been unable to do so, and I'm turning here for help.
Here's the problem in a nutshell:
I have about 10 projects, but let's call the interesting ones "master", "lib", "end_point" where "end_point" has a dependency on "lib"

*

*If I go to the end_point directory and do "gradle clean build" everything is fine

*If I go to the master directory and do "gradle clean build" the "end_point" project fails to build because it can't find a symbol that was defined in the "lib" project

I appreciate that that's not a lot of detail, but we've been looking at it for some time and we have run out of possible ideas for next things to look at.
Omitting the "clean" from the build does not help. The error happens during the compileJava step. It's gradle 2.14.1. Both lib and end_point have the org.springframework.boot plugin applied.
Any suggestions would be greatly appreciated.

A: This is a known issue/feature with the spring boot plugin.
https://github.com/spring-projects/spring-boot/issues/6572


text:
Q: Fetch all relationship data - Core Data I am new to core data. I am fetching data from API and then saving them to core data.This is my dataModel.

Here is my API Structure,
{
"name" : "name here",
"content" :[
{
    "homeContentItems" : [
    {
         "some objects" : "values",
         "contentItemDetails": [
          {
          },
          {
          }
         ]
    },
    {
         "some objects" : "values",
         "contentItemDetails": [
          {
          },
          {
          }
         ]
    }

  ]
},
{
    "homeContentItems" : [
    {
         "some objects" : "values",
         "contentItemDetails": [
          {
          },
          {
          }
         ]
    },
    {
         "some objects" : "values",
         "contentItemDetails": [
          {
          },
          {
          }
         ]
    }

  ]
}

]
}

How can I fetch data from the Entity so I can get all data from related entity too?
I Have never worked with database before so its bit complected for me. Any help will be much appreciated.
let informedDataFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Informed360Entity")
    informedDataFetch.fetchLimit = 1
    informedDataFetch.predicate = NSPredicate()
    let tableviewData = try! context.fetch(informedDataFetch)

    let tdata : Informed360Entity = tableviewData.first as! Informed360Entity
    var contentData = tdata.toContent?.allObjects as? [ContentEntity]

I tried this code and getting data from ContentEntity table. How can I get other 2 tables data too so I can use to display in tableview.

A: You do it the same way as you did with ContentEntity but now you use the two properties that represent the relationships, contentDetailItem and homeContentItems, which both will return a Set.
 for content in contentData {
     let contentDetailItems = content.contentDetailItem
     let homeContents = content.homeContentItems
     //...
 }


text:
Q: IOS trigger location permission popup I have implemented geo location functionality in my application.
App first release, We have got permission "access location while using"
But we need to ask again permission popup to change the location permission to Always
Is possible in we provide the update version of app???
Otherwise if permission popup show only once.

A: First app's Info.plist must contain both NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription keys with string values explaining to the user how the app uses this data.
Now just replace your line of code
locationManager.requestWhenInUseAuthorization()

with this
locationManager.requestAlwaysAuthorization()

It will again ask for permission as shown below...

Hope this will help you. :)


text:
Q: Howto: Adding custom made library to CMakeLists.txt in another project I want to include the software for a video device to my docker-project.
The camera-software is a SDK (https://thermalcapture.com/software-sdk-thermalcapture-grabber-usb/) that I built with make + cmake.
I append the CMakeLists.txt from that SDK here:
set( CMAKE_BUILD_TYPE RelWithDebInfo )
set( CMAKE_CXX_FLAGS "-std=c++11" )
#set( CMAKE_CXX_FLAGS "-fpermissive -std=c++11" )
set( CMAKE_VERBOSE_MAKEFILE on )
set( TARGET thermalgrabber )
set( ROOT ./ )
set( LIBRARY_OUTPUT_PATH ${CMAKE_CURRENT_SOURCE_DIR}/lib )

set( TEAXLIB_VERSION_MAJOR 1 )
set( TEAXLIB_VERSION_MINOR 2 )
set( TEAXLIB_VERSION_PATCH 0 )
set( TEAXLIB_VERSION_STRING ${TEAXLIB_VERSION_MAJOR}.${TEAXLIB_VERSION_MINOR}.${TEAXLIB_VERSION_PATCH} )

#set(USE_FTDI_LIB 1)

cmake_minimum_required(VERSION 2.8)

if (WIN32)

    MESSAGE("Setup for windows")

    if (USE_FTDI_LIB)

        MESSAGE("Using ftdi lib")
        ADD_DEFINITIONS(-DUSE_FTDI)

        include_directories (
            ${CMAKE_CURRENT_SOURCE_DIR}/src/inc
        )

        link_directories (
            ${CMAKE_CURRENT_SOURCE_DIR}/src/lib/ftdi_i386
        )

        link_libraries (
            ftd2xx
        )

    elseif (NOT USE_FTDI_LIB)

        MESSAGE("Using libusb")

        include_directories (
            ${CMAKE_CURRENT_SOURCE_DIR}/src/inc
        )

        link_directories (
            ${CMAKE_CURRENT_SOURCE_DIR}/src/lib/MingGW32/dll
        )

        link_libraries (
            libusb-1.0
        )

    endif(USE_FTDI_LIB)

elseif (NOT WIN32)

    MESSAGE("Setup for linux")

    if (USE_FTDI_LIB)

        MESSAGE("Not implemented")

    elseif (NOT USE_FTDI_LIB)

        MESSAGE("Using libusb")

        include_directories (
            /usr/include/libusb-1.0
            /usr/local/include/libusb-1.0

        )

        link_directories (
            /usr/lib/x86_64-linux-gnu
            /usr/local/lib
        )

        link_libraries (
            usb-1.0
        )

    endif (USE_FTDI_LIB)

endif(WIN32)

#unix:CONFIG(release, debug|release): LIBS += -L/usr/include/libusb-1.0 -lusb-1.0

set( SOURCES

    ${CMAKE_CURRENT_SOURCE_DIR}/src/thermalgrabber.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/inc/thermalgrabber.h

    ${CMAKE_CURRENT_SOURCE_DIR}/src/thermograbber.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/thermograbber.h

    ${CMAKE_CURRENT_SOURCE_DIR}/src/tauinterface.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/tauinterface.h

    ${CMAKE_CURRENT_SOURCE_DIR}/src/tauimagedecoder.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/tauimagedecoder.h

    ${CMAKE_CURRENT_SOURCE_DIR}/src/taucom.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/taucom.h

    ${CMAKE_CURRENT_SOURCE_DIR}/src/fastftdi.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/fastftdi.h

    ${CMAKE_CURRENT_SOURCE_DIR}/src/crc.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/crc.h
)

include_directories (
    ${ROOT}
    ${THERMALGRABBER}
    ${CMAKE_CURRENT_BINARY_DIR}
    ${CMAKE_CURRENT_SOURCE_DIR}/inc # public header
    ${CMAKE_CURRENT_SOURCE_DIR}/src # internal headers
)

link_directories (
    ${CMAKE_CURRENT_SOURCE_DIR}/lib
    ${CMAKE_CURRENT_SOURCE_DIR}/src/lib
    #${CMAKE_CURRENT_SOURCE_DIR}/src/lib/ftdi_i386
)

add_library( ${TARGET} SHARED ${SOURCES} )
set_target_properties( ${TARGET} PROPERTIES VERSION ${TEAXLIB_VERSION_STRING} SOVERSION ${TEAXLIB_VERSION_MAJOR} )
install( TARGETS ${TARGET} DESTINATION ${CMAKE_SOURCE_DIR}/lib )

target_link_libraries(
    ${TARGET}
    pthread
)

As far as I know this projects add a library to my system (ubuntu 20.04 on a jetson Xavier NX) via add_library( ${TARGET} SHARED ${SOURCES} ). This one is named thermalgrabber as in the header part of the CMakeLists.txt.
Now I want to include this library to my project. The current CMakeLists.txt is as following:
cmake_minimum_required(VERSION 3.6)
project(socket_connection)

set(CMAKE_CXX_STANDARD 17)

add_executable(socket_connection)

find_package(PkgConfig)
pkg_check_modules(GSTREAMER REQUIRED gstreamer-1.0)

find_package(OpenCV REQUIRED)
find_package(PkgConfig REQUIRED)
find_package(Threads REQUIRED)

pkg_check_modules(gstreamer REQUIRED IMPORTED_TARGET gstreamer-1.0)

target_compile_options(socket_connection PUBLIC "$<$<CONFIG:DEBUG>:-g>")

include_directories(socket_connection
                    ${OpenCV_INCLUDE_DIRS}
                    ${GSTREAMER_INCLUDE_DIRS}
)

target_sources(socket_connection
    PRIVATE
        src/main.cpp
        src/tcpSocket.cpp
        src/extern/toraw_fileCollector.cpp
)
target_link_libraries(socket_connection
    PRIVATE
        thermalgrabber
        ${OpenCV_LIBS}
        ${GSTREAMER_LIBRARIES}
        Threads::Threads
    )

I inherited this project and the file and it is working without the thermalgrabber. I tried adding the $TARGET in the target_link_libraries with the actual name. But I feel like I am missing something as the current error states:
fatal error: thermalgrabber.h: No such file or directory
   15 | #include "thermalgrabber.h"

This header-file being used to actual get hold of the camera is not found. So my link seems to be false.
I also tried adding it with find_library and add_library:
set( TCGLib thermalgrabber )
find_library(${TCGLib}
    NAMES
        thermalgrabber
        libthermalgrabber
    PATHS
        /home/xavier/TCG_SDK_2018_02_04/libthermalgrabber/lib
    )
add_library(${TCGLib} STATIC IMPORTED)

target_link_libraries(socket_connection
    PRIVATE
        ${OpenCV_LIBS}
        ${GSTREAMER_LIBRARIES}
        Threads::Threads
        ${TCGLib}
    )

I can launch the camera with gst-launch-1.0 v4l2src device/dev/video0 ! some more stuff
After LD_PRELOAD=../libthermalgrabber/lib/libthermgrabber.so ./TCGrabberUSBV4l2d /dev/video0.
So the lib itself is working with the running example.
Any help in succesfully including said library is very much appreciated.


text: Q: Как реализовать в приложении сначала загрузку данных с сервера, а затем обращение к базе данных? У меня приложение сначала обращается к серверу, берет оттуда данные. А затем нужно сравнить эти данные с данными из БД. Но происходит так, что приложение начинает сравнивать данные до того, как они пришли с сервера, и выходит ошибка NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference. Как сделать так, чтобы все было по порядку(сначала запрос на сервер, а затем обращение к БД)?


text:
Q: how to place text and a tabbed navigation next to each other I have written a text inside h2 and next to that i want to show a tabbed navigation but that tabbed navugation is not being placed next to it ,its going below h2 as shown in following image inside that gray box:

Following is my code for html page:

     Corporate
     jobpost

              Your Jobposts

              Other Jobposts

              Applied for

header is the thing which is in gray color in the image.Inside this header i want to show text ,next to that tabbed navigation and at the corner that button

Following is my CSS for this tabbed navigation:
#tabjob
{
  padding-top:0px;
  padding-left:10px;
    height:0px;

}

.innertab
{
    background-color: rgba(142, 194, 218, 0.3);display: block;height: 25px;
    line-height: 30px;text-align: center;
    width: auto;float: left;font-weight: bold;
    padding-left: 8px;
    padding-right: 8px;

  text-shadow: #eee 0px 0px 2px;
}
#tabjob ul li
{
 display:block;
}

A: I have already posted the answer in comments just adding the details of the answer here.
DEMO is HERE
since your h2 tag and all heading tags are block element in HTML it take the complete width available.
so to avoid h2 tag to take complete width just add {float:left} to this element
Make sure you apply this style to specific h2  only otherwise your HTML will mess up. is you have used more than one h2 tags on the page.
HTML

Corporate jobpost

                Your Jobposts

                Other Jobposts

                Applied for

CSS
#tabjob
{
  padding-top:0px;
  padding-left:10px;
    height:0px;
}

.innertab
{
    background-color: rgba(142, 194, 218, 0.3);display: block;height: 25px;
    line-height: 30px;text-align: center;
    width: auto;float: left;font-weight: bold;
    padding-left: 8px;
    padding-right: 8px;

  text-shadow: #eee 0px 0px 2px;
}
#tabjob ul li
{
 display:block;
}

h2.floatTag{float:left;}

A: Use display:inline-block for both the h2 and the tabjob:
h2, #tabjob { display: inline-block }

Demo: http://dabblet.com/gist/2774902

A: ul and div are block elements which means they always go below whatever is before them:
 a
x

would give you two lines. Try
 a
x


text:
Q: How are min and max of cumulative variables assigned? I created a routing problem and added some dimension to it. A solution assignment is found and I want to know the cumulative value at each index. I noticed that the CumulVar of an assignment does not only have a Value method but also Min and Max methods. Apparently the cumulative variables are implemented in such a way that they can represent intervals. I can see how setting

*

*slack_max>0

*fix_start_cumul_to_zero=False
introduces an ambiguity for the cumulative variables as their is a choice in how to start and how much slack to add at each stop. But
Question: How are the Min and Max at each index computed?

A: You can get the Min and Max range of a given node index from solution.Min(dimension.Cumulvar(index))
Note you'll get Min and Max exactly the same when slack_max=0 unless you know something I don't ;)
Assuming you are using an output solution object solution and a time dimension time_dimension, this will store em as a dict with min-max tuples, you may wish to adapt the output format however you wish:
time_dict = {}
for vehicle_id in range(num_vehicles):
  vehicle_time_dict={}
  index = routing.Start(vehicle_id)
  start_time = solution.Min(time_dimension.CumulVar(index))
  vehicle_time_dict[index]=(index_min,index_max)
  while not routing.isEnd(index):
    previous_index = index
    index = solution.Value(routing.NextVar(index))
    index_min = solution.Min(time_dimension.CumulVar(index))
    index_max = solution.Max(time_dimension.CumulVar(index))
    vehicle_time_dict[index]=(index_min,index_max)
  time_dict[vehicle_id]=vehicle_time_dict

routing.IsEnd(index) returns True if it's the last index of that vehicle's route (or anywhere after the last index, so if it's 10 nodes long:

*

*routing.IsEnd(8) will return False,

*routing.IsEnd(9) will return True,

*routing.IsEnd(10) will also return True, etc)


text:
Q: access json data using swig-template {
"_id": "1",
"style": "13123",
"category": "dress",
"colors": {
    "Black": {
        "prestock": 50,
        "instock": 60,
        "inactive": 0
    },
    "Blue": {
        "prestock": 30,
        "instock": 0,
        "inactive": 0
    },
    "Red": {
        "prestock": 10,
        "instock": 60,
        "inactive": 0
    }
  }
}

i'm using swig-template to access 'colors' object
i need to express each color in this list-format:

*Black

*Blue

*Red
how can i access this json?
ps. i tried other ways but no luck,
what i have is {{style_list.colors|sort}} which gives me like this:
Black, Blue, Red

A: Use the built-in JavaScript method Object.keys

{% for color in Object.keys(colors) %}

{{ color }}

{% endfor %}


text:
Q: Seeing unexpected behavior with async and retry spring boot I have a use case to call multiple REST APIS in parallel. But catch here is, they need an access token to be passed in header of each request. So, I ended up making this class level variable. There's also retry to happen in case of timeout or expired token. In case of expired token, we call loadToken() method to get new token and retry the same call. we have a max retries of 3 times.
Issue:

*

*One issue I see is loadToken() can be called by multiple threads at same time and there could be a race condition here.

*In prd, I am seeing very weird behaviour. Even for 500 errors, the retry is kicking loadToken() method which should not happen. Only loadToken() should trigger in case of expired token.

Any thoughts/ suggestions here to improve this code. Thanks for any help.
Code looks like this:
@Component
public class MyDaoImpl implements MyDao {

    @Autowired
    private RestTemplate restTemplate;

    private String token;

    @PostConstruct
    public void loadToken() throws CustomException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        try {
            ResponseEntity<TokenResponse> exchange = restTemplate.exchange(tokenUrl, HttpMethod.POST, request, TokenResponse.class);
            token = exchange.getBody()!=null && StringUtils.isNotBlank(exchange.getBody().getToken()) ? exchange.getBody().getToken() : null;
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    @Async("threadPoolExecutor")
    @Retryable(maxAttemptsExpression = "#{${retry.max.attempts:3}}", value = {UnAuthorizedException.class, GatewayTimeoutException.class}, backoff = @Backoff(delayExpression = "#{${retry.backoff.period:1000}}"))
    public CompletableFuture<String> getResponse1(String string) throws CustomException {
        HttpHeaders headers = new HttpHeaders();
        headers.setBearerAuth(getAccessToken());
        HttpEntity<String> request = new HttpEntity<>(headers);
        try {
            ResponseEntity<byte[]> exchange = restTemplate.exchange(url, HttpMethod.GET, request, byte[].class);
            if(exchange.getBody()==null) return CompletableFuture.completedFuture(null);
            return CompletableFuture.completedFuture(Base64.getEncoder().encodeToString(exchange.getBody()));
        } catch (HttpClientErrorException | HttpServerErrorException e) {
            if(e.getStatusCode()==HttpStatus.UNAUTHORIZED) {
                loadToken();
                throw new UnAuthorizedException("Expired Token", e);
            }
        } catch (Exception e) {
            if(StringUtils.isNotEmpty(e.getMessage()) && (e.getMessage().contains("I/O error on ") || e.getMessage().contains("timeout"))) {
                throw new GatewayTimeoutException("Gateway_Timeout", e);
            }
        }
        return CompletableFuture.completedFuture(null);
    }

    @Override
    @Async("threadPoolExecutor")
    @Retryable(maxAttemptsExpression = "#{${retry.max.attempts:3}}", value = {UnAuthorizedException.class, GatewayTimeoutException.class}, backoff = @Backoff(delayExpression = "#{${retry.backoff.period:1000}}"))
    public CompletableFuture<SomeResponse> getResponse2(String string) throws CustomException {
        HttpHeaders headers = new HttpHeaders();
        headers.setBearerAuth(getAccessToken());
        HttpEntity<String> request = new HttpEntity<>(headers);
        try {
            final ResponseEntity<Response> exchange = restTemplate.exchange(someurl, HttpMethod.GET, request, Response.class);
            return CompletableFuture.completedFuture(exchange.getBody());
        } catch (HttpClientErrorException | HttpServerErrorException e) {
            if(e.getStatusCode()==HttpStatus.UNAUTHORIZED) {
                loadToken();
                throw new UnAuthorizedException("Expired Token", e);
            }
        } catch (Exception e) {
            if(StringUtils.isNotEmpty(e.getMessage()) && (e.getMessage().contains("I/O error on ") || e.getMessage().contains("timeout"))) {
                throw new GatewayTimeoutException("Gateway_Timeout", e);
            }
        }
        return CompletableFuture.completedFuture(null);
    }

    @Override
    public String getAccessToken() throws JbException {
        if(StringUtils.isBlank(token)) {
            loadToken();
        }
        return token;
    }

    @Override
    @Async("threadPoolExecutor")
    @Retryable(maxAttemptsExpression = "#{${retry.max.attempts:3}}", value = {UnAuthorizedException.class, GatewayTimeoutException.class}, backoff = @Backoff(delayExpression = "#{${retry.backoff.period:1000}}"))
    public CompletableFuture<List<Response3>> getResponse3(String string) throws CustomException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(getAccessToken());
        HttpEntity<String> request = new HttpEntity<>("{}", headers);
        try {
            ResponseEntity<List<CobrandCard>> exchange = restTemplate.exchange(someUrl2, HttpMethod.POST, request, new ParameterizedTypeReference<List<Response3>>() {});
            return CompletableFuture.completedFuture(exchange.getBody());
        } catch (HttpClientErrorException | HttpServerErrorException e) {
            if(e.getStatusCode()==HttpStatus.UNAUTHORIZED) {
                loadToken();
                throw new UnAuthorizedException("Expired Token", e);
            }
        } catch (Exception e) {
            if(StringUtils.isNotEmpty(e.getMessage()) && (e.getMessage().contains("I/O error on ") || e.getMessage().contains("timeout"))) {
                throw new GatewayTimeoutException("Gateway_Timeout", e);
            }
        }
        return CompletableFuture.completedFuture(null);
    }

    @Override
    @Async("threadPoolExecutor")
    @Retryable(maxAttemptsExpression = "#{${retry.max.attempts:3}}", value = {UnAuthorizedException.class, GatewayTimeoutException.class}, backoff = @Backoff(delayExpression = "#{${retry.backoff.period:1000}}"))
    public CompletableFuture<List<Response4>> getTier(String string) throws CustomException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(getAccessToken());
        HttpEntity<String> request = new HttpEntity<>(headers);
        try {
            ResponseEntity<List<Response4>> exchange = restTemplate.exchange(finalUrl, HttpMethod.GET, request, new ParameterizedTypeReference<List<Response4>>() {});
            return CompletableFuture.completedFuture(exchange.getBody());
        } catch (HttpClientErrorException | HttpServerErrorException e) {
            if(e.getStatusCode()==HttpStatus.UNAUTHORIZED) {
                loadToken();
                throw new UnAuthorizedException("Expired Token", e);
            }
        } catch (Exception e) {
            if(StringUtils.isNotEmpty(e.getMessage()) && (e.getMessage().contains("I/O error on ") || e.getMessage().contains("timeout"))) {
                throw new GatewayTimeoutException("Gateway_Timeout", e);
            }
        }
        return CompletableFuture.completedFuture(null);
    }

}


text:
Q: Creating a view between two tables in SQL I'm having trouble creating a view between two tables, as I'm quite new to SQL. I need to create a view which will show which employees have carried out work as consultants within the past 14 days. The result of the view should also display this kind of layout:
14 day consultancy report
-----------------------------------------------
Employee Helvin Paul worked for 6 hours for factory ltd chargeable £351

The two tables I assume you will need to join together are the Employee table and also the Consultancy table. I will show both below as I have them in a text file from when I was creating these tables:
create table Funtom_employee
(
    emp_ID      Number(3)  primary key,
    Emp_firstname   varchar2(50) not null,
    Emp_surname varchar2(50),
    Emp_department  Number(2) constraint FK_funtom_dept references
    funtom_department,
    emp_street  varchar2(50),
    emp_town    varchar2(50),
    emp_district    varchar2(50),
    Emp_grade   Number(3) default 4 constraint chk_emp_grd check (Emp_grade between 1 and 9),
    Emp_site    varchar2(30) default 'LONDON',

    constraint  FK_funtom_grade funtom_grade references funtom_department
);

create table Funtom_consultancy
(
    consultancy_ID  Number(3) primary key,
    Consultancy_emp Number(3) constraint cns_emp references funtom_employee,
    Consultancy_hours   Number(4,2) constraint consultancy_check check (Consultancy_hours > 1),
    Consultancy_client  Number(3) references funtom_customer,
    Consultancy_date    DATE,
    Consultancy_activity    Number(3) references funtom_activity
);

Thanks to anyone that can help with this create view and for your time

A: A view can be created using the CREATE VIEW statement. An example based on your data is listed below.
CREATE VIEW consultancy_report as
select
    Funtom_employee.Emp_firstname,
    Funtom_consultancy.Consultancy_date,
from
    Funtom_employee
    join Funtom_consultancy
        on Funtom_employee.emp_id = Funtom_consultancy.Consultancy_emp

You can add whatever other fields you need from either table in the select clause of the query. I've demonstrated one field from both tables.
If you want output explicitly as listed in your sample, you will need to concatenate several fields together as one string. Since this feels like a homework question, I will leave that as an exercise for you.


text:
Q: Iterate dataframe column Array of Array in Spark Scala I am trying to iterate over an array of array as a column in Spark dataframe. Looking for the best way to do this.
Schema:
root
 |-- Animal: struct (nullable = true)
 |    |-- Species: array (nullable = true)
 |    |    |-- element: struct (containsNull = true)
 |    |    |    |-- mammal: array (nullable = true)
 |    |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |    |-- description: string (nullable = true)

Currently I am using this logic. This only gets the first array.
df.select(
   col("Animal.Species").getItem(0).getItem("mammal").getItem("description")
)

Pseudo Logic:
col("Animal.Species").getItem(0).getItem("mammal").getItem("description")
+
col("Animal.Species").getItem(1).getItem("mammal").getItem("description")
+
col("Animal.Species").getItem(2).getItem("mammal").getItem("description")
+
col("Animal.Species").getItem(...).getItem("mammal").getItem("description")

Desired Example Output (flattened elements as string)
llama, sheep, rabbit, hare

A: You can apply explode two times: first time on Animal.Species and second time on the result of the first time:
import org.apache.spark.sql.functions._
df.withColumn("tmp", explode(col("Animal.Species")))
  .withColumn("tmp", explode(col("tmp.mammal")))
  .select("tmp.description")
  .show()

A: Not obvious, but you can use . (or the getField method of Column) to select "through" arrays of structs. Selecting Animal.Species.mammal returns an array of array of the innermost structs. Unfortunately, this array of array prevents you from being able to drill further down with something like Animal.Species.mammal.description, so you need to flatten it first, then use getField().
If I understand your schema correctly, the following JSON should be a valid input:
{
  "Animal": {
    "Species": [
      {
        "mammal": [
          { "description": "llama" },
          { "description": "sheep" }
        ]
      },
      {
        "mammal": [
          { "description": "rabbit" },
          { "description": "hare" }
        ]
      }
    ]
  }
}

val df = spark.read.json("data.json")
df.printSchema
// root
//  |-- Animal: struct (nullable = true)
//  |    |-- Species: array (nullable = true)
//  |    |    |-- element: struct (containsNull = true)
//  |    |    |    |-- mammal: array (nullable = true)
//  |    |    |    |    |-- element: struct (containsNull = true)
//  |    |    |    |    |    |-- description: string (nullable = true)

df.select("Animal.Species.mammal").show(false)
// +----------------------------------------+
// |mammal                                  |
// +----------------------------------------+
// |[[{llama}, {sheep}], [{rabbit}, {hare}]]|
// +----------------------------------------+

df.select(flatten(col("Animal.Species.mammal"))).show(false)
// +------------------------------------+
// |flatten(Animal.Species.mammal)      |
// +------------------------------------+
// |[{llama}, {sheep}, {rabbit}, {hare}]|
// +------------------------------------+

This is now an array of structs and you can use getField("description") to obtain the array of interest:
df.select(flatten(col("Animal.Species.mammal")).getField("description")).show(false)
// +--------------------------------------------------------+
// |flatten(Animal.Species.mammal AS mammal#173).description|
// +--------------------------------------------------------+
// |[llama, sheep, rabbit, hare]                            |
// +--------------------------------------------------------+

Finally, array_join with separator ", " can be used to obtain the desired string:
df.select(
  array_join(
    flatten(col("Animal.Species.mammal")).getField("description"),
    ", "
  ) as "animals"
).show(false)
// +--------------------------+
// |animals                   |
// +--------------------------+
// |llama, sheep, rabbit, hare|
// +--------------------------+


text:
Q: WordPress Admin Panel search posts with custom post meta values along with title Trying to modify default admin search by including search by custom post type fields,
Below is my code,
function custom_search_query( $query ) {
    $custom_fields = array(
        // put all the meta fields you want to search for here
        "rg_1job_designation",
        "rg_2job_designation"
    );
    $searchterm = $query->query_vars['s'];
    // we have to remove the "s" parameter from the query, because it will prevent the posts from being found
    $query->query_vars['s'] = "";
    if ($searchterm != "") {
        $meta_query = array('relation' => 'OR');
        foreach($custom_fields as $cf) {
            array_push($meta_query, array(
                'key' => $cf,
                'value' => $searchterm,
                'compare' => 'LIKE'
            ));
        }
        $query->set("meta_query", $meta_query);
    };
}
add_filter( "pre_get_posts", "custom_search_query");

But it's not working.
i have a post title -> John & Designation -> Designer On search by Designer can get 1 result, But on search of John result is empty (This should also fetch one result). Now the default search for title is lost want to use that too.
Did anyone know what's wrong in my code?

A: With this code you can search in post list in WordPress Admin Panel with custom post meta values along with title and other default fields.
Please, add below code in functions.php file:
if (!function_exists('extend_admin_search')) {
    add_action('admin_init', 'extend_admin_search');

    /**
     * hook the posts search if we're on the admin page for our type
     */
    function extend_admin_search() {
        global $typenow;

        if ($typenow === 'your_custom_post_type') {
            add_filter('posts_search', 'posts_search_custom_post_type', 10, 2);
        }
    }

    /**
     * add query condition for custom meta
     * @param string $search the search string so far
     * @param WP_Query $query
     * @return string
     */
    function posts_search_custom_post_type($search, $query) {
        global $wpdb;

        if ($query->is_main_query() && !empty($query->query['s'])) {
            $sql    = "
            or exists (
                select * from {$wpdb->postmeta} where post_id={$wpdb->posts}.ID
                and meta_key in ('rg_1job_designation','rg_2job_designation')
                and meta_value like %s
            )
        ";
            $like   = '%' . $wpdb->esc_like($query->query['s']) . '%';
            $search = preg_replace("#\({$wpdb->posts}.post_title LIKE [^)]+\)\K#",
                $wpdb->prepare($sql, $like), $search);
        }

        return $search;
    }
}


text:
Q: Application Lifecycle for Xamarin.iOS I'm porting a XNA game to iOS using MonoGame and VisualStudio for Mac. In the original source code I used PhoneApplicationService to manage the application lifecycle:
PhoneApplicationService.Current.Launching += OnGameLaunching;
PhoneApplicationService.Current.Closing += OnGameClosing;
PhoneApplicationService.Current.Deactivated += OnGameDeactivated;
PhoneApplicationService.Current.Activated += OnGameActivated;

I used PhoneApplicationService in a class derived from Microsoft.Xna.Framework.Game so that I could manage the lifecycle with events inside the game loop.
To port the game to iOS, I know I need to use UIKit and provide an AppDelegate like this (the code below comes from a Xamarin example):
[Register("AppDelegate")]
class Program : UIApplicationDelegate
{
    private static Game1 game;

    static void Main(string[] args)
    {
        UIApplication.Main(args, null, "AppDelegate");
    }

    public override void FinishedLaunching(UIApplication app)
    {
        game = new Game1();
        game.Run(); // does not return until the game doesn't end
    }

    public override void OnResignActivation(UIApplication application)
    {
        // pause the stopwatch
        ...
    }

    public override void OnActivated(UIApplication application)
    {
        // resume the stopwatch
        ...
    }
}

In the code above, Microsoft.Xna.Framework.Game.Run() is invoked in FinishedLaunching() and it returns only when the game actually ends. That being said, I'm wondering whether OnResignActivation() and OnActivated() get still invoked when the application goes into a background state or when is moved back to an active state, respectively.

A: I've created a small test app and I confirm that OnResignActivation() and OnActivated() get invoked even though game.Run() doesn't return until the game doesn't end.


text:
Q: JToolbar added to JScrollPane will scroll when I put focus on a JButton on a Toolbar How do I avoid having the JScrollPane scroll that has a JToolbar added to it that has buttons when I have already scrolled to where I want to go? If I move my mouse over a Jbutton on the toolbar (I disabled the scrollpane scrollbars and disabled autoscroll for both the JToolbar and the JScrollPane) the first Jbutton I move the mouse over highlights then the whole JToolbar moves right till the last button is lined up with the right side edge of the visible area of the JScrollPane.
Also as a clue possibly to the root cause of the problem I noticed on a different JToolbar in my application if I put focus on a button by moving the mouse over the button it causes the toolbar in another window to scroll if it was already scrolled.
I am trying to implement a scrollable toolbar and if you know of a implementation that works please let me know.
Thanks,
-Tony


text:
Q: How to render if..else if...else type in React functional component? I am using React hooks and following is the conditional rendering which I want to achieve where sortDirection is a state. I want to render one of the <i> tag based on sortDirection. How can I achieve this ?
    if (sortDirection == "ascending") {
        return <i onclick={() => setSortDirection('descending')} className="fa fa-arrow-down" />
    } else if (sortDirection == "descending") {
        return <i onClick={() => setSortDirection('random')} className="fa fa-arrow-up" />
    } else {
        return <i onClick={() => setSortDirection('ascending')} className="fa fa-arrow-h" />
    }

A: You can just create a separate functional component and having the condition as a prop
const MyIComponent = (sortDirection) => {
  if (sortDirection == "ascending") {
        return <i onclick={() => setSortDirection('descending')} className="fa fa-arrow-down" />
    } else if (sortDirection == "descending") {
        return <i onClick={() => setSortDirection('random')} className="fa fa-arrow-up" />  }

    return <i onClick={() => setSortDirection('ascending')} className="fa fa-arrow-h" />
}

const MainComponent = () => <myIComponent sortDirection={sortDirection} />

A: const MyIComponent = ({sortDirection, iClassName}) => {
  return <i onclick={() => setSortDirection(sortDirection)} className={iClassName} />
}

You can pass sortDirection and iClassName dynamically from main component as a props then if conditions also you can avoid.


text:
Q: get dynamically inserted script as text I'm using an extension that allows you to write javascript and then register it to a site, which then dynamically injects this script into the site and effectively allows you to modify the DOM locally when the site is loaded up.
This is fine, however, I want to implement script updating. This would be fine if I could give the script tag an Id or even a class, but I can't. So what I need to do is somehow get the current script tags content as text (without JQuery selectors). I know how i'm going to do the rest of it though.
I had a look at document.currentScript but it's returning null. I had a quick google and this happens when it's not executing a script, but it must be if it's telling me it's null! What am I doing wrong here?

A: TamperMonkey actually has an inbuilt update operation, which by default checks for updates daily and updates the scripts. To use this, you just need to add this into the userscript headers:
// @updateURL    This is the same URL as below, as far as I can tell
// @downloadURL  URL to download the update from
// @version      This is a number, but it needs to be updated with each release for it to be updated

My original solution wouldn't have worked anyway, as it required doing an Ajax call to gitlab, which doesn't have a CORS header...


text:
Q: modifying multiple Pandas columns with .map() I'm trying to modify a few columns that all the yesses and nos become 1 and 0:
df['Outbreak Associated', 'FSA'] = df['Outbreak Associated', 'FSA'].map({'yes': '1', 'no': '0'})

Doing them one at a time works, but two or more is giving me an error. I imagine there's something simple I'm missing but I can't think of what it is.
KeyError: ('Outbreak Associated', 'FSA')

Any thoughts?

A: You can use replace, BUT if no match get original value, not NaN like map:
cols = ['Outbreak Associated', 'FSA']
df[cols] = df[cols].replace({'yes': '1', 'no': '0'})

Solutions for Series.map - you can loop each column by DataFrame.apply with lambda funcion:
df[cols] = df[cols].apply(lambda x: x.map({'yes': '1', 'no': '0'}))

Or use DataFrame.stack and
Series.unstack:
df[cols] = df[cols].stack().map({'yes': '1', 'no': '0'}).unstack()

Or using map for each column separately ;):
d = {'yes': '1', 'no': '0'}
df['Outbreak Associated'] = df['Outbreak Associated'].map(d)
df['FSA'] = df['FSA'].map(d)


text:
Q: Unity can not Build on Android:java.lang.IllegalArgumentException: already added: Manifest$permission (UNEXPECTED TOP-LEVEL EXCEPTION)
*

*When I have
----Plugins/Android/{res, jar….}
----Plugins/Android/AndroidManifest.xml
It's OK

*When I have Facebook and Google+
----Plugins/Android/{res, jar….}
----Plugins/Android/facebookSDK folder
----Plugins/Android/google-play-services_lib  (google+)
----Plugins/Android/BaseGameUtils  (google+)
----Plugins/Android/MainLibProj  (google+)
----Plugins/Android/AndroidManifest.xml
Can not Build to Android, getting error:

UNEXPECTED TOP-LEVEL EXCEPTION: java.lang.IllegalArgumentException:
  already added: L …. /Manifest$permission;

It's because of this line on AndroidManifest.xml

     <permission android:name="{my package}.permission.C2D_MESSAGE"
     android:protectionLevel="signature" />

When I remove this permission, I can build and run, but can not get Push Notification (lack of permission).
Question: How can I keep this permission on Unity?

A: Finally, I solved this issue.
When you build your ----Plugins/Android/{ jar….} (your own project). Don't add any permission on AndroidManifest.
And then add that permission on ----Plugins/Android/AndroidManifest.xml. Good luck!


text:
Q: DetachedCriteria and jax-ws Is there a way to pass a DetachedCriteria object to a jax-ws service?
(my problem is that DetachedCriteria does not have a no-arg constructor, which is required by jax-ws)

A: I would say ... please don't do that.
It's a shame to use something as decoupled as web services and then tie it to a specific Java+Hibernate combination, not to mention that and changes to your hibernate config will likely ripple through all the clients.
You're better of creating some sort of Query object which mimics the Criteria:
public class Query {

     public void setTargetClass(...) {}
     public void addPropertyEquals(...) {}

     /* more add/set instructions */

}

and then at the server side you have a class which converts the Query to a Criteria.

A: JAXB is annotation-based, so you need to annotate DetachedCriteria and all its subclassses before you can pass it via JAX-WS interfaces (on the top of requirement of no-arg constructor). That hardly doable :)
But you can serialize DetachedCriteria into stream of bytes via standard Java serialization mechanism and deserialize it on remote side. I agree, this approach is a mis-use of XML.


text:
Q: Running a queue of MPI calls in parallel with SLURM and limited resources I'm trying to run a Particle Swarm Optimization problem on a cluster using SLURM, with the optimization algorithm managed by a single-core matlab process. Each particle evaluation requires multiple MPI calls that alternate between two Python programs until the result converges. Each MPI call takes up to 20 minutes.
I initially naively submitted each MPI call as a separate SLURM job, but the resulting queue time made it slower than running each job locally in serial. I am now trying to figure out a way to submit an N node job that will continuously run MPI tasks to utilize the available resources. The matlab process would manage this job with text file flags.
Here is a pseudo-code bash file that might help to illustrate what I am trying to do on a smaller scale:
#!/bin/bash

#SBATCH -t 4:00:00 # walltime
#SBATCH -N 2 # number of nodes in this job
#SBATCH -n 32 # total number of processor cores in this job

# Set required modules
module purge
module load intel/16.0
module load gcc/6.3.0

# Job working directory
echo Working directory is $SLURM_SUBMIT_DIR
cd $SLURM_SUBMIT_DIR
echo Running on host `hostname`
echo Time is `date`
echo Directory is `pwd`

# Run Command
while <"KeepRunning.txt" == 1>
do
  for i in {0..40}
  do
    if <"RunJob_i.txt" == 1>
    then
      mpirun -np 8 -rr -f ${PBS_NODEFILE} <job_i> &
    fi
  done
done

wait

This approach doesn't work (just crashes), but I don't know why (probably overutilization of resources?). Some of my peers have suggested using parallel with srun, but as far as I can tell this requires that I call the MPI functions in batches. This will be a huge waste of resources, as a significant portion of the runs finish or fail quickly (this is expected behavior). A concrete example of the problem would be starting a batch of 5 8-core jobs and having 4 of them crash immediately; now 32 cores would be doing nothing while they wait up to 20 minutes for the 5th job to finish.
Since the optimization will likely require upwards of 5000 mpi calls, any increase in efficiency will make a huge difference in absolute walltime. Does anyone have any advice as to how I could run a constant stream of MPI calls on a large SLURM job? I would really appreciate any help.

A: A couple of things: under SLURM you should be using srun, not mpirun.
The second thing is that the pseudo-code you provided launches an infinite number of jobs without waiting for any completion signal. You should try to put the wait into the inner loop, so you launch just a set of jobs, wait for them to finish, evaluate the condition and, maybe, launch the next set of jobs:
#!/bin/bash
#SBATCH -t 4:00:00 # walltime
#SBATCH -N 2 # number of nodes in this job
#SBATCH -n 4 # total number of tasks in this job
#SBATCH -s 8 # total number of processor cores for each task

# Set required modules
module purge
module load intel/16.0
module load gcc/6.3.0

# Job working directory
echo Working directory is $SLURM_SUBMIT_DIR
cd $SLURM_SUBMIT_DIR
echo Running on host `hostname`
echo Time is `date`
echo Directory is `pwd`

# Run Command
while <"KeepRunning.txt" == 1>
do
  for i in {0..40}
  do
    if <"RunJob_i.txt" == 1>
    then
      srun -np 8 --exclusive <job_i> &
    fi
  done
  wait
  <Update "KeepRunning.txt">

done

Take care also distinguishing tasks and cores. -n says how many tasks will be used, -c says how many cpus per task will be allocated.
The code I wrote will launch in the background 41 jobs (from 0 to 40, included), but they will only start once the resources are available (--exclusive), waiting while they are occupied. Each jobs will use 8 CPUs. The you will wait for them to finish and I assume that you will update the KeepRunning.txt after that round.