text:
Q: From vim, how do I open a html file in my web browser? I have started using Vim since last month and I am halfway through Vimscript.Ijust want to know how to run my html file and open it in my browser (Edge).
Update: whenever i am writing this-
nnoremap e :exe ':silent !chromium-browser %'
it is showing that chromium-browser is not an internal or external command


text:
Q: Error on getting data from a JSON API currently I'd like to get data from a JSON API URL:
http://bitsnoop.com/api/trackers.php?hash=3BA918BF6B648BB6BEC6AAC716F1855451016980&json=1
I have tried the following:
<?php
$query = file_get_contents('http://bitsnoop.com/api/trackers.php?hash=3BA918BF6B648BB6BEC6AAC716F1855451016980&json=1');
$parsed_json = json_decode($query, true);
foreach ($parsed_json as $key => $value)
{
    echo $value['ANNOUNCE'];
    echo "
";
}
?>

Here I'd want to get the value of as:
ANNOUNCE, NUM_SEEDERS, NUM_LEECHERS, FOUND, UPDATED.
But I'm getting this error:
Warning: Invalid argument supplied for foreach() in C:\xampp\test.php on line 4

A: You need to add user agent headers
<?php
 function get_json($url, $curl = true) {
    $responseString = '';
    if (!$curl) {
        $responseString = file_get_contents($url);
    } else {
        $ch = curl_init( $url );
        $options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array('Content-type: application/json', 'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36') ,

        );
        curl_setopt_array( $ch, $options );
        $responseString =  curl_exec($ch);
    }
    return $responseString;
}

$url ="http://bitsnoop.com/api/trackers.php?hash=3BA918BF6B648BB6BEC6AAC716F1855451016980&json=1";
$query = get_json($url);
$parsed_json = json_decode($query, true);
foreach ($parsed_json as $key => $value)
{
    echo $value['ANNOUNCE'];
    echo "
";
}
?>

A: Try the below code and let me know:
<?php
$loginUrl = 'http://bitsnoop.com/api/trackers.php?hash=3BA918BF6B648BB6BEC6AAC716F1855451016980&json=1';
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$loginUrl);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
$result=curl_exec($ch);
curl_close($ch);

$result=json_decode($result,true);

$html="ANNOUNCE, NUM_SEEDERS, NUM_LEECHERS, FOUND, UPDATED.";
foreach($result as $key=>$value)
{

    $html.=$result[$key]["ANNOUNCE"].",  ";
    $html.=$result[$key]["NUM_SEEDERS"].",  ";
    $html.=$result[$key]["NUM_LEECHERS"].",  ";
    $html.=$result[$key]["FOUND"].",  ";
    $html.=$result[$key]["UPDATED"];
    $html.="
";
}
echo $html;

?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to solve two different ode system which is related? I need help on solving two systems which are related to each other. Basically, first I have to solve a non-linear ODE system. Then, I have to solve another system of equations, I have to ask mathematica to get the values from first system, in order to solve the second system.
The first system is this one:
inf = 50;
s = ParametricNDSolve[{H'[η] == -2*F[η] - ((1 - n)/(1 + n))*η*F'[η],
    F[η]^2 - (G[η] + 1)^2 + (H[η] + ((1 - n)/(1 + n))*η*F[η])*F'[η] ==
    (F'[η]^2 + G'[η]^2)^((n - 1)/2)*F''[η] + F'[η]*((n - 1)*(F'[η]^2 + G'[η]^2)^((n - 3)/2)
    *(F'[η]*F''[η] + G'[η]*G''[η])),
    2*F[η]*(G[η] + 1) + (H[η] + ((1 - n)/(1 + n))*η*F[η])*G'[η] ==
    (F'[η]^2 + G'[η]^2)^((n - 1)/2)*G''[η] + G'[η]*((n - 1)*(F'[η]^2 + G'[η]^2)^((n - 3)/2)
    *(F'[η]*F''[η] + G'[η]*G''[η])),
    F[0] == 0, G[0] == 0, H[0] == 0,
    F'[inf] == H[inf] F[inf], G'[inf] == H[inf] (G[inf] + 1)},
    {F, G, H, F', G'}, {η, 0, inf}, {n, Fp0, Gp0},
    Method -> {"Shooting", "StartingInitialConditions" ->
    {F[0] == 0, G[0] == 0, H[0] == 0, F'[0] == Fp0, G'[0] == Gp0}}];

The value of F[η], G[η] and H[η] that I get from the first system will be used to solve the second system.
I believe there is a lot of mistakes i've done to solve the second question. Hence, I need help. thank you :)
This is the second system:
inf = 20;
    alphabar=1;
    betabar=1;
    omegabar=0;
    R=1;
    sol =First@ NDSolve[{y1'[\[Eta]] == y2[\[Eta]] ,
y2'[\[Eta]]==(1/((F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 1)/2)))*(H[\[Eta]]-((n - 1)*(F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 3)/2)*(F'[\[Eta]]*F''[\[Eta]] +
                G'[\[Eta]]*G''[\[Eta]])))*y2[\[Eta]]+(1/((F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 1)/2)))*(\[ImaginaryI]*R*(alphabar*F[\[Eta]]+betabar*G[\[Eta]]-omegabar)+F[\[Eta]])*y1[\[Eta]]-(2/((F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 1)/2)))*(G[\[Eta]]+1)*y5[\[Eta]]+(R/((F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 1)/2)))*F'[\[Eta]]*y3[\[Eta]]+\[ImaginaryI]*(R/((F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 1)/2)))*alphabar*y4[\[Eta]],
y3'[\[Eta]]==-(\[ImaginaryI]*alphabar*(1/R))*y1[\[Eta]]-\[ImaginaryI]*betabar*y5[\[Eta]],
y4'[\[Eta]]==-((\[ImaginaryI]*R*(alphabar*F[\[Eta]]+betabar*G[\[Eta]]-omegabar)+H'[\[Eta]])/R)*y3[\[Eta]]-(H[\[Eta]]/R)*(-\[ImaginaryI]((alphabar*(1/R))*y1[\[Eta]]-\[ImaginaryI]*betabar*y5[\[Eta]]))-(1/R)*(((F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 1)/2))*y3''[\[Eta]]+y3'[\[Eta]]*(n - 1)((F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 3)/2))(F'[\[Eta]]* F''[\[Eta]]+ G'[\[Eta]]*G''[\[Eta]])),
y5'[\[Eta]]==y6[\[Eta]],
y6'[\[Eta]]==(1/((F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 1)/2)))*(H[\[Eta]]-((n - 1)*(F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 3)/2)*(F'[\[Eta]]*F''[\[Eta]] +
                G'[\[Eta]]*G''[\[Eta]])))*y6[\[Eta]]+(1/((F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 1)/2)))*(\[ImaginaryI]*R*(alphabar*F[\[Eta]]+betabar*G[\[Eta]]-omegabar)+F[\[Eta]])*y5[\[Eta]]-(2/((F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 1)/2)))*(G[\[Eta]]+1)*y1[\[Eta]]+(R/((F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 1)/2)))*F'[\[Eta]]*y3[\[Eta]]+\[ImaginaryI]*(R/((F'[\[Eta]]^2 + G'[\[Eta]]^2)^((n - 1)/2)))*betabar*y4[\[Eta]],  y1[0] == 0, y2[0] == 0, y3[0] == 0, y4[0] == 0, y5[0] == 0, y6[0] == 0,y1[inf] == 0, y2[inf] == 0, y3[inf] == 0,y4[inf] == 0, y5[inf] == 0, y6[inf] == 0} /. n -> 1.0,
        {y1,y2,y3,y4,y5,y6}, {\[Eta], 0.00001, inf}];

This is the error:
 NDSolve
:Derivative order  1.  in term  y1
(1.)
[η]  should be a non-negative machine-sized integer.

Thank you so much if anyone can help me on this.
Attached is the system:
I replaced η with y, U with F, V with G and W with H.

A: Here I will illustrate with a simple example to solve two couple systems of odes.
Method I
(*The first system*)
Ode1 = x'[t] == 1/y[t];
Ode2 = y'[t] == x[t];
ics := {x[0] == 1, y[0] == 2};
sys = Join[{Ode1, Ode2}, ics];
soln = First@NDSolve[sys, {x, y}, {t, 0, 10}];
x1[t_] := Evaluate[x[t] /. soln]; (*assign the interpolating function x[t] to x1[t]*)
y1[t_] := Evaluate[y[t] /. soln]; (*assign the interpolating function y[t] to y1[t]*)
(*The second system*)
Ode3 = x2'[t] == x1[t];
Ode4 = y2'[t] == x2[t] + y1[t] + y2[t];
ics2 := {x2[0] == -1, y2[0] == -2};
sys1 = Join[{Ode3, Ode4}, ics2];
soln1 = First@NDSolve[sys1, {x2, y2}, {t, 0, 10}];
Plot[{x1[t], y1[t], {x2[t], y2[t]} /. soln1}, {t, 0, 10}]

Method II
Solve the two systems as one,
Ode3 = x2'[t] == x[t];
Ode4 = y2'[t] == x2[t] + y[t] + y2[t];
combsys12 = Join[{Ode1, Ode2, Ode3, Ode4}, ics, ics2];
combsoln = First@NDSolve[combsys12, {x, y, x2, y2}, {t, 0, 10}];
Plot[{x[t], y[t], x2[t], y2[t]} /. combsoln, {t, 0, 10}]


text:
Q: Adding null to empty TreeSet raising NullPointerException import java.util.TreeSet;
class Test
{
    public static void main(String[] args)
    {
        TreeSet t=new TreeSet();
        t.add(null);
        System.out.println(t);
    }
}

output: NullPointerException.
I read in many articles that empty TreeSet will accept null for first time but am getting NullPointerException...am using java7..can any body clarify my doubt....

A: This is because for an empty TreeSet at the first element a null value can be inserted, but after inserting that first value if we are trying to insert any other objects then we will get a NullPointerException.
For a non-empty TreeSet, if we are trying to insert a null value at run time you will get a NullPointerException. This is because when some elements exist in the tree, before inserting any object it compares the new object to the existing ones using the compareTo() method and decides where to put the new object. So by inserting null the compareTo() method internally throws  NullPointerException.
I think in the new version of Java the null insertion is not allowed.

A: From 1.7 onwards null is not at all accepted by TreeSet. If you enforce to add then we will get NullPointerException. Till 1.6 null was accepted only as the first element.

A: The documentation for TreeSet#add in Java 7 states:

NullPointerException - if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements

So since you have not specified a custom comparator implementation that can handle null values, you get the NPE.
Edit: It was possible to add a null element as the first element of a TreeSet/TreeMap in Java 6, but it was considered a bug:

A: API explanation:
Synopsis: Inserting an Invalid Element into a TreeMap Throws an NPE
Description: Due to an error in java.util.TreeMap, it was previously possible to insert invalid null elements and elements not implementing the Comparable interface into an empty TreeMap or TreeSet. Only a single invalid element could be inserted into an empty TreeMap or TreeSet; additional elements would cause the expected NullPointerException or ClassCastException. Most other operations upon the collection would also fail. As of Java SE 7, inserting an invalid null element or an element not implementing Comparable into an empty TreeMap or TreeSet throws a NullPointerException.

A: TreeSet internally uses Comparable interface to sort the elements in ascending order.
compareTo() method of Comparable interface compare two values each other to find the greater value. When if you add null as element, can not compare null with other value to decide which one is the larger/greater value, for this reason compareTo() method throws NullPointerException.
Declaration of add method in TreeSet is,
public boolean add(E e) throws ClassCastException, NullPointerException;

A: For Empty TreeSet as 1st element null Insertion is possible.
But after inserting that null if we are trying to insert any element we will get NullPointerException.
And for Empty TreeSet if we are trying to Insert null we will get NullPointerException

A: In Java from Version 1.7 onwards, it is not allowed the first element as null on For Tree set it will give Runtime exception -NullPointerException.
Same if you can try in java 1.6 it will get compiled and run also when adding null on the first element but after that add any element it will give null point exception.


text:
Q: git sparse-checkout only root files in ropos subdir? I have created a git repo, added the following file structure, and pushed to remote:
test
├── dir1
│   ├── file1.txt
│   └── file2.txt
└── dir2
    ├── file1.txt
    ├── file2.txt
    ├── file3.txt
    └── file4.txt

So lets say dir1 contains project documentation and initial zip files and generally stuff I don't want to clone. I would like to perform a sparse clone and end up with the following file structure:
test_sparse
├── file1.txt
├── file2.txt
├── file3.txt
└── file4.txt

So I perform the following on my local machine:
mkdir test_sparse
cd test_sparse
git init
git config core.sparsecheckout true
echo dir2/* > .git/info/sparse-checkout
git remote add -f origin <url>/git/test
git pull origin master

But I end up with the following file structure:
test_sparse
└── dir2
    ├── file1.txt
    ├── file2.txt
    ├── file3.txt
    └── file4.txt

What do I need to write to .git/info/sparse-checkout so only the files (and potential subdirs) in dir2 are cloned and not the actual dir2?
Thank you

A: That's how sparse checkout works, it keeps the locations the same, but extracts only the parts you want. The answer to your question as asked is, sparse checkout will not restructure your history, it will not hide the existence of those other parts, it just won't put their content in the work tree for your inspection.
Git doesn't come with a lot of newbie-user convenience commands for casual structure surgery. Git can do it, it's built for that, there's power tools galore and they're not particularly difficult to use, for a starter kit look at git read-tree -um and git merge -Xsubtree or git merge -Xsubtree=dir2 to maintain a locally-sliced history, which Git will handle just fine.
But the administrative overhead of so completely hiding the existence of stuff you're not working with at the moment generally seems to exceed any savings, so Git's convenience commands don't go there. Just do git sparse-checkout set 'dir2/**' and be done with it. If some slice you're after is so completely severable that everything else is often treated as entirely separate histories, the Git way is to make them entirely separate histories. Nothing says you can't have disjoint histories in a repo and check them out / combine them into any structure you like. But Git gets its speed and efficiency from knowing where those boundaries are, so to make everything fast and efficient the way Git and it users like things, tell Git what you're doing up front.


text:
Q: What is the largest square that can fit in a dodecagon and not rotate? I am an engineer in the oil field and I am trying to find a socket that can fit around a square drive pin. I am trying to prove this for fun before I just draw it on CAD and measure it. I believe sockets have six or twelve sides. I have had some success calculating the largest hexagonal wrench that can fit on a square drive, but it came out very large and I remember that it was not this large of a tool when I worked in the field. The problem is that when you add this extra point in a hexagon making it a decagon, it allows the square to rotate. The square drive is d=.750 and I came out with x=(sqrt(5)/(3-sqrt(3))d, where x is the width across two sides of a hexagon. The proof of the hexagon starts with the fact that the largest square inside of a hexagon shares the same center. Its a strange proof that I dont understand, but it can be found here: http://www.drking.org.uk/hexagons/misc/deriv3.html.
This web page gives us the result that (1) d=(3-sqrt(3))a. Then I derived (2) a=x/sqrt(5) using the Pythagorean therom. From there, I substituted (2) into (1). and got the result x~1.764d, x~1.323 when d=.750.
I know this cant be right. I could calculate the diagonals of the square drive and set that equal to the diagonals of the dodecagon. From there I could probably find the distance between two sides of the dodecagon and that would be a starting point, but I'd rather find a relation and proof for largest square inside a dodecagon that cannot rotate. I know aligning the square diagonals with the dodecagon diagonals would not be correct because I do not think this is how you'd want to start this proof.

A: Wouldn't it be easier with a regular dodecagon, since 4 divides evenly into 12?
The largest square which will not rotate will fit snugly into four corners of the dodecagon.

Note that in $\triangle AOM$, side $OM$ must be the largest side. Since $\angle MOA<30^\circ$ then $\angle MAO>75^\circ$.


text:
Q: Solving ns3 packet receiption issue I am using ns3 to send a message and its hash using client-server echo application, i have created two packets to do so , one for the message and the other for the hash ,
  at sever i store the packet received content in a string variable "called it str"
when I received them got the message first with its correct size
but when I receive later the hash i got correct packet size but not when i stroe it my str
At time 2s client sent Message of  14 AND bytes With Hash of 64 bytes to 10.1.1.2 port 9
At time 2.00207s server received 14 AND str  14 bytes from 10.1.1.1 port 49153
At time 2.00222s server received 64 AND str  65 bytes from 10.1.1.1 port 49153
Ptr packet;
  Address from;
       while ((packet = socket->RecvFrom (from)))

      {

    uint8_t *buffer = new uint8_t[packet->GetSize ()];

    packet->CopyData(buffer, packet->GetSize ());
   std::string str = (char*)buffer;


text:
Q: Area outside of bounding box colored in reprojected wms request When making a wms request to a geoserver image mosaic layer in which I specify a crs that's different from the layer's native crs (i.e. reprojection occurs) I get a non white background color in the areas outside the bounding box as in the below picture:

The blue color is the same that is set in my sld for value 0. -9999 is the nodata value.
Here is my request. The layer has a native epsg of 4269
https://mygeoserver/geoserver/wms?service=WMS&request=GetMap&bbox=-2300000,-2200000,2700000,850000&srs=EPSG:2163&layers=climate:tmax,climate:states&styles=climate:celsius_web,&format_options=layout:provisional&width=1600&height=800&time=2017-01-14&format=image/png
Here is my style sld:
<?xml version="1.0" encoding="ISO-8859-1"?>
<StyledLayerDescriptor version="1.0.0" xmlns="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc"
  xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd">
  <NamedLayer>
    <Name>celcsius</Name>
    <UserStyle>
      <Name>celsius</Name>
      <Title>Temp C</Title>
      <FeatureTypeStyle>
        <Rule>
          <RasterSymbolizer>
            <Opacity>1.0</Opacity>
            <ColorMap>
              <ColorMapEntry color="#FFFFFF" quantity="-9999" label="" />
              <ColorMapEntry color="#CCFFFF" quantity="-30" label="-30"/>
              <ColorMapEntry color="#66FFFF" quantity="-25" label="-25"/>
              <ColorMapEntry color="#00CCFF" quantity="-20" label="-20"/>
              <ColorMapEntry color="#0099CC" quantity="-15"  label="-15"/>
              <ColorMapEntry color="#006699" quantity="-10"  label="-10"/>
              <ColorMapEntry color="#003366" quantity="-5"  label="-5"/>
              <ColorMapEntry color="#000000" quantity="0"   label="0"/>
              <ColorMapEntry color="#660000" quantity="5"   label="5"/>
              <ColorMapEntry color="#990000" quantity="10"   label="10"/>
              <ColorMapEntry color="#CC0000" quantity="15"   label="15"/>
              <ColorMapEntry color="#FF0000" quantity="20"  label="20"/>
              <ColorMapEntry color="#FF6666" quantity="25"  label="25"/>
              <ColorMapEntry color="#FFCCCC" quantity="30"  label="30"/>
            </ColorMap>
          </RasterSymbolizer>
        </Rule>
      </FeatureTypeStyle>
    </UserStyle>
  </NamedLayer>
</StyledLayerDescriptor>

How can I remove the blue color (make it transparent or white) outside of the bounding box?
EDIT: This question was closed as a duplicate, but I tried putting &BGCOLOR=0x000000 in my request as mentioned in the linked solution and that only changes the background color inside of the extent from white to black... it doesn't change the light blue color outside of the extent which is what I need. Here's a second image to show this:


text:
Q: Change MDI Parent color form back to white again How to get back to white form background when IsMdiContainer is true?
form becomes gray and i cant change it .
Me.BackColor.FromArgb(255, 255, 255)
it doesnt work, it justs makes background white of the minimize and maximize buttons.

A: For Each ctl As Control In Me.Controls
    If TypeOf ctl Is MdiClient Then
        ctl.BackColor = Me.BackColor
    End If
Next ctl

A: Try This "this will change the color of your mdi container"
  Public Sub MDIBGColor()
        Dim ctl As Control
        Dim ctlMDI As MdiClient

        ' Loop through all of the form's controls looking
        ' for the control of type MdiClient.
        For Each ctl In Me.Controls
            Try

                ' Attempt to cast the control to type MdiClient.
                ctlMDI = CType(ctl, MdiClient)

                ' Set the BackColor of the MdiClient control.
                ctlMDI.BackColor = Me.BackColor

            Catch exc As InvalidCastException
                ' Catch and ignore the error if casting failed.
            End Try
        Next

    End Sub

and call the sub on the form load event

A: #Region "Change Background Color of MDIParent : bgcolor()"
'to change the background color of mdiparent

Private Sub bgColor()
    Dim child As Control
    For Each child In Me.Controls
        If TypeOf child Is MdiClient Then
            child.BackColor = Color.CadetBlue
            Exit For
        End If
    Next
    child = Nothing
End Sub

use this in any click or form load


text:
Q: Algebraic manipulation question find inverse Could someone explain which algebraic manipulations is used to get the result on the right side of the red box.
In my opinion will $$ \frac {2}{x-2}={y-1}$$ lead to
$$ \frac {2}{y-1}+2={x}$$
So how do i get $$ \frac {1}{2
({y-2})}+2={x}$$
??
question in red

A: We get by multiplication by $$(x-2)$$:$$2=(x-2)(y-1)$$ and then dividing by $$y-1$$
so we get
$$\frac{2}{y-1}=x-2$$
adding $$2$$ so we get
$$\frac{2}{y-1}+2=x$$


text:
Q: HttpClientErrorException: 401 Unauthorized Exception in Tomcat We are trying to access the Lithium Rest Api using HTTPS through Spring Rest Template as below
String plainCreds = lswUserName + ":" + lswPassword;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<String> sRawResp = restTemplate.exchange(completeURL.toString(), HttpMethod.GET, request, String.class);

Above code always gives
org.springframework.web.client.HttpClientErrorException: 401 Unauthorized Exception

There were no issues when invoking the same web service through postman, however when ever accessed through java code, getting the above 401 unauthorized exception
Previously I faced this issue with Windows OS, and I added below entry related to proxy in to catalina.bat:
JAVA_OPTS=%JAVA_OPTS% -Dhttp.proxyHost=hy**1.*****.co.in -Dhttp.proxyPort=8080`

Now we moved the entire setup to Linux OS and I get the same error. In Linux I don't have any proxy set. I checked through wget http://www.google.com and no proxy details are displayed.
How do I resolve this issue in Linux when no proxy is set?
Please Help.


text:
Q: Making a  slideshow I am looking to create a  slideshow. What I mean by that is that I want to create one of those things that you sometimes see on websites where you have a row of buttons at the bottom, and clicking on those buttons fades you to an image or a  element, but if you do not touch those buttons, they switch in order between one another. How can I make something like this? I am new to web development, and help would be much appreciated. I am aware that this task will require JavaScript, however I would like to avoid jQuery if at all possible, I will still consider suggestions made using jQuery, so please don't hesitate to post them.
Thank you.

A: I don't believe there is any way to do this with HTML/CSS alone, though I could be wrong. When I was first starting web development I found it useful to look at code from Twitter Bootstrap to figure out how they managed to create certain effects/elements.
If I understand what you want correctly, I think you are looking for Carousel. Take a look at that and hopefully it'll help. You can even use bootstrap if you'd like.
Good luck.

A: Google Jquery Sliders or Gallerys.
Or CSS sliders

*

*http://www.queness.com/post/14329/pure-css3-sliders-and-tutorials

*http://vandelaydesign.com/blog/tools/awesome-jquery-sliders/
You dont need to know any jquery to be able to get a working slider. Read the Documentation and look at the example files to get started. If you use jquery make sure you link your files to the document correctly.

A: Here is a very simple jQuery carousel which slides automatically.
EXAMPLE
The code is very simple and easy to use as well.
HTML
Just a DIV with images inside

CSS
CSS is pretty straight forward as well
#banner_area img
{
    display:none;
    position: absolute;
}
#banner_area img:first-child
{
    display:block;
}
#banner_area > img /* Use this to resize all image's container */
{
    width:400px;
    height:250px;
}

JavaScript
Don't forget to include jQuery as well // You can increase/decrease the time
function cycleImages() {
    var images = $('#banner_area img'),
        now = images.filter(':visible'),
        next = now.next().length ? now.next() : images.first(),
        speed = 1000;

    now.fadeOut(speed);
    next.fadeIn(speed);
}

$(function () {
    setInterval(cycleImages, 1400);
});


text:
Q: Python - Calling to a function within a method from another class I'm using Python inside of Autodesk Maya but this should apply anywhere.
I have a class called bRigUI and it inherits from another class called wingUtils inside of the file wingUtilities.py
I can get to the self.gPrefix / etc. names by using inheritance. But I don't know how to get to the functions inside of the function that's inside of the class such as def cName(txt):
Here is the wingUtilities script:
import maya.cmds as cmds

class wingUtils():
    def __init__(self):
        pass
    def wingUtil(self, *args):
        self.gPrefix = cmds.textField(self.prefixField, q = True, text = True)
        self.lPrefix = cmds.textField(self.leftPrefixField, q = True, text = True)
        self.rPrefix = cmds.textField(self.rightPrefixField, q = True, text = True)

        def cName(txt):
            n = self.gPrefix + (txt)
        def lName(txt):
            n = self.gPrefix + self.lPrefix + (txt)
        def rName(txt):
            n = self.gPrefix + self.rPrefix + (txt)

w = wingUtils()

And here is a VERY dumbed down UI script that is trying to call it (and is also the class with the inheritance) - this script wont work, it's just a shell to show you what I'm doing without all the clutter.
import maya.cmds as cmds
import jtWingRigAutomation.wingUtilities as wingUtilities

reload(wingUtilities)

class bRigUI(wingUtilities.wingUtils):
    def __init__(self):

        bRigUI = 'bRigUI'

        if cmds.window(bRigUI, exists = True):
            cmds.deleteUI(bRigUI)

            bRigUI = cmds.window('bRigUI', title = 'JT Wing Rig Automation')
        form = cmds.formLayout()
        tabs = cmds.tabLayout(innerMarginWidth = 5, innerMarginHeight = 5)
        cmds.formLayout(form, e = True, attachForm=((tabs, 'top', 0), (tabs, 'left', 0), (tabs, 'bottom', 0), (tabs, 'right', 0)))

        tab2 = cmds.rowColumnLayout('Wing Setup', parent = tabs)
        cmds.text(self.naming(), parent = tab2)

        cmds.showWindow(bRigUI)
        cmds.window(bRigUI, e = True, w = 250, h = 500)

b = bRigUI()

What do I enter in the UI script to call to the function cName within the method within the wingUtils class?

A: You can't. cName is a local variable which only exists within the function context of wingUtils.wingUtil, and is only accessible via code within that function.

A: The only way would be to move the inner functions to the outer scope. Do you have a good reason for them to be function-internal? If so, there's no way to do what you want. Otherwise you may consider rewriting that class. Currently the three functions cName(), lName() and rName() do absolutely nothing, because no code can call them from outside, and they're not being called inside. In this case it's as easy as unindenting them, and adding self:
class wingUtils():
    def __init__(self):
        pass
    def wingUtil(self, *args):
        self.gPrefix = cmds.textField(self.prefixField, q = True, text = True)
        self.lPrefix = cmds.textField(self.leftPrefixField, q = True, text = True)
        self.rPrefix = cmds.textField(self.rightPrefixField, q = True, text = True)

    def cName(self, txt):
        n = self.gPrefix + (txt)
    def lName(self, txt):
        n = self.gPrefix + self.lPrefix + (txt)
    def rName(self, txt):
        n = self.gPrefix + self.rPrefix + (txt)


text:
Q: Lower Bound ,Calculus Let be $xy + xz + yz = 1$ and $x'y '+ x'z' +y'z'= 1$ , with each variable being positive , is possible show that there exists an $\epsilon > 0$ such that $x'x + y'y + z'z > \epsilon$ ?

A: No. As a counterexample, choose
$$
\vec x = \frac{1}{\sqrt{1+\frac{2}{n^2}}}\begin{pmatrix}1\\\frac 1 {n^2}\\1\end{pmatrix}\quad\text{and}\quad\vec x' = \frac{1}{\sqrt{1+\frac{1}{n} + \frac 1 {n^3}}}\begin{pmatrix}\frac 1 n\\n\\\frac 1 {n^2}\end{pmatrix}
$$
and let $n$ tend to $\infty$.


text:
Q: How to retrieve the top row in an Azure table Do I need to get all the values and than break the foreach block after the first record? Like below:
TableQuery<CustomerEntity> query = new TableQuery<CustomerEntity>()
    .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "Smith"));

// Print the fields for each customer.
foreach (CustomerEntity entity in table.ExecuteQuery(query))
{
    Console.WriteLine("{0}, {1}\t{2}\t{3}", entity.PartitionKey, entity.RowKey,
        entity.Email, entity.PhoneNumber);
    break;
}

Or is there a select top command?

A: The default sort order for table storage is by partition key and row key.  Are you looking to find the most recently added item?  If so, you could leverage the PK and RK to help you, setting the RK value to something like DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks.  Then using LINQ's Take() function to return the necessary rows.


text:
Q: MySQL bit inversion, how to only negate the fist x bits? I am using bitwise operators in MySQL. I have a column of 6 bits. When I used the bit negation operator "~" I get a 64 bt integer returned. This means I have a number of leading 1's that I don't want.
How do I negate only the last 6 bits (the rightmost 6 bits)?

A: You can use an XOR with one bits set for each bit you want to negate.
In your case, you would XOR by 0b00111111, or 0x3F.


text:
Q: split frequency and percentage in tbl_summary in to two separate columns I would to split the values of N and % into two separate columns ie, N and % columns
library(gtsummary)

trial %>%
  select(response, grade) %>%
  tbl_summary()

A: The easiest way to do this is with tbl_merge(), constructing two tables (one with N the other with %). Example below!
library(gtsummary)
#> #BlackLivesMatter
library(tidyverse)

tbl <-
  # iterate over these two statistics
  c("{n} / {N}", "{p}%") %>%
  # build tbl_summary using each of the stats
  map(
    ~trial %>%
      select(response, grade) %>%
      tbl_summary(
        statistic = all_categorical() ~ .x,
        missing = "no"
      )
  ) %>%
  # merge the two tables together
  tbl_merge() %>%
  # some formatting to make it cute
  modify_spanning_header(everything() ~ NA) %>%
  modify_footnote(everything() ~ NA) %>%
  modify_header(list(stat_0_1 ~ "**n / N**", stat_0_2 ~ "**percent**"))

Created on 2021-08-06 by the reprex package (v2.0.0)


text:
Q: Bootstrap 3 navigation too long to view on mobile devices The navigation consists of 12 links (1 being a dropdown that has an additional 4) on a single page website. The problem arises on mobile devices. The whole navigation can be seen, however, selecting the dropdown menu only the first two links can be seen on larger screens and nothing can be seen on iphone 5 (as shown in pic below).
enter image description here
If any of you guys have had similar issues or can offer a solution it would be really appreciated.
Thanks in advance.


text:
Q: Quitar el fondo blanco de mi imagen png Estoy trabajando en una aplicación en Android Studio y he leído en varios hilos que para quitar el fondo en mi buttonimage tengo que poner en sus propiedades Android: Background="null".
Efectivamente se me quita el fondo y queda una imagen transparente que es lo que busco, pero me salta el siguiente error:

Error:(14, 28) String types not allowed (at 'background' with value
  '').

¿Alguien me puede decir como resolverlo?

A: Prueba lo siguiente en la actividad correspondiente:
ImageView image = (ImageView) findViewById(R.id.id_de_tu_imageView);

image.setBackgroundDrawable(null);

o como ha dicho el compañero "Pikoh"  android:background="@null"en el ImageView de tu xml.

A: Utiliza el simbolo '@' delante de null al establecer la referencia; de esta manera:
android:background="@null", también puedes utilizar android:background="@android:color/transparent".
Tu error se debe a que estas asignando un string a la propiedad background cuando esta necesita una referencia a un drawable, en este caso @null representa la ausencia de este.
Cuando le asignas la referencia @null a la propiedad background, se mostrará cualquier elemento que se encuentre detrás, en tu caso especifico, desaparecerá el fondo y los bordes del botón.

A: Si defines la propiedad android:background, es estrictamente necesario definas el recurso, puede se color, imagen o un drawable .xml, el color puede incluso tener transparencia
android:background="@???/???"

Por el mensaje de error deduzco que cargas un valor vacio:
android:background=""

o el recurso hace referencia a un valor vacio, por ejemplo :
android:background="@color/mi_color"

donde el valor no ha sido especificado:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="mi_color"></color>
</resources>

¿Como quitar el fondo blanco de mi ImageButton'?

Programaticamente pueds asignar un valor null al fondo:
imageButton.setBackgroundDrawable(null);

o mediante la definición del valor en el layout:
android:background="@null"


text:
Q: How to make a pointer to a varible inside nested structs in C? In the following code,how to create a pointer to the variable triangle.pluto.mars.a so it becomes unnecessary in the printf line to repeat the whole path for member a.
#include <stdio.h>

int main(){
    struct euler {
        int a;
        int b;
    };

    struct gauss {
        int f;
        int g;
        struct euler mars;

    };

    struct aristotle{
        int x;
        int y;
        struct gauss pluto;
    } triangle;

    triangle.pluto.mars.a = 151;

    printf("\nThe value is: %d\n\n",triangle.pluto.mars.a );

    return 0;
}

A: The band-aid solution:
int * someVariable = &(triangle.pluto.mars.a);

The long solution: Do a redesign.

A: If you are willing to rearrange your structures, you will have a more "intuitive" means of accessing your members. While C does not offer inheritance, it does guarantee that the pointer to the first member of a structure is equal in value to the pointer to the containing structure. This allows you to mimic inheritance like behavior via pointer conversion.
    struct euler {
        int a;
        int b;
    };

    struct gauss {
        struct euler mars;
        int f;
        int g;
    };

    struct aristotle{
        struct gauss pluto;
        int x;
        int y;
    } triangle;

    triangle.pluto.mars.a = 151;

    struct euler *e = (void *)▵
    struct gauss *g = (void *)▵

    printf("\nThe value is: %d\n\n", e->a );

This guarantee is stated in C.11 §6.7.2.1 ¶15 (emphasis mine, and similar language exists in C.99):

Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

This does not take away from @LawrenceAiello's answer, which still works after the reorganization suggested above.

A: int *num = &(triangle.pluto.mars.a);

I suggest you redesign your structs fields to be pointers.
Such as
struct euler {
    int *a;
    int *b;
};


text:
Q: Write unit tests for restish in Python I'm writing a RESTful API in Python using the restish framework.  I would like to write some unit tests (using the unittest package, for example), that will make different requests to my application and validate the results.  The unit tests should be able to run as-is, without needing to start a separate web-server process. How do I set up a mock environment using restish to do this?
Thanks

A: I test everything using WebTest and NoseTests and I can strongly recommend it. It's fast, flexible and easy to set up. Just pass it your wsgi function and you're good to go.

A: Since restish is a WSGI framework, you can take advantage of any one of a number of WSGI testing tools:

*

*http://wsgi.org/wsgi/Testing
At least a few of those tools, such as Twill, should be able to test your application without starting a separate web server.  (For example, see the "Testing WSGI Apps with Twill" link for more details.)
You might want to ask on the restish forum/list if they have a preferred tool for this type of thing.

A: Restish has a built in TestApp class that can be used to test restish apps.
Assuming you have a "test" dir in your root restish project callte "restest" created with paster.
import os
import unittest
from paste.fixture import TestApp

class RootTest (unittest.TestCase):

  def setUp(self):
    self.app = TestApp('config:%s/../development.ini' % os.path.dirname(os.path.abspath(__file__)))

  def tearDown(self):
    self.app = None

  def test_html(self):
    res = self.app.get('/')
    res.mustcontain('Hello from restest!')

if __name__ == '__main__':
    unittest.main()


text:
Q: PyQt5 QML Signal to Python Slot? How can a python method/slot be connected to a QML signal? It looks like QtObject.connect() used to work in PyQt4 but it's no longer available in PyQt5.
#Sample QML File (stack.qml)

import QtQuick 2.0

Rectangle {
    MouseArea {
        anchors.fill: parent
        onClicked: {
           // relay this to python
        }
    }
}

--
#Sample Python File
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQuick import QQuickView

if __name__ == '__main__':
    import os
    import sys

    app = QGuiApplication(sys.argv)

    view = QQuickView()
    view.setWidth(500)
    view.setHeight(500)
    view.setTitle('Hello PyQt')
    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.setSource(QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__),'stack.qml')))

    def on_qml_mouse_clicked(mouse_event):
        print 'mouse clicked'

    view.show()
    qml_rectangle = view.rootObject()

    # this technique doesn't work #############################
    qml_rectangle.mousePressEvent.connect(on_qml_mouse_clicked)

    sys.exit(app.exec_())

Some of the PyQT examples pass an object into the QML context via "setContextProperty" and then relay QML events to slots on that object but that approach seems roundabout. Is there a better way?

A: I would recommend sub classing QQuickView and setting a property on its root context, for example MainWindow. Now all you need to do is adding functions in that class with decorations such as @pyqtSlot('QString'), and then you can set the event handler with onClicked: MainWindow.FunctionName(Arguments_According_To_Decoration)
Then your main.py would look like this
#!/bin/env python3
# -*- coding: utf-8 -*-
from PyQt5.QtCore    import pyqtSlot
from PyQt5.QtCore    import QUrl
from PyQt5.QtQuick   import QQuickView
from PyQt5.QtWidgets import QApplication
import sys

class MainWindow(QQuickView):
    def __init__(self):
        super().__init__()
        self.setSource(QUrl('sample.qml'))
        self.rootContext().setContextProperty("MainWindow", self)
        self.show()

    @pyqtSlot('QString')
    def Print(self, value):
        print(value)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    sys.exit(app.exec_())

And sample.qml like so
import QtQuick          2.0
import QtQuick.Controls 2.2

Rectangle {
    width: 200; height: 200

    Button {
      text: "print Hello World"
      onClicked: MainWindow.Print('hello world')
    }
}

You can find more information in the docs
http://pyqt.sourceforge.net/Docs/PyQt5/signals_slots.html

A: qml_rectangle.mousePressEvent is not a signal, it's an event handler that is called on mouse events, so you can't connect to it. You could just replace it with your handler function (qml_rectangle.mousePressEvent = on_qml_mouse_clicked), but that's not a very clean way of working with Qt.
The better way would be to define a signal in your qml file and emit it from the rectangle's onClicked handler:
import QtQuick 2.0

Rectangle {
    signal clicked()
    MouseArea {
        anchors.fill: parent
        onClicked: {
           parent.clicked()  // emit the parent's signal
        }
    }
}

Then you can just connect to it from your python code:
...
def on_qml_mouse_clicked():
    print('mouse clicked')

qml_rectangle.clicked.connect(on_qml_mouse_clicked)
...


text:
Q: Add clickable buttons to a custom DataGridViewCell control I made a custom DataGridViewColumn control together with its DataGridViewCell controls.
The idea is to dynamically create the contents of the cell, which consists of a series of clickable function buttons, upon databinding. The number and kinds of buttons depend on the data value passed.
For this, I override the Paint method of the DataGridViewCell and check the formattedValue on its contents and draw buttons accordingly. However, these buttons are "dead" and not clickable, so the question is how to make them clickable, i.e. how do I add a handler for the click event?
Do I have to override the cell's OnClick method and then try to pinpoint which button exactly is clicked? Is this even possible? Are there better ways?
This is what I've got so far:
    Protected Overrides Sub Paint(graphics As Graphics, clipBounds As Rectangle, cellBounds As Rectangle, rowIndex As Integer, cellState As DataGridViewElementStates, value As Object, formattedValue As Object, errorText As String, cellStyle As DataGridViewCellStyle, advancedBorderStyle As DataGridViewAdvancedBorderStyle, paintParts As DataGridViewPaintParts)

    MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts)

    Dim cellBackground As New SolidBrush(cellStyle.BackColor)
    graphics.FillRectangle(cellBackground, cellBounds)
    cellBackground.Dispose()

    PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle)

    Dim sValue As String = formattedValue.ToString()

    If (sValue.Contains("ViewAsPDF")) Then

        Dim buttonArea As Rectangle = cellBounds
        Dim buttonAdjustment As Rectangle = Me.BorderWidths(advancedBorderStyle)
        buttonArea.X += buttonAdjustment.X
        buttonArea.Y += buttonAdjustment.Y
        buttonArea.Height -= buttonAdjustment.Height
        buttonArea.Width -= buttonAdjustment.Width
        buttonArea.Width = buttonArea.Width / 4
        ButtonRenderer.DrawButton(graphics, buttonArea, PushButtonState.Default)
        TextRenderer.DrawText(graphics, "PDF", Me.DataGridView.Font, buttonArea, SystemColors.ControlText)

    End If

   'etcetera

End Sub

A: I think you may have wandered down the wrong road.  Based on the code provided, you are simply drawing  the cells to look like they contain buttons.  Since they are not actually objects, they are incapable of raising events.
I don't understand ButtonRenderer, if you can't create actual Buttons with it
The ButtonRender does not create a new button object, it is meant to be used by Button objects for drawing.  Often a subclassed a button, will not use it because it employs the existing theme and style which is may be what a you wants to do differently (even the DataGridViewButtonCell does not use it -- at least not directly).
From the code provided, it seems to work out each button on the fly each time rather than drawing from some collection or definition.   What if the "action" list needs to vary based on the row (e.g. different actions for a DOC, XLS or Image row)?  Doing so, would seem to take a great deal of code.

Your current course may not be impossible, but it is not trivial either.  You  might be able to create a collection of virtual buttons (basically the Rect from when it was drawn) and render them as you have done.  Then in the cell-click event, translate/adjust the X position to see which rectangle contains thisPt.X to determine which related action to take.
There are "issues" still such as what happens when the user resizes the column? What about when the button list varies by some other cell value (DOC vs XLS vs IMG vs PDF)?  This would require a collection of button sets...and a fair amount of code.
This is not to say it cant be done, but it seems like a great deal of code would be required to make it even a little flexible.

Are there better ways?
I think so.
A simpler, existing solution might be to use the existing DataGridViewComboBoxColumn to store "Actions" or "Activities".  It seems a bit less cluttered and more user friendly:

It takes only a small amount of code to provide a different list for each animal:
' dogs like to go for walks
Private ActsCan() As String = {"Feed", "Pet", "Bathe", "Brush", "Take for Walk"}
' no walks or baths for cats
Private ActsFel() As String = {"Feed", "Pet", "Baby-Talk To", "Brush"}
' never bathe a Mugwai, comb rather than brush
Private ActsMug() As String = {"Feed", "Pet", "Baby-Talk To", "Comb"}
Private ActsGrem() As String = {"Hide From", "Strangle"}
...
Private Sub dgv_RowEnter(sender As Object,
          e As DataGridViewCellEventArgs) Handles dgv.RowEnter

    Dim dgvCBO As DataGridViewComboBoxCell
    dgvCBO = CType(dgv.Rows(e.RowIndex).Cells("ColActs"), DataGridViewComboBoxCell)
    dgvCBO.Items.Clear()
    Select Case dgv.Rows(e.RowIndex).Cells("colSpecies").Value.ToString
        Case "Canine"
            dgvCBO.Items.AddRange(ActsCan)
        Case "Feline"
            dgvCBO.Items.AddRange(ActsFel)
        Case "Mugwai"
            dgvCBO.Items.AddRange(ActsMug)
        Case "Gremlin"
            dgvCBO.Items.AddRange(ActsGrem)
    End Select
End Sub

A class to encapsulate most of that might be nice for unbound DGVs.  It could be optimized not to rebuild the list when the trigger value for thisRow is the same as the last.

A: What about this approach. Only implementing the ui.


text:
Q: Tikz tree in beamer % Red-black tree
% Author: Madit
\documentclass[leqno,fleqn,table]{beamer}
\usepackage{tikz}
%%%<
%\usepackage{verbatim}
%\usepackage[active,tightpage]{preview}
%\PreviewEnvironment{tikzpicture}
%\setlength{\PreviewBorder}{10pt}%
%%%>
%\begin{comment}
%:Title: Red-black tree
%:Tags: Trees;Graphs
%:Author: Madit
%:Slug: red-black-tree
%
%A red-black tree is a special type of binary tree, used in computer science
%to organize pieces of comparable data, such as text fragments or numbers.
%(Wikipedia)
%\end{comment}
\usetikzlibrary{arrows}

\tikzset{
  treenode/.style = {align=center, inner sep=0pt, text centered,
    font=\sffamily},
  arn_n/.style = {treenode, circle, white, font=\sffamily\bfseries, draw=black,
    fill=black, text width=1.5em},% arbre rouge noir, noeud noir
  arn_r/.style = {treenode, circle, red, draw=red,
    text width=1.5em, very thick},% arbre rouge noir, noeud rouge
  arn_x/.style = {treenode, rectangle, draw=black,
    minimum width=0.5em, minimum height=0.5em}% arbre rouge noir, nil
}

\begin{document}

\begin{frame}
\begin{minipage}[c]{\textwidth}
\begin{tikzpicture}[->,>=stealth',level/.style={sibling distance = 5cm/#1,
  level distance = 1.5cm}]
\node [arn_n] {33}
    child{ node [arn_r] {15}
            child{ node [arn_n] {10}
                child{ node [arn_r] {5} edge from parent node[above left]
                         {$x$}} %for a named pointer
                            child{ node [arn_x] {}}
            }
            child{ node [arn_n] {20}
                            child{ node [arn_r] {18}}
                            child{ node [arn_x] {}}
            }
    }
    child{ node [arn_r] {47}
            child{ node [arn_n] {38}
                            child{ node [arn_r] {36}}
                            child{ node [arn_r] {39}}
            }
            child{ node [arn_n] {51}
                            child{ node [arn_r] {49}}
                            child{ node [arn_x] {}}
            }
        }
;
\end{tikzpicture}
\end{minipage}
\end{frame}
\end{document}

So I'm using this in a beamer but get an error (illegal parameter number in definition of iterate)
Though it works when i delete the frames and make the documentclass article.
Is it possible to get it working in beamer?

A: Pass the [fragile] option to the 'frame' environment:
\begin{frame}[fragile]
    ...
    % \end{frame} must be on a single line!
\end{frame}

In your case, this is necessary because of the use of a tex parameter (#1) inside the style definition of the tikzpicture. TeX'nically speaking: To provide for the parameter syntax in style definitions, TikZ needs to change the catcode of #, which in turn requires to use the fragile option for the frame enivornment.
Background
fragile appears to be a "magic" option to solve all kinds of strange error messages. Basically, it just has to be used whenever some part of the frame content needs to be read verbatim, that is, without immediately interpreting special characters (#1 in this case).
The details are explained in the beamer user guide in §8.1:

fragile[=singleslide] tells beamer that the frame contents is
  "fragile." This means that the frame contains text that is not
  "interpreted as usual." For example, this applies to verbatim text,
  which is, obviously, interpreted somewhat differently from normal
  text. If a frame contains fragile text, different internal mechanisms
  are used to typeset the frame to ensure that inside the frame the
  character codes can be reset. The price of switching to another
  internal mechanism is that either you cannot use overlays or an
  external  file needs to be written and read back (which is not always
  desirable).
In detail, the following happens when this option is given
  for normal (pdf)LATEX: The contents of the frame is scanned and then
  written to a special  le named ⟨jobname⟩.vrb or, if a label has been
  assigned to the frame, ⟨jobname⟩.⟨current frame number⟩.vrb. Then, the
  frame is started anew and the content of this  file is read back.
  Since, upon reading of a  file, the character codes can be modified,
  this allows you to use both verbatim text and overlays.
To determine
  the end of the frame, the following rule is used: The  first occurence
  of a single line containing exactly \end{⟨frame environment name⟩}
  ends the frame.


text:
Q: Get kubernetes pods to take on a specific identity / role / job once started What I am presenting here is a simplified version of my setup and the syntax is wrong.
I have a list of high level "agents" that I want to deploy as pods on a kubernetes cluster.
Some nodes in this cluster have special hardware, some don't, but all the pods should use the same container.
Could look like (again: syntax is wrong):
agent1 wlan
...
agent8 wlan
agent9 wlan rs232.1
agent10 wlan rs232.2

I setup a deployment that roughly looks like that (the syntax is wrong):
deployment (standard nodes)
  replicas: 8
---
deployment (rs232, terminal 1)
  replicas: 1
  nodeSelector:
    rs232=1
  env:
    rs232=1 (because nodeSelector can't be passed nicely afaik)
---
deployment (rs232, terminal 2)
  replicas: 1
  nodeSelector:
    rs232=2
  env:
    rs232=2

I would like each of these agents to start up and take on one identity from the list, while having the matching hardware of course.
So like a pod would talk to a role distribution service like that:
pod - Hi, I'm pod/container-xyz and I have env/label/annotation rs232=2
service - Hi, well then you are now agent10
pod - OK I'll do the work of agent10 then
(service - cool, I'll add agent10 as an alias to you in the cluster DNS) <- that will be my next question

Same thing for agents no with special hardware: the service gives them one agent role each.
I tried something with StatefulSet but that does not fit the bill (because of the various nodeSelector and they are super slow to start).
I started to think about a dedicated self-implemented server pod that would keep my agent list and lease them to matching hardware (a bit like dhcp server) but I'm pretty sure I am not the only one having this problem and there must be a solution out there. I looked quickly at Zookeeper but I don't think it is for me. I am probably not finding the solution because my vocabulary is not the correct one I guess.
Has anybody got a good idea ? Am I going in the right direction ?

A: I would probably implement this with a MetaController CompositeController and a Custom Resource which defines the agents. Coding is required though. It looks much more complicated than it is.
Basically you regularly receive sync hooks over HTTP describing the current state of resources and you respond with JSON to create/destroy them.


text:
Q: How do you get the value inside an XML document? In below XML I need to confirm "Internet" is there.

Internet

I tried the following:
WebElement findInternet = driver.findElement(By.xpath("//h1"));
System.out.println(findInternet);

A: I think this will work for you:
WebElement findInternet = driver.findElement(By.cssSelector("h1.theme--primary"));
System.out.println(findInternet.getText());

Your xpath selector will probably work as well, the key thing you were missing is your println was printing the findInternet object.  getText() will get the inner text of the selected element.`


text:
Q: OAuth2 token with google play services on Android I'm attempting to get a Oauth2 token for Google Cloud Storage on Android using Google Play services.  I am using the following code
try {
        gsToken=GoogleAuthUtil.getToken(this, email,
            "https://www.googleapis.com/auth/devstorage.read_only");
    } catch (IOException e) {
        e.printStackTrace();
    } catch (UserRecoverableAuthException userAuthEx) {
            startActivityForResult(userAuthEx.getIntent(),1);;
    } catch (GoogleAuthException e) {

    }

This throws a GoogleAuthException.  Is this scope not supported at this time by Google PLay Services??

A: You need to prefix the scope with the string "oauth2:" when asking GoogleAuthUtil for OAuth2 tokens. If you want multiple scopes you can list them with a space separator.
So, in your case the scope string would be "oauth2:https://www.googleapis.com/auth/devstorage.read_only".
For more details see http://android-developers.blogspot.com/2012/09/google-play-services-and-oauth-identity.html.


text:
Q: TypeScript: inferring data types from variadic tuple types Variadic tuple types allow us to provide the caller of a function, a tuple return type
driven by the tuple supplied to the function like so:
function makeArrayAsConstItems<T extends readonly any[]>(...arr: [...T]): {[K in keyof T]: {item: T[K]} } {
    return arr.map(item => ({ item })) as any;
}

const arrayAsConstItems = makeArrayAsConstItems('cfgh', 1, new Date());

// this is the type
const arrayAsConstItems: [{
    item: string;
}, {
    item: number;
}, {
    item: Date;
}]

Now consider we want to do two more things:

*

*Narrow the items that can be supplied in each array element to be a type of Data<TypeOfData>

*Extract the type we're going to be returning from Data<TypeOfData>; so use TypeOfData essentially

interface Data<TypeOfData = unknown> {
    data: TypeOfData;
}

function makeArrayAsConstItemsForDataTypesOnly<T extends readonly Data[]>(...arr: [...T]): {[K in keyof T]: {item: T[K]} } {
    return arr.map(item => ({ item })) as any;
}

const arrayAsConstItemsForDataTypesOnly = makeArrayAsConstItemsForDataTypesOnly(
    { data: 'cfgh' },
    { data: 1 },
    { data: new Date() }
)

What would we need to do for arrayAsConstItemsForDataTypesOnly to have the same type as arrayAsConstItems?
At present the type is:
const arrayAsConstItemsForDataTypesOnly: [{
    item: {
        data: string;
    };
}, {
    item: {
        data: number;
    };
}, {
    item: {
        data: Date;
    };
}]

And we desire it to be:
const arrayAsConstItemsForDataTypesOnly: [{
    item: string;
}, {
    item: number;
}, {
    item: Date;
}]

This is @A_blop's suggestion:
function makeArrayAsConstItemsForDataTypesOnly<T extends readonly Data[]>(...arr: [...T]): {[K in keyof T]: {item: Extract<T[K], Data>["data"]} } {
    return arr.map(item => ({ item })) as any;
}

A: We can do that by utilizing lookup types in combination with the Extract utility type:
function fn<T extends readonly Data[]>(...arr: [...T]):
    { [K in keyof T]: { item: Extract<T[K], Data>["data"] } } {/* impl */}

const arrayAsConstItemsForDataTypesOnly = fn(
    { data: 'cfgh' },
    { data: 1 },
    { data: new Date() }
)
/*
[{
    item: string;
}, {
    item: number;
}, {
    item: Date;
}]
 */

As TypeScript cannot resolve T[K] further, we need to first convince it again, that the resulting type has a data property accessible via lookup operator. This is done by Extract.
Playground


text:
Q: How do I programmatically trigger an "input" event without jQuery? I installed an event handler on an input using
var element = document.getElementById('some-input');
element.addEventListener('input', function() {
    console.log('The value is now ' + element.value);
});

As expected, the handler is triggered when I type into the text field, but I also need to invoke this handler from my code. How can I simulate the input event so that my event listener is called?

A: element.dispatchEvent(new Event('input'));

A: The proper way to trigger an event with plain JavaScript, would be to create an Event object, and dispatch it
var event = new Event('input', {
    bubbles: true,
    cancelable: true,
});

element.dispatchEvent(event);

Or, as a simple one-liner:
element.dispatchEvent(new Event('input', {bubbles:true}));

FIDDLE
This is not supported in IE, for that the old-fashioned way still has to be used
var event = document.createEvent('Event');
event.initEvent('input', true, true);

elem.dispatchEvent(event);

A: If you are using react, following will work:
const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
    valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));


text:
Q: bitwise shift for a string holding a numeric hex. in perl I have a string
$string = "0x0"

Now I want to basically use this string as a number and do a bitwise shift i.e my aim is to
$C = $string <<4 ;

But when I do this it says :
Argument "0x0" isn't numeric in left bitshift (<<)

Can someone please help to execute this ?

A: It's because "0x0" isn't numeric. It's a string. You would have to turn it into a numeric value.
 use strict;
 use warnings;

 my $string = "0x0";
 my $number = hex($string);
 my $C = $number <<4 ;
 print $C;

A: As mentioned, you have to convert it to a numeric value and use sprintf to turn back to a hexadecimal value.
sprintf ("0x%x" , hex($string) << 4);


text:
Q: Oracle Clusterware - What is the difference between Votedisk, quorum disk and quorum failure group? Some references say quorum disk and vote disk are the same, but "quorum disk" name was used in older versions. But Oracle 19c documentation still use both the names, so I think there is a difference. Also, when to use quorum failure group and what is it? documentation says:

A quorum failure group is a special type of failure group that does
not contain user data. Quorum failure groups are used for storing
Oracle ASM metadata. A quorum failure group may also contain voting
files if those files are stored in a disk group that contains a quorum
failure group. Additionally, Oracle ASM uses a quorum failure group to
help determine if the disk group can be mounted in the event of the
loss of one or more failure groups.

Ok, but, for example, we have a Oracle Clusterware running and there is no quorum failure group configured, so it seems it can be used or not. When to use it?

A: The QUORUM DISK can only contain the "voting file". But a voting file can reside in either QUORUM DISK or REGULAR DISK. And the voting file is called votedisk in the crsctl command ("Adding, Deleting, or Migrating Voting Files").
A quorum failgroup is a failgroup with quorum disk only. So if you place the voting file in a diskgroup with 2 regular disk + 1 quorum disk, and Oracle can have 3 copy of the voting file.


text:
Q: How do I rearrange a deciphered text grammatically? Trying out a simple text cipher program by simply mapping each alphabet to a numerical value plus one. Here is the code.
import string

chars = [c for c in string.ascii_lowercase]
nums = [n for n in range(1, 27)]

plain_cipher = dict(zip(chars, nums))

prompt = input("Enter a word to decipher > ")

# Ciphering ...
print('Ciphering ... ')
cipher = [str(plain_cipher[char]+1)for char in prompt]

print('-'.join(cipher))

# Deciphering ...
decipher = [int(num)-1 for num in cipher]
text = ''

for k in plain_cipher.keys():
    for n in decipher:
        if plain_cipher[k] == n:
            text += k

print('Deciphering ... ')
print(text)

.
Prints out the correct ciphered output but the wrong deciphered output. Output returned alphabetically.
How do you correct this?

A: The problem is that when you look for a match you're iterating through the keys of the plain_cipher dictionary in the outer loop, then the ciphered message in the inner loop - so you'll see results in the order the dictionary iterator gives you (ie alphabetical).
for k in plain_cipher.keys():
    for n in decipher:
        if plain_cipher[k] == n:
            text += k

Switch the two loops and you'll search through the ciphertext decoding letters as you go:
for n in decipher:
    for k in plain_cipher.keys():
        if plain_cipher[k] == n:
            text += k


text:
Q: Multilanguage Next.js app with different language builds I would like to build a Next.js website and it should be multilanguage.
Each language is going to have its own domain, so there is no need to implement instant language switcher.
It's going to work the next way:
1) user goes to the website.com, the js code detects user location/language etc
2) it redirects to the website with detected language.
So I am going to have one client app, but it should have different languages for different domains.
What is the best way to do so?

A: Even with this redirect logic I would use https://www.i18next.com/ and https://github.com/i18next/i18next-browser-languageDetector if you detect the language and then redirect the languageDetector will then do the same and set the corresponding local or instead of languageDetector you just detect the domain and use this to set the local. If you really need the redirect logic  I hope you detect the language and redirect from server side and not with js.


text:
Q: getter не возвращает значение Имеется vector, который заполняется классе, необходимо передать его в другой класс, ну для этих целей сделал getter. По дебагу смотрел, возвращается пустой список. Проверил в классе, в котором заполняются данные, там vector заполнен некоторыми значениями. Как доходит программа до getter'а, то он оказывается пустой. Подскажите в чем причина?
Класс в котором заполняется vector (.h)
#ifndef INCLUDE_WALLSMANAGER_H_
#define INCLUDE_WALLSMANAGER_H_

#include <Wall.h>
#include <vector>

class WallsManager : IReader {
    std::vector<Wall> wallsToRenderList;
    std::vector<Wall> walls;
 public:
    void renderWalls();
    void Read() override;
    void renderVerticalWalls(Wall item);
    void renderHorizontallWalls(Wall item);

    const std::vector<Wall> &getWalls() const;

    void setWalls(const std::vector<Wall> &walls_);
};
#endif  // INCLUDE_WALLSMANAGER_H_

cpp файл
#include <WallsManager.h>
#include <BearLibTerminal.h>
#include <fstream>
#include <string>
#include <vector>

Wall wall{};

void WallsManager::Read() {
    int xSt, ySt, xEnd, yEnd;
    std::string direction;
    std::ifstream file("C:/Users/Konstantin/CLionProjects/Game/levels/WallsLevel");
    if (file) {
        while (!file.eof()) {
            file >> direction;
            if (direction == "hor") {
                file >> xSt >> xEnd >> ySt;
                wall.setXStart(xSt);
                wall.setXEnd(xEnd);
                wall.setYStart(ySt);
                wall.setDirection(direction);
                wallsToRenderList.push_back(wall);
            }
            if (direction == "vert") {
                file >> ySt >> yEnd >> xSt;
                wall.setYEnd(yEnd);
                wall.setYStart(ySt);
                wall.setXStart(xSt);
                wall.setDirection(direction);
                wallsToRenderList.push_back(wall);
            }
        }
    }
}

void WallsManager::renderVerticalWalls(Wall item) {
    for (int i = item.getYStart(); i < item.getYEnd(); i++) {
        terminal_put(i, item.getXStart(), '#');
        wall.setCurrentX(item.getXStart());
        wall.setCurrentY(i);
        walls.push_back(wall);
    }
}

void WallsManager::renderHorizontallWalls(Wall item) {
    for (int i = item.getXStart(); i < item.getXEnd(); i++) {
        terminal_put(i, item.getYStart(), '#');
        wall.setCurrentX(i);
        wall.setCurrentY(item.getYStart());
        walls.push_back(wall);
    }
}

void WallsManager::renderWalls() {
    for (auto item : wallsToRenderList) {
        if (item.getDirection() == "hor") {
            renderHorizontallWalls(item);
        }
        if (item.getDirection() == "vert") {
            renderVerticalWalls(item);
        }
    }
    setWalls(walls);
}

const std::vector<Wall> &WallsManager::getWalls() const {
    return walls;
}

void WallsManager::setWalls(const std::vector<Wall> &walls_) {
    WallsManager::walls = walls_;
}

То есть vector walls в методе getWalls() показывается в дебаге, как пустой.


text:
Q: $\cos(2\pi f nT +2\pi N_n) =\ cos(2\pi f nT)$ and more, why? I am studying signals and systems and this came up?
Could someone explain why is $\cos(2\pi f nT +2\pi N_n)$  equal to $\ cos(2\pi f nT)$?
The book says: "because $N_n$ is an integer"
I am wondering how does that explain the equation?
Same with the following:
$e^{i2\pi Nf_snT}=1$
in
snippet from book

A: Look at the picture below;

Can you see that between $0$ and $2\pi$ has a specific behaviour, but repeats after the $2\pi$? This is because the cosine function has a period of $2\pi$. That is to say, $$\cos(x) = \cos(x + 2k\pi)$$
for $k\in \Bbb{Z}.$ To illustrate this, plugging $0$ into the cosine gives $$\cos(0) = 1 = \cos(0 + 2\pi) = \cos(0 + 4\pi) = \dots.$$


text:
Q: java.nio.file organizing text from a file I have never really worked with text files in java before, but now I need to and I am sort of stuck. Below is what I have.
public static void main(String[] args) {
    Path file = Paths.get("dir/NRCLexiconEmotion.txt");

    Charset charset = Charset.forName("US-ASCII");

    try (BufferedReader reader = Files.newBufferedReader(file, charset)) {
        String line = null;

        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException x) {
        System.err.format("IOException: %s%n", x);
    }

}

and this is part of the output
virtual anger   0
virtual anticipation    0
virtual disgust 0
virtual fear    0
virtual joy 0
virtual negative    0
virtual positive    0
virtual sadness 0
virtual surprise    0
virtual trust   0

I am trying to copy the word and then I am going to create a serial number for the word using the numbers. So I need to be able to read the word then the emotion and then the number matched to the emotion.
I tried using line.charAt(); and when I put an index number in I just get an error. I think what is causing me troubles is I don't know a lot about streams. I can't seem to find a specific method for my need in the java docs and was wondering if someone could help me out.
if it helps or anyone is interested I am wanting to match songs to certain moods based on the lyrics of the songs, tags and genres. So I will be working with a lot of text files.


text:
Q: adding an external "find my location" button outside of the map I'm trying to add a button above my map that would show the current location of the user.
Basically i want to duplicate the functionality of the built in button but make a more obvious one.
Here's my code:
<script>
  var map = L.mapbox.map('map', 'plisvb.hopljoko');
  L.control.locate({
    drawCircle: true, // controls whether a circle is drawn that shows the uncertainty about the location
    setView: true, // automatically sets the map view to the user's location, enabled if `follow` is true
    keepCurrentZoomLevel: false, // keep the current map zoom level when displaying the user's location. (if `false`, use maxZoom)
    icon: 'icon-location', // `icon-locate` or `icon-direction`
    iconLoading: 'icon-spinner  animate-spin', // class for loading icon
    circlePadding: [0, 0], // padding around accuracy circle, value is passed to setBounds
    locateOptions: {
      maxZoom: 15
    },
    strings: {
      title: "Click to see your current location", // title of the locate control
      popup: "Your current location", // text to appear if user clicks on circle
      outsideMapBoundsMsg: "You seem located outside the boundaries of the map" // default message for onLocationOutsideMapBounds
    }
  }).addTo(map);
  map.scrollWheelZoom.disable();
</script>

any ideas?

A: The question was posted a year ago but if people are still looking for an answer I found the following:
    http://codepen.io/leemark/pen/vcbuf
$('.pure-button').on('click', function(){
mymap.locate({setView: true, maxZoom: 15});
});

In the example provided this is the call on the click event of the button. You can either use their button or create a different looking one.
I'm not sure if it is exactly what I want and not sure if I will implement it. However it seem to answer the original post.

A: I'd recommend browsing over to the leaflet-locate repository and reading the documentation, that covers the .locate() method that you can trigger yourself, like $('a.somelink').click(function() { locateControl.locate(); });


text:
Q: Teradata CLOB object How to have a hyperlink column in the teradata table if i select the hyper link column the it has to be redirected to that link,
How to insert record in CLOB object
Thanks
Vinoth.B


text:
Q: sox: Split audio on silence but keep silence I've got multiple audiobooks that are stored in large mp3s. And I'm trying to split these large mp3s into multiple smaller files.
I've found a tool that can detect silence in audio files and split audio files based on this "delimiter".
Here is an example:
sox -V3 audiobook.mp3 audiobook_part_.mp3 \
silence 1 0.5 0.1% 1 0.5 0.1% : newfile : restart

This will basically split audiobook.mp3 into audiobook_part_001.mp3, audiobook_part_002.mp3, ... where silence >= 0.5 seconds.
Now the problem is that this command not only splits the file but it also removes the silence.
Therefore when you play the new files in a playlist the tracks/paragraphs sound squeezed together.
So how do you tell sox to only split the file but to keep the silence (at the end of each track)?

A: You can preserve all the silences in the split parts with some small changes. Starting with your original command:
silence 1 0.5 0.1%   1 0.5 0.1%

The first triplet of values means removes silence, if any, at the start until .5 seconds of sound above .1%.  The second triplet means stop when there is at least .5 seconds of silence below .1%.  The rest of your command, : newfile : restart, then starts a new output file and begins again to look for sound at the start.  So the first file ends when the silence begins, and the second file will start when the silence ends.
The simplest option available to improve this is silence -l. It will preserve the .5 seconds of silence that triggered the end of file.  Unfortunately, any longer silence will be removed because it is the start of the next file.  An easy way to keep a longer gap is to combine -l with a longer detection time, eg 2 seconds:
silence -l  1 0.5 0.1%   1 2.0 0.1%

You will now only split if there is at least 2 seconds of silence, but you will preserve the first 2 seconds of the gap.
To avoid losing all silence, simply remove the detection of silence at the start. You need to replace the triplet by a single 0:
silence -l  0   1 2.0 0.1%

If you want to play with simple sound files to see how sox handles situations, you can easily create 2 sound files, one consisting of 1 second of a tone, and one consisting of 1 second of silence, then join them together as you wish before presenting the result as input to the silence effect. For example, create:
sox -n gap.wav   trim 0 1
sox -n tone.wav  synth 1.001t sine C5

then join gap-tone-gap-tone and create out.wav using your effect and listen to the result:
sox gap.wav tone.wav gap.wav tone.wav out.wav silence 1 0.5 0.1%
play out.wav

A: I would use sox pad to add back silence to the beginning and end of each split file. At the end, it won't be a single sox command that does everything in a single go, but it's much more straight forward, and gives you some extra control such as choosing the length of padded silence.
See this answer on how to use sox pad. E.g.
files="*.wav"
for f in $files
do
  sox "$f" "${f%.*}-pad.wav" pad 2 3
done


text:
Q: Symplectic equivalent of commuting matrices It is well known what happens if two real symmetric matrices commute, i.e. if we have two matrices $A$ and $B$ such that $A=A^T$, $B=B^T$ and $AB=BA$. The answer is given in terms of diagonalization: there is a unitary matrix $M$ such that $A$ and $B$ are transformed into $A'=M^TAM$ and $B'=M^TBM$, and both $A'$ and $B'$ are diagonal.
Here I'm asking if any analogous property holds in the following case.
$A$ and $B$ are symmetric, i.e. $A=A^T$ and $B=B^T$. The following property holds:
$$A\Omega B=B\Omega A$$ (1)
where $\Omega$ is the matrix defining the symplectic bilinear form (skew-symmetric, nonsingular, and hollow), e.g.:
$$\Omega = \begin{bmatrix}0 & 0 & 1 & 0\\0 & 0 & 0 & 1\\
-1 & 0 & 0 & 0 \\ 0 & -1 & 0 & 0 \end{bmatrix}$$
The allowed transformations are the symplectic matrices $M$, i.e. matrices for which the following holds:
$$M^T\Omega M=\Omega$$
The transformed matrices are $A'=M^TAM$ and $B'=M^TBM$.
My question is if there is a form into which $A'$ and $B'$ can be put, by means of a suitable $M$, provided that Eq.1 holds.

A: Let $A$ and $B$ be complex symmetric matrices of even dimension which satisfy condition $(1)$ and for which $\Omega A$ and $\Omega B$ are diagonalizable. Then $\Omega A$ and $\Omega B$ are Hamiltonian (not (anti)symmetric as my comment said):
$$\Omega^\top (\Omega A)^\top \Omega=-\Omega A^\top\Omega^\top\Omega=-\Omega A.$$
Condition $(1)$ means that $\Omega A$ and $\Omega B$ commute. By Lemma 17 in the paper in Carlo's answer, there's a symplectic $S$ such that $S^{-1}\Omega AS=D$ and $S^{-1}\Omega BS=E$ are diagonal. Hence $S^\top AS=-\Omega D$ and $S^\top BS=-\Omega E$ are of the same form.

A: The symplectic counterpart of the fact that a family of commuting diagonalizable matrices is simultaneously diagonalizable is discussed in section 3.1 of On the diagonalizability of a matrix by a symplectic equivalence, similarity or congruence transformation

A: I see that the answer of MTyson requires making an additional
assumption, i.e., that $A\Omega$ and $B\Omega$ are diagonalizable, in
addition to the conditions described in the question. It is possible
that the conditions described in the question are too generic, hence they does not lead to any interesting form for $A$ and $B$. Here, I discuss a
different additional condition, that is more relevant for my
interests. However, I thank the other users who posted interesting
answers and suggestions!
The additional condition is that one of the two matrices, $A$ or $B$,
is positive definite. Moreover, I will assume that both $A$ and $B$
are invertible; actually, the case of singular matrices can be easily
handled in a similar (but longer) way and its discussion does not add
too much.
First, I follow the suggestion of Richard and I write $\Omega$ as:
$$ \Omega =
   \begin{bmatrix}
   0 & 1 &  & & \cdots \\
  -1 & 0 &  &  \\
    &  & 0 & 1 &\\
    &  & -1 & 0 & \\
    \vdots & & & & \ddots
   \end{bmatrix}.
$$
I claim that the two matrices $A$ and $B$ can be written as diagonal
block matrices:
\begin{gather*}
A =
\begin{bmatrix}
  \lambda_1 C_1 & & & \\
  & \lambda_2 C_2 & & \\
  & & \lambda_3 C_3 & \\
  & & & \ddots
\end{bmatrix}
\\
B =
\begin{bmatrix}
  C_1 & & & \\
  & C_2 & & \\
  & & C_3 & \\
  & & & \ddots
\end{bmatrix},
\end{gather*}
where $C_i$ are symmetric square $2n_i\times 2n_i$ matrices, and $\lambda_i$ and
$2n_i$ are the eigenvalues and their multiplicities, respectively, of
the matrix $P=B^{-1}A$. Btw, it is important to notice that $P$ is diagonalizable and all the eigenvalues have even (multiple of 2) multiplicity.
Proof
I call $P=B^{-1}A$. From the fact that one of the two $A$ and $B$ is positive definite, $P$ is diagonalizable.
I define $Q=-B^{-1}A\Omega$. It can be easily shown that $Q$ is antisymmetric, $Q=-Q^T$. Thus:
$$ P = Q\Omega = B^{-1}A $$
is both the product of two antisymmetric matrices ($Q$ and $\Omega$) and two symmetric matrices ($B^{-1}$ and $A$).
This ensures that the eigenvalues, $\lambda_i$, have even multiplicity, $2n_i$.
It can easily be shown that:
$$ P \Omega P^T \Omega = \Omega P^T \Omega P $$
This condition is called $\phi_J$-normality in the paper "On the diagonalizability of a matrix by a symplectic equivalence, similarity or congruence transformation" cited by Carlo Beenakker. Together with the condition that $P$ is diagonalizable, from the same paper we conclude that $P$ is symplectically similar to a diagonal matrix:
$$ P = M^{-1} D M $$
where $M$ is symplectic.
This can be rewritten as:
$$ \tilde{B}^{-1}\tilde{A} = D $$
where $\tilde{A}=M^T A M$ and $\tilde{B}=M^T B M$.
$$ \tilde{A} = \tilde{B} D.$$
It can be noticed that $\tilde{A}$ and $\tilde{B}$ are symmetric. Thus:
$$ \tilde{B} D = D \tilde{B}.$$
Since $\tilde{B}$ commutes with a diagonal matrix, and is symmetric, it has the
block structure of the thesis. $\tilde{A}$ is then calculated as $ \tilde{A} = \tilde{B} D$.

A: It is not too difficult to prove (if I made no mistakes) that, under the further hypothesis added by Doriano in his answer, i.e. that one of the two matrices, say $A$, is positive definite (the invertibility of $B$ is not necessary), then the two real simmetric matrices $A$ and $B$ satisfying (1) can actually be simultaneously diagonalized by means of a real symplectic matrix $M$. This can be so chosen that the transformed matrices have the form $A'=\text{diag} (a_1, a_1, a_2, a_2, \dots, a_n, a_n)$, $B'=\text{diag} (b_1, b_1, b_2, b_2, \dots, b_n, b_n)$, with $a_i>0\ \forall\ i=1,\dots, n$.


text:
Q: How to best write a SQL SPROC to clone table rows but changing select fields Let's say I have the following table
fID Field1  Field2
1   a       dennis
1   f       mac
2   j       clownbaby
1   k       charlie
3   t       frank
7   d       dee

and I want to take all the rows with 1 in the first column and insert them in the same table with a number I could pick as an argument to my stored procedure.
So that if I called my stored procedure as rowClone(1,8) I would end up with a table with
fID Field1  Field2
1   a       dennis
1   f       mac
2   j       clownbaby
1   k       charlie
3   t       frank
7   d       dee
8   a       dennis
8   f       mac
8   k       charlie

A: Create Procedure RowClone(@fIDToClone int, @newFID int)
As
Insert Table(fID, Field1, Field2)
Select @newFID, Field1, Field2
From Table
Where fID = @fIDToClone

You will probably want to add an additional check that ensures that the routine does not create duplicates. However, you did not mention what unique keys exist on the table.


text:
Q: Postgresql: Query to know which fraction of the values are larger/smaller I would like to query my database to know which fraction/percentage of the elements of a table are larger/smaller than a given value.
For instance, let's say I have a table shopping_list with the following schema:
   id   integer
 name   text
price   double precision

with contents:
id       name  price
 1     banana      1
 2       book     20
 3    chicken      5
 4  chocolate      3

I am now going to buy a new item with price 4, and I would like to know where this new item will be ranked in the shopping list. In this case the element will be greater than 50% of the elements.
I know I can run two queries and count the number of elements, e.g.:
-- returns = 4
SELECT COUNT(*)
FROM shopping_list;

-- returns = 2
SELECT COUNT(*)
FROM shopping_list
WHERE price > 4;

But I would like to do it with a single query to avoid post-processing the results.

A: if you just want them in single query use UNION
SELECT COUNT(*), 'total'
FROM shopping_list
UNION
SELECT COUNT(*),'greater'
FROM shopping_list
WHERE price > 4;

A: The simplest way is to use avg():
SELECT AVG( (price > 4)::float)
FROM shopping_list;

A: I found the aggregate function PERCENT_RANK which does exactly what I wanted:
SELECT PERCENT_RANK(4) WITHIN GROUP (ORDER BY price)
FROM shopping_list;
-- returns 0.5

A: One way to get both results is as follows:
select count(*) as total,
    (select count(*) from shopping_list where price > 4) as greater
from shopping_list

It will get both results in a single row, with the names you specified. It does, however, involve a query within a query.


text:
Q: Можно ли программно добавлять новые item в res/values/ids.xml? Пробую программно создавать вьюхи в коде. Возникла потребность в задании определенного ID для каждой вью. Почитал вот такую статью:
https://stackoverflow.com/questions/3216294/programmatically-add-id-to-r-id
Вот, к примеру, есть у меня
res/values/ids.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <item name="my_edit_text_1" type="id"/>
    <item name="my_button_1" type="id"/>
    <item name="my_time_picker_1" type="id"/>

</resources>

Как добавить туда программно новый ID??

A: Нет. Программно добавлять новые ресурсы нельзя.
ID - это число типа int. Вы можете использовать любое число в качестве идентификатора ваших вьюшек.
Например, определив его как константу:
    public static final int MY_ID = 100;

Вы  можете создавать вьюшки так:
    for (int i=0;i<1000;i++) {
            View view = new View(context);
            view.setId(MY_ID + i);
            layout.addView(view);
    }

И затем искать так:
    layout.findViewById(MY_ID+58);


text:
Q: How to smooth the movement of the camera? There is such a code for the camera -
cam.transform.Rotate (-cameraRotation);

Thus, I try to smooth the movement of the camera -
var orgRotation = this.transform.rotation.eulerAngles;
cameraRotation = Vector3.Lerp (orgRotation, cameraRotation, 5);
cam.transform.Rotate (-cameraRotation);

cameraRotation is the x-axis (mouse).
But Lerp does not work, so I did not fix the time, why?

A: Lerp is basically used to lerp between two values
You have done two things wrong.
First you are changing cameraRotaion value though it should be the final value which you have to go. Use a temp variable for instead.
Second you have to put the value between 0 to 1 in third parameter where you used 5 which will be considered as 1. It work on percentage 0 means starting value 1 means ending value.
So you have to use it on Update function or in a Coroutine where you have to check if final rotation reached and stop that.


text:
Q: JavaFX - Unique scene per stage I have a class that extends Application and calls the primary stage. This primary stage has a Next Button, that will call another stage (options stage). The options stage has a Previous Button.
I'd like to get the instance of the primary stage, in the state it was before the user clicked Next Button, for example: a textfield with input data or combobox with selected item.
How can I do that?
Main class:
public class MainClass extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {

        final FXMLLoader loader = new FXMLLoader(getClass().getResource("interfaceOne.fxml"));
        final Parent root = (Parent)loader.load();
        final MyController controller = loader.<MyController>getController();

        primaryStage.initStyle(StageStyle.TRANSPARENT);
        primaryStage.getIcons().add(new Image(getClass().getResourceAsStream("icon.png")));

        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        Platform.setImplicitExit(false);

        controller.setStage(primaryStage);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}
MyController:
public class MyController{

    // Some declarations ...

    Stage stage = null;

    public void setStage(Stage stage) {
       this.stage = stage;
    }

    // Next button's action
    @FXML
    public void handleNextAction(ActionEvent event) {

        try {

            Parent root = FXMLLoader.load(getClass().getResource("optionInterface.fxml"));

            stage.initStyle(StageStyle.TRANSPARENT);
            stage.getIcons().add(new Image(getClass().getResourceAsStream("icon.png")));
            stage.setScene(new Scene(root));
            stage.show();

            // Hide the current screen
            ((Node)(event.getSource())).getScene().getWindow().hide();

        } catch (Exception exc) {
            System.out.println("Error: " + exc.getMessage());
        }
    }
}

Options Controller:
public class OptionsController implements Initializable {

    public void handlePreviousAction(ActionEvent event) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("interfaceOne.fxml"));;
            MyController controller = MyController.getInstance();

            stage.initStyle(StageStyle.TRANSPARENT);
            stage.getIcons().add(new Image(getClass().getResourceAsStream("icon.png")));
            stage.setScene(new Scene(root));

            controller.setStage(stage);
            controller.isLocationLoaded(false);
            stage.show();

            // Hide the current screen
            ((Node)(event.getSource())).getScene().getWindow().hide();

        } catch (IOException exc) {
            System.out.println("Error: " + exc.getMessage());

        }
    }
}

A: Recommended Approach
Don't use multiple stages for this, instead use a single stage and multiple scenes or layered Panes.
Sample References

*

*Angela Caicedo's sophisticated Scene switching tutorial.

*A wizard style configuration.

Background
Read over a discussion of the theater metaphor behind JavaFX to help understand the difference between a Stage and a Scene and why you want to probably be changing scenes in and out of your application rather than stages.
Simple Sample
I created a simple sample based upon your application description which just switches back and forth between a main scene and an options scene.  As you switch back and forth between the scenes, you can see that the scene state is preserved for both the main scene and the options scene.
For the sample, there is just a single stage reference, which is passed to the application in it's start method and the stage reference is saved in the application.  The application creates a scene for the main screen and another for the options screen, saving both scene references switches the currently displayed scene back and forth between these references as required using stage.setScene.
The demo is deliberately simple to make it easy to understand and does not persist any of the data used or make use of a MVC style architecture or FXML as might be done in a more realistic demo.

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;

public class RoomReservationNavigator extends Application {
  public static void main(String[] args) { Application.launch(args); }

  private Scene mainScene;
  private Scene optionsScene;
  private Stage stage;

  @Override public void start(Stage stage) {
    this.stage = stage;
    mainScene    = createMainScene();
    optionsScene = createOptionsScene();

    stage.setScene(mainScene);
    stage.show();
  }

  private Scene createMainScene() {
    VBox layout = new VBox(10);
    layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 10;");
    layout.getChildren().setAll(
      LabelBuilder.create()
        .text("Room Reservation System")
        .style("-fx-font-weight: bold;")
        .build(),
      HBoxBuilder.create()
        .spacing(5)
        .children(
          new Label("First Name:"),
          new TextField("Peter")
         )
        .build(),
      HBoxBuilder.create()
        .spacing(5)
        .children(
          new Label("Last Name:"),
          new TextField("Parker")
         )
        .build(),
      new Label("Property:"),
      ChoiceBoxBuilder.<String>create()
        .items(FXCollections.observableArrayList(
          "The Waldorf-Astoria",
          "The Plaza",
          "The Algonquin Hotel"
        ))
        .build(),
      ButtonBuilder.create()
        .text("Reservation Options  >>")
        .onAction(new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent t) {
            stage.setScene(optionsScene);
          }
        })
        .build(),
      ButtonBuilder.create()
        .text("Reserve")
        .defaultButton(true)
        .onAction(new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent t) {
            stage.hide();
          }
        })
        .build()
    );

    return new Scene(layout);
  }

  private Scene createOptionsScene() {
    VBox layout = new VBox(10);
    layout.setStyle("-fx-background-color: azure; -fx-padding: 10;");
    layout.getChildren().setAll(
      new CheckBox("Breakfast"),
      new Label("Paper:"),
      ChoiceBoxBuilder.<String>create()
        .items(FXCollections.observableArrayList(
          "New York Times",
          "Wall Street Journal",
          "The Daily Bugle"
        ))
        .build(),
      ButtonBuilder.create()
        .text("Confirm Options")
        .defaultButton(true)
        .onAction(new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent t) {
            stage.setScene(mainScene);
          }
        })
        .build()
    );

    return new Scene(layout);
  }
}


text:
Q: Java OutOfMemoryError with ArrayList> I want to create a very large graph (with ~10 million edges) in Java. I plan to List<List<Integer>> to describe the edges, with the inside List<Integer> describing the two vertices of each edge (and the vertices are Integer type).
The following code throws the OutOfMemoryError after about 1 million edges are added to the graph. (I simplified how the edge is generated for the sake of discussion.)
public static void main(String[] args) {
  List<List<Integer>> graph = new ArrayList<List<Integer>>();
  for (int i = 0; i < 10000000; i++) {
    List<Integer> edge = new ArrayList<Integer>();
    // the real edges are more complicated (than from vertex i to vertex i+1)
    // this is simplified for the sake of the discussion here
    edge.add(i);
    edge.add(i+1);
    graph.add(edge);
  }
}

I have searched for OutOfMemoryError, and I have increased the initial heap size to 2G for Eclipse: -Xms2g -Xmx4g -Xss2m (which get passed to JVM). But that did not solve the problem.
Then I thought maybe I should garbage collect the List<Integer> edge variable, by calling System.gc(), in case its memory does not get cleared. That did not work either.
I was thinking maybe the problem is with the List<List<Integer>> data structure. I tried List<int[]>, which lasted a bit longer: more edges are added before OutOfMemoryError happens. I do not have a better idea right now.
I have searched around for similar problems, but have not find much help. I wonder if anyone has experience with this kind of situation.

A: To let your program use more memory from Eclipse:
Go to Run -> Run Configurations. You will see this window

Click on Arguments

Enter your arguments to the VM

A: Since you are using a lot of RAM besides setting the max heap parameter, make sure you use 64-bit Java. The 32-bit is limited to 2 Gigs or something like that.
Also, for large graphs you should consider using a database.
And last but not least, maybe you can rethink your algorithm, sometimes you just don't need all the nodes and edges.


text:
Q: Operations with empty set in python returning null set b = set([j-i for j in set([1,2,3,4,5]) for i in set() if j-i>=0])

print b

Output:
set()

Why does this expression return an empty set instead of returning set([1,2,3,4,5]) or raising an Error?

A: for i in set() is iterated zero times, leading to an empty set.

A: Because you are iterating over zero items.  Unrolling the loops makes it clearer:
result = set()
for j in set([1,2,3,4,5]):
    for i in set():   #  <-- there are no i's !
        if j - i >= 0:
            result.add(j - i)

The code path to add to the result set can never be reached.


text:
Q: I keep getting "Ran out of input" error in for() function to open and adjust pickle file I was making stock data MACD calculator in python. The way of my approach is using 'for()' to access pickle datas in certain directory and calculate MACD values one by one. However, I got 'Ran out of input error' everytime. I checked my directory where pickle datas are stored and it was not empty. Funny thing is, If I just put numbers in i position without using 'for()', I could get data of the pickle file. Please help me to get free from this error.
Here's my code:
'''
import pickle
import os
import pathlib
from pathlib import Path

file_list = os.listdir('/home/sejahui/projects/pickle_data')
os.chdir('/home/sejahui/projects/pickle_data')

for i in range(2):
    odd = file_list[i]
    with open(odd,'rb') as stock:
        data = pickle.load(stock)
    print(data)

'''

A: In this case, actually, you create a list with file_list = os.listdir('/home/sejahui/projects/pickle_data'). You do not need range to iterate.
The error is because sometimes there is only 1 file so it will be out of the index. The correct way is like this:
import pickle
import os
import pathlib
from pathlib import Path

file_list = os.listdir('/home/sejahui/projects/pickle_data')
os.chdir('/home/sejahui/projects/pickle_data')

for str in file_list:

    with open(str,'rb') as stock:
        data = pickle.load(stock)
    print(data)

You can even add an if statement to the filter based on a regex or pattern
if str == "something":
    with open(str,'rb') as stock:
        data = pickle.load(stock)


text:
Q: EOFException while reading an object I get an EOFException when I'm trying to send an object through a server socket in Java.
This is the code on the sending part:
public static void sendObject(Object Object, InetAddress IP, int Port){
    try{
        Socket receivingSocket = new Socket(IP, Port);
        OutputStream OS = receivingSocket.getOutputStream();
        ObjectOutputStream OOS = new ObjectOutputStream(OS);

        OOS.writeObject(Object);
        OOS.close();
        OS.close();
        receivingSocket.close();
    }
    catch(Exception e){
        System.err.println("Failed to send object to: " + IP + " on port: " + Port);
        System.err.println(e);
    }
}

I tried casting the object to the specific object and that didn't work.
The problem actually shows up on the receiving side which looks like this:
public Downloader(int PortStart, int PortStop, Loading_State loading_state){
    this.loading_state = loading_state;

    for(int i = PortStart;i<PortStop;i++){
        try {
            SS = new ServerSocket(i);
            break;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public void run(){
    try {
        S = SS.accept();
        IS = S.getInputStream();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    while(!destroy){
        while(active){
            try {
                OIS = new ObjectInputStream(IS);
                Character Char = (Character)OIS.readObject();
                loading_state.setChar(Char);
                pause();
            }
            catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

So when I initiate the download the console immediatly spits out:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at input_output.network.Downloader.run(Downloader.java:68)

Edit: The object does implement Serializeable
public class Character implements Serializable{
private static final long serialVersionUID = -6390272842934614484L;

BIG EDIT!:
I dont know why or how but I think the download works BUT now it can't cast the received object to my object!
Character Char = (Character)OIS.readObject();
java.lang.ClassCastException: server.database.account.Character cannot be cast to database.Character

Any ideas why?

A: Is your object serializable? The object should implement serializable interface:
class MyClass implements Serializable {
}

A: You're only sending one object, yet you are looping expecting to read multiple objects. That doesn't make sense. Either send more objects or only read one. If you send and read multiple objects you will always get an EOFException when you go to read one more than was sent.

A: Two things,

*

*While loop should cover entire run method( i believe so seeing the code)

*Since its infinite loop, which could collect empty inputs , you should handle that as well.
public void run(){
while(!destroy){

    while(active){
        try{
            S = SS.accept();
            IS = S.getInputStream();
            if(IS!=null && IS.available()>0){
                OIS = new ObjectInputStream(IS);
                Character Char = (Character)OIS.readObject();
                loading_state.setChar(Char);
                pause();
            }
        }
        catch(Exception e){  ..}
    }
}

}

A: I solved it!
First problem was that I sent a request at the same time as I started the thread to download (I think) so what I did was I send the request a little bit later and suddenly the EOF facepalm exception was gone...
Now I had the convert exception left and the problem there was that I had to have the class (object) character in the exact same package hierarchy as the sender cause java is stupid.
Thanks for the help!