text:
Q: Finding real world reference points on assessor's map This is probably a very basic question, but I don't even know the right terms to use to start searching for what I need. I'm new to this, but I want to learn.
I have the following assessor's map, and I am trying to reference it to the real world so that I can approximately survey the boundaries of a particular lot on block 052. What reference point(s) can I use as starting point?
It seems like the blocks were originally divided into 25 ft by 125 ft lots, and the current parcels are legally described in reference to those lots.

A: I think your best bet would be to use QGIS and the "Parcels" dataset available from the San Diego GIS Data Warehouse:
SANGIS
You will need an account, but it is easy enough to set up. Took me 5mins.
Once you have downloaded the data, you can add the Zip file directly into QGIS  by dragging and dropping it.
All you need to do is then find your area of interest (easy enough using Google Earth and the QGIS Base maps).
Google Earth:

QGIS with Basemap:

Adding the parcels, you can see the common points between your diagram and the parcel dataset (Look at the meeting of the parcel boundaries in the middle).
You can add a Georeferencer Tool to QGIS via the Plugins menu -> Manage and Install Plugins (search for Georeferencer) and Georeferencer GDAL will popup.
Install and you will find the tool under the "Raster" menu.
select Georeferencer and a new window will pop-up. Add your raster  to this window and hit the play button. You will be asked a few questions - Just select an output SRS and file name, leave everything else for now. Hit ok.
Next add a point a new window will pop-up and you can select Use map canvas, then select the common point on the map. You can see below that red dots are added everytime you do this.

Repeat this process at least 3 more times and try to get a spread across the raster - try for each corner and maybe the middle. When you done, his the "Play" button again. You should see a "Successful" ribbon popup in the Georeferencing window.
You can then add the gereferenced image to QGIS.


text:
Q: Bad request in Springboot custom filter When ever I try to get the request body inside the springboot filter (in order to check some parameters) a BAD request error is thrown
Here's the code for the filter
public class PostURLFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;

        InputStream requestInputStream = req.getInputStream();
        try {
            String body = StreamUtils.copyToString(requestInputStream, StandardCharsets.UTF_8);
            out.println(body + "this is the body");

        } catch (Exception e) {
            out.println(e);
        }

        out.println("end");

        filterChain.doFilter(servletRequest, servletResponse);

    }
}

This is my POST request body
{
       "id":590,
       "name":"run"
}

Without this piece of code (requesting the request body) the POST request works fine. But with this it doesn't run.
I don't know where I'm missing the login. Kindly help me. Thanks in advance!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change a prop on a styled component and update appearance I'm very new to styled components (and I'm not great with React in general) and I can't quite get my head around them. I've created a basic example which is an abstraction of what I want to achieve. When I click on the box, I want the property on to be changed to true and for the colour of <Box> to be updated to green as per the background-color rule.
How do I achieve this? Especially in the instance where there could be an indeterminate number of boxes?
Component
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

const Box = styled.a`
    display: block;
    height: 100px;
    width: 100px;
    background-color: ${props => props.on ? 'green' : 'red' };
`;

Box.propTypes = {
    on: PropTypes.bool,
    onClick: PropTypes.func,
}

Box.defaultProps = {
    on: false,
    onClick: () => {},
}

export default Box;

Implementation
<Box on={ false } onClick={ }></Box>

A: You would handle the state in its parent component. For example you could do something like this:
class Page extends Component {
  state = { on: false }

  handleClick = () => {
    this.setState(prevState => ({ on: !prevState.on }));
  }

  render() {
    return <Box on={this.state.on} onClick={this.handleClick} />
  }
}

Or even simpler using React hooks:
const Page = () => {
  const [on, setOn] = useState(false);
  return <Box on={on} onClick={() => setOn(on => !on)} />;
};

Here's an example of what you could do if you wanted 10 boxes
(note: creating the onClick handler in the render method like I did could cause performance issues if you have a very large number of boxes)
class Page extends Component {
  state = { boxes: Array(10).fill(false) }

  handleClick = (index) => {
    this.setState(prevState => ({
      boxes: [
        ...prevState.boxes.slice(0, index),
        !prevState.boxes[index],
        ...prevState.boxes.slice(index)
      ]
    }));
  }

  render() {
    return (
      <React.Fragment>
        {this.state.boxes.map((on, index) =>
          <Box on={on} onClick={() => this.handleClick(index)} />
        )}
      </React.Fragment>
    );
  }
}

A: // App.js
import React from "react";
import ReactDOM from "react-dom";
import Test from "./Test";

class App extends React.Component {
  state = {
    on: false
  };
  handleChange = () => {
    this.setState(prevState => ({ on: !prevState.on }));
  };
  render() {
    return (
      <div className="App">
        <Test on={this.state.on} onClick={this.handleChange}>
          Hey
        </Test>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

// Test.js
import PropTypes from "prop-types";
import styled from "styled-components";

const Box = styled.a`
  display: block;
  height: 100px;
  width: 100px;
  background-color: ${props => (props.on ? "green" : "red")};
`;

Box.propTypes = {
  on: PropTypes.bool,
  onClick: PropTypes.func
};

Box.defaultProps = {
  on: false,
  onClick: () => {}
};

export default Box;


text:
Q: Isomorphisms between groups, and order Hi first time posting here, I am self studying group theory and came upon the following exercise:
Let G=(Z/612Z)*
a) using the Chinese rem theorem, construct an EXPLICIT isomorphism
f: (Z/4Z)*x(Z/9Z)x(Z/17Z) -> G=(Z/612Z)*
b) Calculate |G| and m=max{ord(x) : x is an element of G}
c) Using the first two parts, gind g element of G s.t ord(g)=m
For part a, how is the given isomorphism not explicit? What would be an explicit one? For parts b,c could someone provide a solution with explanation, or give me some hints?
Thanks

A: An "explicit" isomorphism means that if your are given $(a,b,c)$ you can calculate (explicitely) $f(a,b,c)$. For your information the chinese remainder theorem says that the explicit function :
$$\frac{\mathbb{Z}}{612\mathbb{Z}}\rightarrow  \frac{\mathbb{Z}}{4\mathbb{Z}}\times \frac{\mathbb{Z}}{9\mathbb{Z}}\times \frac{\mathbb{Z}}{17\mathbb{Z}}$$
$$x\mapsto (x\text{ mod } 4,x\text{ mod } 9,x\text{ mod } 17)$$
is an isomorphism (because $612=4\times 9\times 17$ and $4$, $9$ and $17$ are prime to each other). Finding the explicit isomorphism $f$ boils down to give the inverse function of the function above. Since $f$ is a ring isomorphism $f(a,b,c)=af(1,0,0)+bf(0,1,0)+cf(0,0,1)$, you basically only need to compute $f(1,0,0)$, $f(0,1,0)$ and $f(0,0,1)$. For instance $f(1,0,0)$ is a number divisible by both $9$ and $17$ so $f(1,0,0)=153y$, now mod $4$ this number is $y$ so $y=1$ is okay. Hence $f(1,0,0)=153$. For $f(0,1,0)=68y$ which is $5y$ mod $9$ so that $y$ must be the inverse of $5$ modulo $9$ which happens to be $2$ so $f(0,1,0)=136$. Finally $f(0,0,1)=36y$ which is $2y$ mod $17$ so that if $y=9$ then $f(0,0,1)=324$.
Hence $f(a,b,c)=153a+136b+324c$ is the explicit form. Just restrict it to the group of multiplicative inverses to get the wanted isomorphism.
For question $b$ it is easier to look at the order of elements in the group  $G'=  \frac{\mathbb{Z}}{4\mathbb{Z}}^*\times \frac{\mathbb{Z}}{9\mathbb{Z}}^*\times \frac{\mathbb{Z}}{17\mathbb{Z}}^*$ (a by-product of the chinese remainder theorem is precisely that $G$ and $G'$ are isomorphic so you can answer question $b$ in $G'$ rather than in $G$, it is easier). Show that each group in the product is cyclic (by explicitely giving a generating element). Deduce from this the number $m$ you are looking for.
For question $c$ when doing question $b$ you will find the $m$ by explicitely giving an element $(a_0,b_0,c_0)$ of $  \frac{\mathbb{Z}}{4\mathbb{Z}}^*\times \frac{\mathbb{Z}}{9\mathbb{Z}}^*\times \frac{\mathbb{Z}}{17\mathbb{Z}}^*$ whose order is maximal, then use question $a$ to give the corresponding element in $\frac{\mathbb{Z}}{612\mathbb{Z}}^*$.


text:
Q: JxBrowser speculative execution side channel Spectre vulnerability Is JxBrowser impacted by the recent speculative execution Spectre vulnerabilities as JxBrowser is based on Chromium? If so, what steps can users take to resolve the vulnerability?
Chromium guidance can be found at
https://www.chromium.org/Home/chromium-security/ssca
https://support.google.com/faqs/answer/7622138

A: Unfortunately, Site Isolation feature that is mentioned in the Google answer is not supported by JxBrowser and cannot be used to mitigate exploitation of these vulnerabilities in the current version, which is based on Chromium 60.
Right now, we are working on upgrading to Chromium 64. This update will be available in one of the following versions of JxBrowser.


text:
Q: Compute p-value of single value in arbitrary distribution (using java and apache.commons.math3) I want to compute the p-value of a single numeric value drawn from an arbirtary distribution.
The p-value should be comparable to p-values that have been computed with single distinict values drawn from sets (using the Chi-Square Test).
The distribution of the numeric data is propbably mostly normal distributed, but can sometimes be uniform or log distributed.
My application is a dataset that has numeric and distinct features. I want to rank the features for one particular instance according to the p-value of corresponding feature value compared with all values in the dataset of this feature.
I tried using the densitiy of EmpiricalDistribution, this is however no p-value:
    String all[] = { "a", "a", "a", "a", "a", "a", "b", "b", "b", "b", "c", "c" };
    String selected[] = { "c" };
    //-> converted to counts
    long countsAll[] = { 6, 4, 2 };
    long countsSelected[] = { 0, 0, 1 };
    System.out.println(TestUtils.chiSquareTestDataSetsComparison(countsAll, countsSelected));

    double allNumeric[] = { 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7 };
    double selectedNumeric = 5;
    EmpiricalDistribution dist = new EmpiricalDistribution(1);
    dist.load(allNumeric);
    System.out.println(dist.density(selectedNumeric));

The best I came up with was binning the numeric data and using the ChiSquare test as well.
Thanks for your help!

A: The p-value of a $\chi^2$ is done through a lower incomplete gamma. $$CDF(\chi^2( df, x )) = \frac{1}{\Gamma(\frac{df}{2})}.\gamma( \frac{df}{2}, \frac{x}{2})$$ where $df$ is the degrees of freedom and $x$ the $\chi^2$-statistic.
If you are asking for the p-value of the empirical distribution it simply the ratio of the bins in the histogram to the left/right versus all the bins.
There are plenty of algorithms out there for p of the $\chi^2$. Here is one I have used (it is C/C++ but easily tranformed to Java). Ignore the df check I put in there - it is something I required for my data.
/*************************************************************************
Chi-square distribution

Returns the area under the left hand tail (from 0 to x)
of the Chi square probability density function with
v degrees of freedom.

                                  x
                                   -
                       1          | |  v/2-1  -t/2
 P( x | v )   =   -----------     |   t      e     dt
                   v/2  -       | |
                  2    | (v/2)   -
                                  0

where x is the Chi-square variable.

The incomplete gamma integral is used, according to the
formula

y = chdtr( v, x ) = igam( v/2.0, x/2.0 ).

The arguments must both be positive.

ACCURACY:

See incomplete gamma function

Cephes Math Library Release 2.8:  June, 2000
Copyright 1984, 1987, 2000 by Stephen L. Moshier
*************************************************************************/
double getChiSqPValue(int df, double testSt) const
{
    if(df < 2)
    { return(-1.0); }

    double result = incompleteGamma(df/2.0, testSt/2.0);
    return(result);
}

/*************************************************************************
Incomplete gamma integral

The function is defined by

                          x
                           -
                  1       | |  -t  a-1
 igam(a,x)  =   -----     |   e   t   dt.
                 -      | |
                | (a)    -
                          0

In this implementation both arguments must be positive.
The integral is evaluated by either a power series or
continued fraction expansion, depending on the relative
values of a and x.

ACCURACY:

                     Relative error:
arithmetic   domain     # trials      peak         rms
   IEEE      0,30       200000       3.6e-14     2.9e-15
   IEEE      0,100      300000       9.9e-14     1.5e-14

Cephes Math Library Release 2.8:  June, 2000
Copyright 1985, 1987, 2000 by Stephen L. Moshier
*************************************************************************/

double incompleteGamma(double a, double x) const
{
    double igammaepsilon;
    double ans;
    double ax;
    double c;
    double r;
    double tmp;
    double result;

    igammaepsilon = 0.000000000000001;
    if( x < 0 || a < 0 )
    {
        result = 0;
        return result;
    }
    if( x > 1 && x > a )
    {
        result = 1.0 - incompleteGammaC(a, x);
        return result;
    }
    ax = a*log(x)-x-lngamma(a);
    if( ax < -709.78271289338399 )
    {
        result = 0;
        return result;
    }
    ax = exp(ax);
    r = a;
    c = 1;
    ans = 1;
    do
    {
        r = r+1;
        c = c*x/r;
        ans = ans+c;
    }
    while(c/ans > igammaepsilon);
    result = ans*ax/a;
    return result;
}

/*************************************************************************
Complemented incomplete gamma integral

The function is defined by

 igamc(a,x)   =   1 - igam(a,x)

                           inf.
                             -
                    1       | |  -t  a-1
              =   -----     |   e   t   dt.
                   -      | |
                  | (a)    -
                            x

In this implementation both arguments must be positive.
The integral is evaluated by either a power series or
continued fraction expansion, depending on the relative
values of a and x.

ACCURACY:

Tested at random a, x.
               a         x                      Relative error:
arithmetic   domain   domain     # trials      peak         rms
   IEEE     0.5,100   0,100      200000       1.9e-14     1.7e-15
   IEEE     0.01,0.5  0,100      200000       1.4e-13     1.6e-15

Cephes Math Library Release 2.8:  June, 2000
Copyright 1985, 1987, 2000 by Stephen L. Moshier
*************************************************************************/
double incompleteGammaC(double a, double x) const
{
    double igammaepsilon;
    double igammabignumber;
    double igammabignumberinv;
    double ans;
    double ax;
    double c;
    double yc;
    double r;
    double t;
    double y;
    double z;
    double pk;
    double pkm1;
    double pkm2;
    double qk;
    double qkm1;
    double qkm2;
    double tmp;
    double result;

    igammaepsilon = 0.000000000000001;
    igammabignumber = 4503599627370496.0;
    igammabignumberinv = 2.22044604925031308085*0.0000000000000001;
    if( x <= 0 || a <=0 )
    {
        result = 1;
        return result;
    }
    if( x < 1 || x< a )
    {
        result = 1-incompleteGamma(a, x);
        return result;
    }
    ax = a*log(x)-x-lngamma(a);
    if( ax < -709.78271289338399 )
    {
        result = 0;
        return result;
    }
    ax = exp(ax);
    y = 1-a;
    z = x+y+1;
    c = 0;
    pkm2 = 1;
    qkm2 = x;
    pkm1 = x+1;
    qkm1 = z*x;
    ans = pkm1/qkm1;
    do
    {
        c = c+1;
        y = y+1;
        z = z+2;
        yc = y*c;
        pk = pkm1*z-pkm2*yc;
        qk = qkm1*z-qkm2*yc;
        if( qk != 0 )
        {
            r = pk/qk;
            t = abs((ans-r)/r);
            ans = r;
        }
        else
        {
            t = 1;
        }
        pkm2 = pkm1;
        pkm1 = pk;
        qkm2 = qkm1;
        qkm1 = qk;
        if( abs(pk) > igammabignumber )
        {
            pkm2 = pkm2*igammabignumberinv;
            pkm1 = pkm1*igammabignumberinv;
            qkm2 = qkm2*igammabignumberinv;
            qkm1 = qkm1*igammabignumberinv;
        }
    }
    while(t > igammaepsilon);
    result = ans*ax;
    return result;
}

/*************************************************************************
Natural logarithm of gamma function

Input parameters:
    X       -   argument

Result:
    logarithm of the absolute value of the Gamma(X).

Output parameters:
    SgnGam  -   sign(Gamma(X))

Domain:
    0 < X < 2.55e305
    -2.55e305 < X < 0, X is not an integer.

ACCURACY:
arithmetic      domain        # trials     peak         rms
   IEEE    0, 3                 28000     5.4e-16     1.1e-16
   IEEE    2.718, 2.556e305     40000     3.5e-16     8.3e-17
The error criterion was relative when the function magnitude
was greater than one but absolute when it was less than one.

The following test used the relative error criterion, though
at certain points the relative error could be much higher than
indicated.
   IEEE    -200, -4             10000     4.8e-16     1.3e-16

Cephes Math Library Release 2.8:  June, 2000
Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
Translated to AlgoPascal by Bochkanov Sergey (2005, 2006, 2007).
*************************************************************************/
double lngamma(double x) const
{

    double a;
    double b;
    double c;
    double p;
    double q;
    double u;
    double w;
    double z;
    int i;
    double logpi;
    double ls2pi;
    double tmp;
    double result;

    double sgngam = 1.0;
    logpi = 1.14472988584940017414;
    ls2pi = 0.91893853320467274178;
    if( x < -34 )
    {
        q = -x;
        w = lngamma(q);
        p = floor(q);
        i = floor(p+0.5);
        if( i%2==0 )
        {
            sgngam = -1;
        }
        else
        {
            sgngam = 1;
        }
        z = q-p;
        if( z > 0.5 )
        {
            p = p+1;
            z = p-q;
        }
        z = q*sin(PI*z);
        result = logpi-log(z)-w;
        return result;
    }
    if( x < 13 )
    {
        z = 1;
        p = 0;
        u = x;
        while( u >= 3)
        {
            p = p-1;
            u = x+p;
            z = z*u;
        }
        while( u <2 )
        {
            z = z/u;
            p = p+1;
            u = x+p;
        }
        if( z < 0 )
        {
            sgngam = -1;
            z = -z;
        }
        else
        {
            sgngam = 1;
        }
        if( u ==2 )
        {
            result = log(z);
            return result;
        }
        p = p-2;
        x = x+p;
        b = -1378.25152569120859100;
        b = -38801.6315134637840924+x*b;
        b = -331612.992738871184744+x*b;
        b = -1162370.97492762307383+x*b;
        b = -1721737.00820839662146+x*b;
        b = -853555.664245765465627+x*b;
        c = 1;
        c = -351.815701436523470549+x*c;
        c = -17064.2106651881159223+x*c;
        c = -220528.590553854454839+x*c;
        c = -1139334.44367982507207+x*c;
        c = -2532523.07177582951285+x*c;
        c = -2018891.41433532773231+x*c;
        p = x*b/c;
        result = log(z)+p;
        return result;
    }
    q = (x-0.5)*log(x)-x+ls2pi;
    if( x > 100000000 )
    {
        result = q;
        return result;
    }
    p = 1/(x*x);
    if( x > 1000.0 )
    {
        q = q+((7.9365079365079365079365*0.0001*p-2.7777777777777777777778*0.001)*p+0.0833333333333333333333)/x;
    }
    else
    {
        a = 8.11614167470508450300*0.0001;
        a = -5.95061904284301438324*0.0001+p*a;
        a = 7.93650340457716943945*0.0001+p*a;
        a = -2.77777777730099687205*0.001+p*a;
        a = 8.33333333333331927722*0.01+p*a;
        q = q+a/x;
    }
    result = q;
    return result;
}


text:
Q: Problem recompiling using make command I'm trying to modify some C++ files in ns2 and then recompile using make command. Although new .o file is created after make, the output is similar to that of previous C++ file (before modifying). Can someone suggest what may be the reason behind it?

A: Are you modifying .cpp (or .C .cc etc.) files or header files? Some Makefiles are written very poorly and don't have decent dependency information (gcc -MMD or makedepend). This means the project is not rebuild correctly if you modify some files (often header files). You can check what files are triggered by modification (and why) with the command:
make --debug=b -n


text:
Q: Pusher on route not sending event in Laravel I am creating a test app using Pusher for real-time notification on Laravel 4.
As I am testing the said API, I am having difficulties on making it work.
I have this on my routes.php:
Route::get('pusher-test', function(){
    return View::make('pages.test');
});
Route::any('test', function(){
        $pusher = new Pusher('key','sect','app_key'); //my keys are correct.
        $pusher->trigger('notificationChannel', 'userRegistration', []);
});

Then my pusherTest.js file:
(function(){
    var pusher = new Pusher('key');
    var channel = pusher.subscribe('notificationChannel');
        channel.bind('userRegistration', function(data){
            $('.test').append('HEY!');
        });
})();

My view page:

        <meta charset="utf-8">
        {{ HTML::style('_/css/bootstrap.css') }}
        {{ HTML::style('_/css/mystyle.css') }}

HI!

        {{ HTML::script('_/js/bootstrap.js') }}
        {{ HTML::script('_/js/jquery.js') }}
        {{ HTML::script('_/js/pusher/pusher.min.js')}}
        {{ HTML::script('_/js/pusherTest.js')}}

When I try to observe the Debug Console of my app on Pusher.com,
here's what I see:

But when I hit the test route, it is not sending an event on my Pusher app, neither it sends the API message to my client. But if I will use the Create new Event tester on debug console, sure enough it sends the API message and my client receives and updates it.

What do you think is happening why on my route it can't send the event to my pusher app? I can't figure it out because is has no exception error. Please advice.

A: for me it was because I used the eu server and laravel is configured automatically on us server

A: To expand on @adutu's answer, you need to set
'cluster' => 'eu'

Inside the 'options' section of the Pusher driver configuration, in broadcasting.php.

A: There are three points at which you can debug your integration with Pusher:

*

*Your interactions with Pusher's HTTP (REST) API

*Ensuring events are being received by Pusher using the Pusher Debug Console

*Ensuring your client integration is working by checking pusher-js logging

In your situation you've done 2. and you can see the events you are triggering aren't reaching the debug console. So, you need to do 1.
The Pusher PHP Server library provides details of how to enable debugging:
https://github.com/pusher/pusher-php-server#debugging
And how to get log information from the library:
https://github.com/pusher/pusher-php-server#logging
Once you have the pusher-php-server library logging information please feel free to post it so we can see what the problem may be e.g. are you getting a non 2xx response code?

A: The issue with this is due to the fact that you cannot set the host for the pusher broadcasting.
You only get this issue when you are using the EU cluster, in which case, you should change the host to:
api-eu.pusher.com

Similarly, you can make a custom broadcast driver. that does the same thing as the default one but sets the host parameter.

I am going to suggest an edit to the illuminate broadcast manager to make this change easier to make.


text:
Q: Where do I get or find the PublicKeyToken for the latest version of Entity Framework? I am upgrading from EF 6.0 to EF 6.1. The actual EF dll version is 6.1.30225.0. When I upgrade via NuGet, this is the dll version I see. After the upgrade, I am still seeing references in project files to EntityFrameworkSection Version=6.0.0.0 in my config files (app.config, web.config, etc).
Do I need to update these references as well? If so, what version for 6.1.30225.0? 6.1.3.0 or just 6.1.0.0? Do I need a new PublicKeyToken?
Thanks for the help!

A: They are still 6.0.0.0 So, you dont have to update them. :)
Good luck!


text:
Q: Showing that a polynomial is primitive. Show that $f(x)=x^2+x+3 \in \mathbb{Z}_7$ is a primitive polynomial.
I have shown that it is irreducible but I am unsure how to show that it is primitive. Any help would be great.

A: Let $F = \mathbb{Z}_7[x] / \left< f(x) \right> $ represented as degree-$1$ polynomials in $\alpha$. $|F^*| = 48$.
Now all you have to do is prove that $o(\alpha)=48$. $48=2^4 \cdot 3$, so all you have to show is that $\alpha^{24} \ne 1$ and $\alpha^{16} \ne 1$. I would recommend repeated squaring:
$$\alpha^2 = 6\alpha + 4$$
$$\alpha^4 = 5\alpha + 6$$
$$\alpha^8 = 3$$
And it's easy from here.
(I used this calculator, which you might find useful for such computations, but it's not hard at all to square these by hand if you need to on a test.)


text:
Q: Why is Stokes theorem not applicable / not used correctly in this case? I am doing some exercises and I don't understand what is wrong with my solution here.
The problem is: given the integral $$ I = \int_S (1 + x^2) f(x) dydz - 2xy f(x) dz dx - 3z dx dy$$
Find such a continuously differentiable function $f$ such that the integral $I$ is equal for all surfaces $S$, whose border is a circle $ C := \{ (\cos t, \sin t, 1) \; | \; t \in [0, 2 \pi ] \}$ and then calculate the integral $I$.
My thinking is that any function that is defined everywhere and $C^1$ should be alright! Let's denote $\overrightarrow{R}$ the vector field over which we are integrating. For any well defined $C^1$ function $f(x)$, field $\overrightarrow{R}$ will be well defined and $C^1$. Then by Stokes theorem we have:
$$ \int_S rot \overrightarrow{R} d\vec{S} = \int_{\partial S} \overrightarrow{R} d \vec{r}$$
where $\partial S = C$, which is a fixed number, so the integral on the left will be equal for every surface $S$ with the same border.
However, the  solution uses Gauss's theorem instead and shows that the sufficient condition is that $div \overrightarrow{R} = 0$. It also states (without proof) that this condition is also necessary.
To sum up, I would appreciate if you help me figure out

*

*What is wrong with my reasoning using Stokes theorem?

*How to show that $div \overrightarrow{R} = 0$ is a necessary condition?

A: The expression in a chart for a differential 1-form (using Einstein conv.) looks like:
$$\omega = \omega_idx^i$$
$$\implies d\omega  = d\omega_i \wedge dx^i = \partial_j\omega_idx^j\wedge dx^i.$$
For $n=3$, we have (invoking multilinearity and skew-symmetry of $\wedge$) that:
$$d\omega = (\partial_x\omega_idx\wedge dx^i)+(\partial_y\omega_idy\wedge dx^i) + (\partial_z\omega_idz\wedge dx^i)$$
$$= \bigg(\partial_x\omega_1dx\wedge dx+\partial_x\omega_2dx\wedge dy+\partial_x\omega_3dx\wedge dz\bigg)+\bigg(\partial_y\omega_1dy\wedge dx+\partial_y\omega_2dy\wedge dy+\partial_y\omega_3dy\wedge dz\bigg)+\bigg(\partial_z\omega_1dz\wedge dx+\partial_z\omega_2dz\wedge dy+\partial_z\omega_3dz\wedge dz\bigg)$$
$$= (\partial_x\omega_2-\partial_y\omega_1)dx\wedge dy + (\partial_y\omega_3-\partial_z\omega_2)dy\wedge dz+(\partial_x\omega_3-\partial_z\omega_1)dx\wedge dz$$
$$= (\partial_y\omega_3-\partial_z\omega_2)dydz+(\partial_z\omega_1-\partial_x\omega_3)dzdx+(\partial_x\omega_2-\partial_y\omega_1)dxdy.$$

Since we have:
$$d\omega := (1+x^2)f(x)dydz-2xyf(x)dzdx-3zdxdy$$
Combinining with the above gives a system that $\omega$ satisfies:
$$(i)\text{ }\partial_y\omega_3 - \partial_z\omega_2 = (1+x^2)f(x)$$
$$(ii)\text{ } \partial_z\omega_1 - \partial_x\omega_3 = -2xyf(x)$$
$$(iii)\text{ } \partial_x\omega_2 - \partial_y\omega_1 = -3z$$

Now, bear with me as I proceed to find (a) solution to this system (not claiming uniqueness). If we assume that:
$$\omega_3 \equiv 0,$$
then (i) and (ii) simplify to:
$$\partial_z\omega_2 = -(1+x^2)f(x)$$
$$\partial_z\omega_1 = -2xyf(x)$$
Integrating these with respect to $z$ gives:
$$\omega_1 = -2xyzf(x)+G_1(x,y)$$
$$\omega_2 = -z(1+x^2)f(x)+G_2(x,y)$$
where $G_i(x,y)$ are constants of integration w.r.t. $z$.
Let's assume these vanish identically as well. Then combining these results with (iii) gives:
$$\partial_x\omega_2 - \partial_y\omega_1 = -z[2xf(x)+(1+x^2)f'(x)] +2xzf(x)$$
$$=-z(1+x^2)f'(x) = -3z$$
Assuming $z\neq 0$ and $x\neq i$ gives:
$$f'(x) = \frac{3}{1+x^2}$$
Or equivalently:
$$f(x) = 3tan^{-1}(x)+C.$$
This is a good reaffirmation of the exactness discussion!
Take $C=0$.

Putting this all together gives (a) primitive:
$$\omega = (-6xyz\cdot tan^{-1}(x))dx+(-3z(1+x^2)\cdot tan^{-1}(x))dy$$
Provided $z\neq 0$ (which won't matter over $C$).

Finally, in your application of Stoke's Theorem:
$$I = \int_Sd\omega = \int_{\partial S = C}\omega$$
So dump in the parameterization for $C$ $\bigg($i.e. $(x,y,z)(t) = (cos(t),sin(t),1)\bigg)$ for $t\in [0,2\pi]$ and the result will follow!


text:
Q: divide the width of the screen between elements in relative layout? Let's say I have a button and an EditText, aligned at the same height(the bottom of the screen) and sharing the width of the screen. I want the button to take just the space it needs, and the editText to cover the rest of the width.
Up until now I've been using a linearLayout, where in this case I could put those two elements inside an horizontal linear layout, set the weight of the editText to 1 and the with of the button to wrap_content, and it would work.
However, I am not able to replicate this behaviour using a relative layout. I can put the editText at the bottom of the parent, and then set the button to its right, but I don't know how to make the editText fill the rest of the width respecting the button's space.
What's the correct way to do it?
Edit: this is what I have so far:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/edittext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:hint="@string/editText_Hint"
        android:inputType="number" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignRight="@id/edittext"
        android:onClick="sendAnswer"
        android:text="@string/button_text" />

</RelativeLayout>

And I want to replicate the behaviour of this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

   /*other stuff here*/

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/edittext"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="@string/editText_Hint"
            android:inputType="number"
            android:layout_weight="1"
           />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_text"
            android:onClick="sendAnswer"/>
    </LinearLayout>
</LinearLayout>

A: Try this, aligning the button right of the button and setting the width of the edittext to match_parent works fine for me.
<RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/button1"
        android:ems="10" >

        <requestFocus />
    </EditText>
</RelativeLayout>

Doing so the edittext looks as if goes till the border. To have better look add some margin to the right of the edittext using the attribute android:layout_marginRight="5dp"
UPDATE
If your requirement is to use the parent layout to be Relative Layout, the best solution for you to use a nested layout.
Use a LinearLayout nested within the Relative layout with its alignment android:layout_alignParentBottom="true" to the LinearLayout.
Sample given below,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" >

        <EditText
            android:id="@+id/editText1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />

    </LinearLayout>

</RelativeLayout>

A: I found a solution myself. The trick was to set both elements at the bottom, then the edit text to width:0dp, alignParentLeft and toLeftOF the button (NOT alignLeft of the button, but toLeftOF the button). The button should be alignedto parent right and parent bottom.
The final code looks like this:
<EditText
        android:id="@+id/edittext"

        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_toLeftOf="@id/button"
        android:layout_alignParentLeft="true"
        android:hint="@string/editText_Hint"
        android:inputType="number"
        android:layout_width="0dp"
       >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:onClick="sendAnswer"
        android:text="@string/button_text" />


text:
Q: Grey Line on Windows Explorer, Windows 7 I noticed yesterday when I hovered my mouse over a part of windows ezplorer, there was a small grey line, where the explorer toolbar normally goes. However over the line shows this cursor:

This is the line in the question, the images I found on another stack exchange question.

I know this my might be seem like a duplicate but I didnt find the answer on the other similar question.
Is this a default line on Windows 7? I set a system restore up and found system restore effects this bar. I did a restore to about 3 days ago, and the bar was still there, so its obviously been here before I noticed.
Another machine with oem hp windows 7 doesnt have this line. Can other software change how this line appears?
Just like to point out these images came from another superuser question.

A: It is in fact  default on my installation
HKCU/software/Microsoft/Internet Explorer/Toolbar

I exported it as a text file, and the key
Name: Locked Type: REG_DWORD  Data 0x00000000 (0)

Was last writtren/modified at the date of installation. If I lock the toolbar, it changes to
0x00000000 (1)

Thanks everyone!


text:
Q: SIM 800 GPRS modem for HTTP GET and POST to AWS IoT and AWS API gateway I was trying to POST and GET some JSON data to and from the AWS cloud respectively using the SIM 800 module. I'm initially trying it out directly from my PC over a terminal UART software and inputting AT commands in manually.
HTTP GET is working fine over SSL (AT+HTTPSSL=1) for websites like Google and Quora, as in, they return back <html> data.
1) I looked into first going through the AWS IoT route using HTTP as mentioned in the link here. But it requires not only a single certificate for HTTP SSL but also requires the root CA certificate and the private key and I guess it is not possible to add these apart from a single certificate using AT commands on the SIM 800. If there is a way to do so then can anyone please elaborate on it like the process flow and commands to do so?
2) I then tried to go the API route. I created an API gateway in AWS which is internally linked with some cloud logic. I want to actually do HTTP POST (https technically) of JSON data to the AWS cloud but I created a test API gateway for HTTP GET which does the addition of operands written in the URL and sends back data in the form of JSON. An HTTP GET over SSL however to a URL like https://XXXX.execute-api.us-west-2.amazonaws.com/XXX/calc/4/2/+ fails with a 606 error code. In the SSL application note of SIM 800 606 error code means

"SSL alert message with a level of fatal result in the immediate
  termination of the connection"

What am I doing wrong over here?
Also, I tried HTTP GET over SSL on https://httpbin.org/ip too and got the same 606 error. Is it because the SIM 800 expects an <html> and instead it gets JSON or is it something else?
For my AT command routine on the SIM 800 from the PC via Terminal software I usually do (for API gateway method):
AT+SAPBR=3,1,"CONTYPE","GPRS"
AT+SAPBR=3,1,"APN","XXXX"
AT+SAPBR=1,1
AT+HTTPINIT
AT+HTTPSSL=1
AT+HTTPPARA="CID",1
AT+HTTPPARA="URL","https://XXXX.execute-api.us-west-2.amazonaws.com/XXX/calc/4/2/+"
AT+HTTPACTION=0

Thanks in advance.

A: I have the same issue. AWS requires TLS1.2 while the Simcom only permits TLS1.0.

A: Microsoft Azure has recently upgraded TLS requirements with the effect that "If a client tries to negotiate TLS 1.0 over such a scenario, the request will fail with connection reset". This explains why my application now fails as the SIM800 module only supports TLS 1.0.
AWS may have done the same.  It seems that there is an ongoing move to deprecate TLS 1.0 and according to SSL and TLS, what is the Big Deal About June 30th? 30 June 2018 is the cutoff date at which point TLS 1.0 will not be supported if you want to claim PCI compliance.

A: The way to do it is method 2 i.e. API Gateway. I don't think its possible to do it through method 1 i.e. AWS IoT.
@mich and @patrick-fischer are correct with the reason and I too was suspecting the same but didn't know the solution. I and my team contacted AWS support and they told us the solution.
Apparently, you do it through AWS CloudFront. You have to go and create a CloudFront distribution with the link of your API Gateway (in my case https://XXXX.execute-api.us-west-2.amazonaws.com/XXX/calc/4/2/+). While creating this distribution you can mention whether to accept incoming HTTP, HTTPS or both.
In one of the sections (don't remember the name of the section), it allows you to mention which TLS/SSL version to allow incoming requests from. In the case of SIM 800, TLSv1.0 is the highest supported version which has to be set in the CloudFront distribution.
What CloudFront does is allow traffic from sources with certain parameters like the version of HTTP, TLS version .etc.

A: I am trying generating an custom domain in AWS Api Gateway and select TLS 1.0, to activate you need it of an AWS ACM certificate and DNS confirmation in AWS Route S3 (Take some time to activate), here exist some info: https://vintage-kitchen.com/es/faq/faq-how-long-does-aws-certificate-manager-take/ (This option is visualized here: https://i.stack.imgur.com/RVO7y.png), with this you can execute an HTTP POST Request from AT Commands via GPRS to a AWS Lambda for example.


text:
Q: Skip where clause based on condition from collection in Laravel I want to write a collection in which i put multiple where clause. But depending on some conditions i want to execute some where clause and skip some of them. Thanks in advance.

A: You can use the when() method.
https://laravel.com/docs/5.7/queries#conditional-clauses
For example:
DB::table('products')
->when($request->active, function($query) {
    $query->where('active','=',true);
})
->when(isset($request->category), function($query) use ($request) {
    $query->where('category','=', $request->category);
})
->get();


text:
Q: Get points for voting From time to time I'll find a good answer to a programming question on StackO via Google, but in my rush to solve my current problem I'll forget to upvote the answer.
I was thinking maybe users could get a few points for upvoting stuff.  This seems like it would be a good incentive:  People are more likely to upvote, thus improving the filtering mechanism and people who post good questions and answers get bigger rewards.
Maybe it could be implemented via a sort of "investment" scheme.  If I upvote a question/answer and later that question gets a bunch more upvotes, then I could a bonus for each upvote that came after mine.
You could stick a cap on number of upvotes per minute/hour/day to keep people from voting blindly.
edit:  Wow, lots of downvote rage.  Please actually read my suggestion and responses to the knee-jerk objections before downvoting.  I seriously think this would be a good idea.

A: With few exceptions, you don't "earn" reputation by giving it to yourself. In other words, the only way to earn reputation is to provide good content… and have it awarded to you.
If the act of clicking 'up-vote' gave you reputation, that would throw off the whole balance. The person who ran through this system clicking gimme-two-points, gimme-two-points, gimme-two-points, gimme-two-points, gimme-two-points would have earned just as much reputation as someone having their post up-voted by a peer.
That's not what reputation is designed to measure.

A: A main problem I see with this is that it will introduce more bias into voting.  We already have a penalty for downvoting.  Adding this will actually accentuate the penalty since you will be losing the 2 rep plus 2 potential rep.  We don't need more reasons to have our votes skewed in favour of upvoting in my opinion.
The other main problem is gaming the system for rep, though that has the potential to be countered.

A: I'm a big fan of voting, and frequently hit the voting cap (30 per day) on Super User.  I'm also the #1 voter on SU, with 5K+ votes cast.
Imagine what would happen to my rep if I got points for voting! (it would explode).  Voting is pretty easy to do, and would be a rather mindless and easy way to earn rep.  This wouldn't be fair to those who have actually earned the rep in other ways, by asking and answering questions...
Also, it would allow users to exploit the Stack Exchange system, by simply voting everyday (regardless of a cap), which would eventually allow them privileges, for doing NOTHING on the site, but simply pressing an arrow here and there, they don't even have to put any thought into it!  How fair is that?

A: If this would actually help people vote conscientiously, I think it would be a great idea. However, anyone could simply vote as many times as possible each day to earn the maximum rep from voting. It would cause both rep inflation and vote inflation.


text:
Q: Comparing two tables, if rows are different, run query in Oracle Think of my two tables have the same columns. One column is the ID, and the other one is the text. Is it possible to implement the following pseudo code in PLSQL?
Compare each row (They will have the same ID)
    If anything is different about them
        Run a couple of queries: an Update, and an Insert
    ElseIf they are the same
        Do nothing
    Else the row does not exist
        So add the row to the table compared on

Is it easy to do this using PLSQL or should I create a standalone application to do do this logic.

A: As your table have the same columns, by using NATURAL JOIN you can easily check if two corresponding rows are identical -- without need to update your code if a column is added to your table.
In addition, using OUTER JOIN allow you to find the rows present in one table but not in the other.
So, you can use something like that to achieve your purpose:
for rec in (
    SELECT T.ID ID1,
           U.ID ID2,
           V.EQ
           FROM T
           FULL OUTER JOIN U ON T.ID = U.ID
           FULL OUTER JOIN (SELECT ID, 1 EQ FROM T NATURAL JOIN U) V ON U.ID = V.ID)
loop
    if rec.id1 is null
    then
        -- row in U but not in T
    elsif rec.id2 is null
    then
        -- row in T but not in U
    elsif rec.eq is null
        -- row present in both tables
        -- but content mismatch
    end if
end loop

A: Else the row does not exist
    So add the row to the table compared on

Is this condition means that rows can be missed in both tables? If only in one, then:
insert into t1 (id, text)
select id, text
from t2
minus
select id, text
from t1;

If missed records can be in both tables, you need the same query that inserts into table t2 rows from t1.
If anything is different about them

If you need one action for any amount of different rows, then use something like this:
select count(*)
into a
from t1, t2
where t1.id = t2.id and t1.text <> t2.text;
if a > 0 then
   ...

otherwise:
for i in (
    select *
    from t1, t2
    where t1.id = t2.id and t1.text <> t2.text) loop

  <do something>

end loop;

A: A 'merge' statement is what u needed.
Here is the syntax:
MERGE INTO TARGET_TABLE
USING SOURCE_TABLE
ON (CONDITION)
WHEN MATCHED THEN
UPDATE SET (DO YOUR UPDATES)
WHEN NOT MATCHED THEN
(INSERT YOUR NEW ROWS)

Google MERGE syntax for more about the statement.

A: Just use MINUS.

query_1
MINUS
query_2

In your case, if you really want to use PL/SQL, then select count into a local variable. Write a logic, if count > 0 then do other stuff.


text:
Q: Python, code works, but openning via bat file get error Following is a simple working GUI programm. However, when I try to open it from a bat file, it gives an error.
Bat file (2 lines):
ch10.2.py
pause

The error I receive is:
[error message in text format to be included here]
My code:
# Lazy Buttons 2
# Demonstrates using a class with Tkinter

from tkinter import *

class Application(Frame):
    """ A GUI application with three buttons. """
    def __init__(self, master):
        """ Initialize the Frame. """
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """ Create three buttons that do nothing. """
        # create first button
        self.bttn1 = Button(self, text = "I do nothing!")
        self.bttn1.grid()

        # create second button
        self.bttn2 = Button(self)
        self.bttn2.grid()
        self.bttn2.configure(text = "Me too!")

        # create third button
        self.bttn3 = Button(self)
        self.bttn3.grid()
        self.bttn3["text"] = "Same here!"

# main
root = Tk()
root.title("Lazy Buttons 2")
root.geometry("200x85")
app = Application(root)
root.mainloop()

A: It's giving error on super(Application, self).__init__(master).
If you replace with Frame.__init__(self, master) , its working.
See below
# Lazy Buttons 2
# Demonstrates using a class with Tkinter

from tkinter import *

class Application(Frame):
    """ A GUI application with three buttons. """

    def __init__(self, master):
        """ Initialize the Frame. """
        Frame.__init__(self, master)
        #super(Application, self).__init__(master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        """ Create three buttons that do nothing. """
        # create first button
        self.bttn1 = Button(self, text = "I do nothing!")
        self.bttn1.grid()

        # create second button
        self.bttn2 = Button(self)
        self.bttn2.grid()
        self.bttn2.configure(text = "Me too!")

        # create third button
        self.bttn3 = Button(self)
        self.bttn3.grid()
        self.bttn3["text"] = "Same here!"

# main
root = Tk()
root.title("Lazy Buttons 2")
root.geometry("200x85")
app = Application(root)
root.mainloop()

OUTPUT


text:
Q: Filling up a TreeView control I have a N-Ary non sorted in any way tree and each node can have 0-N children. Given the data structure below, how can I fill the tree view assuming you have an array of TermNodes and that array is the first level of the TreeView? I have not been able to come up with a recursive way to do this.
class TermNode
{
   public string Name;
   public string Definition;
   public List<TermNode> Children
}

A: Here is a bit of code to get you started with the recursion. It's not tested (I can't right now), but you should get the idea:
public static void BuildTreeView(TreeNodeCollection Parent, List<TermNode> TermNodeList)
{
  foreach (TermNode n in TermNodeList)
  {
    TreeNode CurrentNode = Parent.Add(n.Name);
    // no need to recurse on empty list
    if (n.List.Count > 0) BuildTreeView(CurrentNode.Nodes, n.List);
  }
}

// initial call
List<TermNode> AllTermNodes = /* all your nodes at root level */;

BuildTreeView(treeView1.Nodes, AllTermNodes);

A: Just took out Generics for a spin.. Worked nicely. Worth a look at...
public interface INode<T>
{
    List<T> Children { get; }
}
class TermNode:INode<TermNode>
{
   public string Name;
   public string Definition;
   public List<TermNode> Children { get; set; }
   public TermNode()
   {
       this.Children = new List<TermNode>();
   }
}

public class TreeBuilder<T> where T : INode<T>
{
    public Func<T, TreeNode> obCreateNodeFunc;

    public void AddNode(TreeView obTreeView, T obNodeToAdd, TreeNode obParentNodeIfAny)
    {
        TreeNodeCollection obNodes;
        if (obParentNodeIfAny == null)
        {
            obNodes = obTreeView.Nodes;
        }
        else
        {
            obNodes = obParentNodeIfAny.Nodes;
        }
        int iNewNodeIndex = obNodes.Add(obCreateNodeFunc(obNodeToAdd));
        TreeNode obNewNode = obNodes[iNewNodeIndex];

        foreach (T child in obNodeToAdd.Children)
        {
            AddNode(obTreeView, child, obNewNode);
        }
    }
}

// calling code - Some class
    static TreeNode GetTreeNodeFor(TermNode t)
    {
        return new TreeNode(t.Name);  // or any logic that returns corr TreeNode for T
    }

    void Main()...
    {
       TermNode[] arrNodesList;
       // populate list with nodes

       TreeBuilder<TermNode> tb = new TreeBuilder<TermNode>();
       tb.obCreateNodeFunc = GetTreeNodeFor;
       foreach (TermNode obNode in arrNodesList)
       {
           tb.AddNode(treeView, obNode, null);
       }
    }

A: Thanks All I was getting confused because I did not realize that for a given TreeNode tn, tn.Nodes.Add would return the added TreeNode
Once you know that the solution is straight forward like so
private void /*TreeNode*/ RecursiveAdd(OntologyNode on, TreeNode tn)
{
    if (on.Children.Count == 0)
    {
        return;
    }
    foreach (OntologyNode child in on.Children)
    {
        TreeNode tCur = tn.Nodes.Add(child.Name);
        tCur.Tag = child;//optional for some selected node events
        RecursiveAdd(child, tCur);
    }
 }

and to start of the recursive call
foreach( OntologyNode on in Nodes )
 {
     if (on.IsTopLevelNode == true)// internal not pertinent to this code snippet
     {
          TreeNode tn = tvOntoBrowser.Nodes.Add(on.Name);
          tn.Tag = on;
          if (on.Children.Count > 0)
          {
               RecursiveAdd(on, tn);
          }
     }

  }


text:
Q: How do I use sessions to display a popup after Nth page? I have a popup from Survey Monkey but it pops up straight away. That's not really any use for anyone as research about a user's experience of a website relies on the user having used the website for at least a few minutes.
I want to run this code only on the Nth (let's say 7th) page on that session to the site. So only after a user has delved deeper into a site will they be requested to fill out a survey.
I'm a novice but I know that javascript resets on every pageload/refresh so that on its own seems to be out for using setTimeout.
I was thinking if I could somehow track number of pages using a session then only load the javascript when number of pages viewed = x then it would solve the problems but not really sure where to start?
Any ideas would be greatly appreciated, the script for the popup is below:

  (function(t,e,n,s){var c,o,l;t.SMCX=t.SMCX||[],e.getElementById(s)||(c=e.getElementsByTagName(n),o=c[c.length-1],l=e.createElement(n),l.type="text/javascript",l.async=!0,l.id=s,l.src=["https:"===location.protocol?"https://":"http://","widget.surveymonkey.com/collect/website/js/surveyidnumbergoeshere.js"].join(""),o.parentNode.insertBefore(l,o))})(window,document,"script","smcx-sdk");

A: Put this code in head of your site:
session_start();
if(!isset($_SESSION['survey_counter'])
    $_SESSION['survey_counter']=1;

$showSurvey=false;
if($_SESSION['survey_counter']++ >= 7)
{
    $showSurvey=true;
    $_SESSION['survey_counter']=0;
}

and this code where you want to echo JS:
if($showSurvey) echo 'YOUR_JAVSCRIPT_CODE';


text:
Q: Node.js & Express / Can context switch between two requests can be in synchronic code? I have the following code in node.js, using Express module:
app.post('/saveDoc', function(req, res) {
    // Code to take params with req.busboy.on('field'...
    req.busboy.on('file', function(fieldname, file) {
    var correctFlags = "";
    var exists = fs.existsSync(returnFilePath(uuid) + "/" + fileFor + "_part");
     if (exists){
         correctFlags = "r+"
     }
     else{
         correctFlags = "w"
      }
      var fstream1 = fs.createWriteStream(returnFilePath(uuid) + "/" + fileFor + "_part", {start: parseInt(start), flags: correctFlags});
      file.pipe(fstream1);
      })

The purpose of this code is to write to the same file some parts of it, in different offset (write files in chunks).
I want to ensure that only one chunk of the file will create the file, and write to it offset (using "w" flag), while the others will go to the "r+" flag.
I worried of the following scenario:

*

*My server is getting 2 requests of saveDoc for returnFilePath(uuid) + "/" + fileFor + "_part"

*Then the file is not still doesn't exists, and the two are getting the 'w' flag.
This can happens if there is a context switch between the request:

*

*The first request will do the next command: var exists = fs.existsSync(returnFilePath(uuid) + "/" + fileFor + "_part"); and get false.

*context switch is done

*The second will do the command: var exists = fs.existsSync(returnFilePath(uuid) + "/" + fileFor + "_part"); and also get false.

*The result is "false" for these two request.
Is this possible? Or in my code I ensure that all be done in synchronicity way, so context switch is impossible?

A: I have a strong suspicion that this is not the correct format for what you want to do. A more structured solution, like storing your data in a database, or just something more structured like JSON, seems like a better.
That said, you can just use fs.appendFile since that will handle figuring whether to write or append.


text:
Q: Transformations of domino tilings Given a domino tiling of a rectangle, we can transform it to a new tiling by the following move: pick two dominos that share a long edge, and rotate them in place 90 degrees. Is it possible to change any domino tiling to any other domino tiling by repeating this move?

A: A generalization of this result appears in Dylan Thurston's paper "From dominoes to hexagons".

A: This is supposedly proved by Bill Thurston in his classic paper Conway's tiling groups.

Here is some more information from O. Bodini, Th. Fernique, E. Rémila, Characterizations of flip-accessibility for domino tilings of the whole plane and S. Desreux, E. Rémila, An optimal algorithm to generate tilings. To follow the explanation, please open the first paper at page 2 and look at Figure 2.
Given a domino tiling, there is a way to assign heights to vertices (right part of Figure 2). Pick your favorite $2\times 2$ rectangle covered by two dominoes. Notice that the heights of all four corners are the same, say $h$, and the point at the center has height $h \pm 2$. Moreover, the point in the center is a local extremum. The move (also called a domino flip) changes the sign: see Figure 1 on page 5 of the second paper.
Apply repeatedly the following algorithm: While the function has a local minimum, flip it into a local maximum. The algorithm increases heights of points, so must converge. Moreover, it is not hard to show that there is a unique local maximum: the corresponding heights can be determined explicitly subject to the constraints. The corresponding tiling appears in Thurston's paper, Figures 4.4 and 4.5 on pages 14 and 15 (769 and 770), respectively.
Since any tiling can be flipped into this tiling of maximal height, flips can transform any given tiling to any other given tiling.

Eric Rémila explains everything in his paper The lattice structure of the set of domino tilings of a polygon. He shows that there is a unique maximal tiling by proving that the pointwise maximum of two height functions is also a height function; he does that by showing that every edge comes from one of the tilings.
He also provides an optimal algorithm to flip from one tiling to another. This algorithm goes through the pointwise maximum of the height functions of both tilings, and changes each vertex in only one direction. Therefore the number of flips needed is exactly one fourth of the total height difference $(L_1$ distance$)$, a formula he attributes to an earlier 1995 paper, Spaces of domino tilings.
The latter paper, by Saldanha, Tomei, Casarin and Romualdo, may be the first to which proves this result. Still, usually the result is attributed to (Bill) Thurston's paper.

A: There is a more accessible proof actually, by using the Littlewood quotient map. By numbering the dominoes in a certain way, one can then produce a bijection between tilings and pairs of standard Young tableaux. Flips have a natural correspondence on these pairs, and on the set of pairs, connectivity is relatively easy to show.


text:
Q: Reactjs don't duplicate my message after update state I was following the example this blog and the question arose me after implementing
https://github.com/DanialK/ReactJS-Realtime-Chat
Summarizing, before send a message via websocket the state of messages is updated.
And when server receives that message, they send a broadcast to all clients, indluding myself.
Thereat, client updates the state with this same message
Why this message does not appear 2 times?
I don't want that message appear 2 times, but I want to know why it happens
Client code:
socket.on('send:message', this.messageRecieve);
...
handleMessageSubmit : function(message){
    Messages.push(message);
    this.setState({ messages : Messages });
    socket.emit('send:message', message);
},

messageRecieve: function(message){
    Messages.push(message);
    this.setState({ messages : Messages });
},

Server code:
socket.on('send:message', function (data) {
    socket.broadcast.emit('send:message', {
        user: name,
        text: data.text
    });
});

A: The server does not send the message to the connected user.
As per the socket.io documentation, this API sends to all but the owner of the socket:
socket.broadcast.emit('send:message')

https://github.com/DanialK/ReactJS-Realtime-Chat/blob/master/routes/socket.js


text:
Q: LINQ orderby on date field in descending order How can I change the LINQ query in the code below to sort by date in descending order (latest first, earliest last)?
using System;
using System.Linq;
using System.Collections.Generic;

namespace Helloworld
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            List<Envelops> env = new List<Envelops> ();
            Envelops e = new Envelops { ReportDate = DateTime.Now };
            env.Add (e);
            e = new Envelops { ReportDate = DateTime.Now.AddDays (5) };
            env.Add (e);
            e = new Envelops { ReportDate = new DateTime (2011, 3, 3) };
            env.Add (e);
            e = new Envelops { ReportDate = DateTime.Now };
            env.Add (e);

            foreach (Envelops r in env) {
                Console.WriteLine (  r.ReportDate.ToString("yyyy-MMM"));
            }

            var ud = (from d in env
                select  d.ReportDate.ToString("yyyy-MMM") ).Distinct();

            Console.WriteLine ("After distinct");

            foreach (var r in ud) {
                Console.WriteLine (r);
            }

        }
    }

    class Envelops
    {
        public DateTime ReportDate { get; set; }
    }

}`enter code here`

the current output is:
2011-Apr
2011-May
2011-Mar
2011-Apr
After distinct
2011-Apr
2011-May
2011-Mar

I want the output to in the following order:
may
april
march order

A: env.OrderByDescending(x => x.ReportDate)

A: This statement will definitely help you:
env = env.OrderByDescending(c => c.ReportDate).ToList();

A: I don't believe that Distinct() is guaranteed to maintain the order of the set.
Try pulling out an anonymous type first and distinct/sort on that before you convert to string:
var ud = env.Select(d => new
                         {
                             d.ReportDate.Year,
                             d.ReportDate.Month,
                             FormattedDate = d.ReportDate.ToString("yyyy-MMM")
                         })
            .Distinct()
            .OrderByDescending(d => d.Year)
            .ThenByDescending(d => d.Month)
            .Select(d => d.FormattedDate);

A: I was trying to also sort by a DateTime field descending and this seems to do the trick:
var ud = (from d in env
     orderby -d.ReportDate.Ticks
     select  d.ReportDate.ToString("yyyy-MMM") ).Distinct();


text:
Q: How to search & connect Miracast sink in my Android APP? I want to search and connect Miracast sink in my Android app.
I plan to do this like the Settings app. I download the android source code, find the \packages\apps\Settings\src\com\android\settings\wfd\WifiDisplaySettings.java
But at the beginning, Eclipse show can't import 2 packages:
import android.hardware.display.WifiDisplay;
import android.hardware.display.WifiDisplayStatus;

So, what's the problem? How can I import the 2 packages? Or is there any other implementation?

A: I have knew that those packages are used in PDK.
they cant be used in application level.
So you should compile your project with entire AOSP source.


text:
Q: Problems with positioning of text within HTML I am trying to position a paragraph between an image and bullet points. I think I have the right layout within the html but for some reason it is just not displaying correctly. See image below:

As you can see, the paragraphs appear under everything else but this is not how it is displayed within my html. See below for code:
HTML:

Plan

Objectives

Scope

Sitemap

Wireframes

Lorem ipsum dolor sit amet, porta quis urna tempor vestibulum purus, vulputate condimentum arcu faucibus aliquam enim accumsan, a nulla nullam morbi bibendum eveniet tempus, parturient consequat sociis quis. Suscipit in vitae ornare lobortis sed, porta et minima odio neque maecenas cras, justo in.

Justo arcu lacus, quos pellentesque nam sit. Luctus mauris egestas, leo nisl porttitor urna scelerisque ut, mauris sodales sapien donec dolor, arcu a ante vestibulum lorem vitae quam

CSS:
.services {
width: 100%; float: left; margin: 30px 0;
}

.services .serviceBox {
width: 898px; padding: 30px; border: 1px solid #43C0C2; background-color: white; float:     left; margin-bottom: 10px;
}

.services .serviceIcon {
float: left; margin: 0 30px 50px 0; width: 129px;
}

.serviceBullets {
float: right; font-weight: 100; width: 150px;
}

.serviceBullets li {
list-style-image: url(../images/bullet.gif); color: #43C0C2; margin-bottom: 10px;
}

.services h2 {
font-size: 40px; margin-bottom: 20px; color: #000000;
}

A: You have added Float:left to just right Div only, You need to update your left div also with following code
.serviceCopy
{
  float: left;
  width: 721px;
}

Also after 2 div you will need to add one more div to clear all floats

So that your layout won't break.

A: Are you trying to have it so that it goes
IMAGE - PLAN AND PARAGRAPH - BULLET POINTS?
Or
IMAGE - Everything else so that the image column is on the left, everything else is on the right?
IF its the former.
Try this:

Plan

Lorem ipsum dolor sit amet, porta quis urna tempor vestibulum purus, vulputate condimentum arcu faucibus aliquam enim accumsan, a nulla nullam morbi bibendum eveniet tempus, parturient consequat sociis quis. Suscipit in vitae ornare lobortis sed, porta et minima odio neque maecenas cras, justo in.

Justo arcu lacus, quos pellentesque nam sit. Luctus mauris egestas, leo nisl porttitor urna scelerisque ut, mauris sodales sapien donec dolor, arcu a ante vestibulum lorem vitae quam

Objectives

Scope

Sitemap

Wireframes

So that it has its own div and bullets are separate.
Then float all of them left. And define their widths.
Then add one more div, to clear the floats.


text:
Q: Trying to enable microphone on Bixby Studio on a Mac I'm using Bixby Studio on a Mac and can't get the mic working - I am running Mojave. I can type input in the simulator and it works great, but can't do any testing using voice input. I checked in the Security & Privacy settings to give access to the mic, but there's no entry for Bixby Studio there. I don't recall it ever asking permission to use the mic - has anyone gotten this to work or know of any workarounds?
UPDATE: I ran Bixby studio on a Windows VM on my Mac and got the Microphone input working that way - seems kind of big kludge though.


text:
Q: Using String or Long for Google App Engine Datastore Key What is the difference of GAE datastore Long id and String key in Key.
Using the Key
KeyFactory.createKey(kind, key);

KeyFactory.createKey(kind, id);

So in this case either can be used as Identifier. If I create a Key from KeyFactory.createKey(kind, key) where key is a String I can see the id field of the key is 0. In this case getId() will be 0? And in contrast, if what is set is KeyFactory.createKey(kind, someLongValue) then getName() will be a empty String?

A: An app engine Key can have EITHER a unique long ID, or a unique String name - they are mutually exclusive. If you set a long ID, the name will be null. Which you decide to use for any Entity kind really depends on your use case.
A benefit of using long IDs is that you can have app engine auto-generate them for you. That is, you can create your Entity without any value for its ID, and then when you save it it will be given a valid unique long ID by the datastore.
If you use a String name, you must create the unique name before the Entity is saved. This is useful in some cases if you have some property on the Entity that makes for a natural fit for the unique name (for example, and SKU for a part). Also, some people generate a random UUID for the String name - this ensures that all names are globally unique, not just unique among a particular Entity kind and ancestor path.


text:
Q: Search for a cell's value in another sheet, colour it, and repeat I have a workbook with two sheet. I want to take a value in sheet1 (ex: cell A1), search it in sheet2, and colour that cell or row if it matches.
I'd also like to know if this can be looped, so that it will search for the value in cell A2, A3, and so on, until it reaches a blank.
Thank you for any help.

A: No need for a loop or a Find when you have Conditional Formatting.
Option Explicit

Sub colorIt()
    With Worksheets("sheet2").UsedRange.Cells
        .FormatConditions.Delete
        .FormatConditions.Add Type:=xlExpression, _
          Formula1:="=isnumber(match(" & .Cells(1).Address(0, 0) & ", sheet1!$a:$a, 0))"
        .FormatConditions(.FormatConditions.Count).Interior.Color = vbRed
    End With
End Sub


text:
Q: disable backspace, delete button on radcheckeddropdownlist in winforms I have  radcheckeddropdownlist , I am entering check boxes dynamically and i am disabling them once the user check and save, but when i press the back and  delete button saved items are deleting , could any one suggest me how to restrict back, delete button radcheckeddropdownlist . Thanks
I have tried key press event.it didn't work kindly help me.
Inside the key press event i have written the if condition as below:
   Private Sub radchecksample_KeyUp(sender As Object, e As KeyEventArgs) Handles radchecksample.KeyUp
    If Not (Asc(e.KeyCode) = Keys.Delete Or Asc(e.KeyCode) = Keys.Back) Then
        e.Handled = True

    End If
End Sub


text:
Q: Is it OK to inject value directly inside Bean function? I was wondering how to do dependency injection in the most effective way inside my code.
I have this code:
@Configuration
public class SomeName {

    @Autowired
    private Other other;

    @Bean
    public void method() {
        other.someMethod();
        // some code
    }
}

Can this code be changed into the following code(other will be used only inside this function)?
@Configuration
public class SomeName {

    @Bean
    public void method(Other other) {
        other.someMethod();
        // some code
    }
}

A: You should avoid @Autowired if possible and inject using a constructor or method.
Starting with Java 9 and java modules (project jigsaw) there are some strict rules that make it harder for your framework to change the values of a private field.
What Spring is doing in the first example is essentially that - it breaks encapsulation to change the value of a private value. (There is a way to overcome this with "opens" directive in module-info..)
You are also becoming dependent on the framework you are using and your code becomes harder to test compared to when using a simple setter.
You are also not explicitly declaring that your class depends on another class since I can easily instantiate it and "Other" will be null.
Some resources:

*

*https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-scanning-autodetection (search for jigsaw)

*https://blog.marcnuri.com/field-injection-is-not-recommended/
PS: You are probably missing @Configuration on your class


text:
Q: Weird conflicts with Chrome I'm running 14.04. I have Chrome installed and when I try to install Redshift through the software center, I get "the following items will be removed" prompt and there are three items:
google-chrome-stable:i386

libappindicator1:i386

libindicator7:i386

I thought this was some weird isolated problem with Redshift, but now I'm trying to use Hamachi, installing with these instructions: https://help.ubuntu.com/community/Hamachi
And at the second step installing Haguchi, when I type
sudo apt-get update && sudo apt-get install haguichi

it does a bunch of stuff, but then stops and says (among other things) that the following packages will be removed, and lists the exact three packages above.
??? What's going on? How do I fix? How do I even begin to diagnose? I have no model of why this would be happening.
Edit:
uname -i

simply gives
x86_64

A: You installed a wrong version of Chrome. You have a 64-bit system, but you installed a 32-bit version of Chrome.
Uninstall Chrome by
 sudo apt-get remove google-chrome-stable:i386

Then download and install a 64-bit version.


text:
Q: Handle simultaneous get calls in angularjs My angular application is divided into 4 modules and all modules require user details so I am calling getUser method from each of the module. So when my application loads all 4 modules hit the getUser API simultaneously resulting in 4 get requests on server. How can I prevent this ? I am using singleton pattern in my getUser method so once my user gets loaded it will simply serve the user from an object. But that does not solves the problem if all modules request for the user simultaneously.
My code looks like this
getUser() {
let defer = this.q.defer();

if (!this.user) {
    this.http.get(`${this.config.apiHost}users`)
        .success(result => {
            this.user = result;

            this.rootScope.$broadcast('userFound', this.user);
            defer.resolve(this.user);
        })
        .error(err => defer.reject(err))
}
else {
    defer.resolve(this.user);
    this.rootScope.$broadcast('userFound', this.user);
}
return defer.promise;
}

A: By storing the current request in a variable the call to UserService.get will return the same request promise.
Then when the promise resolves, it will resolve to all your modules.
    angular.module('app').service('UserService', function ($http) {

    var self = this;

    var getRequestCache;

    /**
     * Will get the current logged in user
     * @return user
     */
    this.get = function () {
        if (getRequestCache) {
            return getRequestCache;
        }

        getRequestCache = $http({
            url: '/api/user',
            method: 'GET',
            cache: false
        }).then(function (response) {
            // clear request cache when request is done so that a new request can be called next time
            getRequestCache = undefined;
            return response.data;
        });

        return getRequestCache;
    };

});

A: You are using ui-router for the routing. You can then use this to resolve the user when landing on the page.
In your routing config :
$stateProvider
    .state('myPage', {
        url: '/myPage',
        templateUrl: 'myPage.html',
        controller: 'myCtrl',
        resolve: {
            userDetails: ['UserService', function(UserService) {
                return UserService.getUserDetails();
            }],
        }
    })

In your controller
angular.module('myModule')
    .controller('myCtrl', ['userDetails', function(userDetails) {
        console.log(userDetails);
        }];

This will load the user details while loading the page.

A: I solved this problem by using defer object as a global object so that it only gets initialised once.


text:
Q: how to check that phone was shut down by battery removal I have searched everywhere but no answer found, is there any way in android to check that Last shutdown was by removing battery in Android?
For example
If I just take out battery of my running phone, upon next boot is there any way to tell that phone was not shutdown properly.
I am sure there will be any flag that keep track of device is running and when we ask android to shutdown by UI it will set the flag to shutdown.

A: You can set a BroadcastReceiver which is triggered by the action android.intent.action.ACTION_SHUTDOWN.
If the device is shut down normally then it will run. If shutdown by a battery removal, then it won't. You can then write some semaphore code to suit your purposes, perhaps using another BroadcastReceiver for android.intent.action.BOOT_COMPLETED to check it on start up.


text:
Q: Split string to dictionary based on multiple delimiters Problem:
I get a cluster definition as a string. The definition contains the IP, Port and Trunk details of two interconnected applications for one or more data centers. The structure of the string is the following:
Application1 IPs and Port details: 'N' number of IPs (minimum 2) and exactly 1 port. IPs are separated with commas, while the port is separated with colon.
Application1 config is closed with a semicolon, which is followed by Application2 IPs and trunks.
On Application 2 an IP and Trunk forms a single unit. These units are separated by colons while IP and Trunk information within the units are separated by '|'
This is a sample input which contains the cluster definitions for 2 Data Centers.
cluster_params = "1.1.1.1,2.2.2.2:5002;10.10.0.1|17,10.10.0.2|18,10.10.0.3|19,10.10.0.4|20\n3.3.3.3,4.4.4.4:5003;10.10.1.1|21,10.10.1.2|22,10.10.1.3|23,10.10.1.4|24"

What I need:
I would like to split the cluster_params into a nested dictionary, something like the below sample:
clusters = { 'Cluster1_App1_port_salt': ['App1_IP1', 'App1_IP2', 'App1_IPn'],
              'App2_IPs_and_ports': ['App2_Ip1', 'App2_Port1','App2_Ip2', 'App2_Port2', 'App2_Ipn', 'App2_Portn'],
              'Cluster2_App1_port_salt': ['App1_IP1', 'App1_IP2', 'App1_IPn'],
              'App2_IPs_and_ports': ['App2_Ip1', 'App2_Port1','App2_Ip2', 'App2_Port2', 'App2_Ipn', 'App2_Portn'],}

I can split and get the required variables from the string with the below code, but can't figure out how to put it into a nested dictionary. (App1 is ICM and App2 is MPP in the below code)
import string
import random
cluster_params = "1.1.1.1,2.2.2.2:5002;10.10.0.1|17,10.10.0.2|18,10.10.0.3|19,10.10.0.4|20\n3.3.3.3,4.4.4.4:5003;10.10.1.1|21,10.10.1.2|22,10.10.1.3|23,10.10.1.4|24"

clusters =cluster_params.split('\n')
for i in clusters:
    separate_cluster=i.split(';')
    icm_config=separate_cluster[0]
    mpp_config=separate_cluster[1]
    icm_separator=icm_config.split(':')
    icm_ips=icm_separator[0]
    icm_port=icm_separator[1]
    salt=random.choice(string.ascii_lowercase)+random.choice(string.ascii_lowercase)+random.choice(string.ascii_lowercase)+random.choice(string.ascii_lowercase)
    PIM_Name='PIM_Connector_' + icm_port + '_' + salt
    mpp_separator=mpp_config.split(',')
    mpp_ip=[]
    mpp_trunk=[]
    for i in mpp_separator:
        mpp_ip.append(i.split('|')[0])
        mpp_trunk.append(i.split('|')[1])

    print('ICM_Config: ' + icm_config)
    print('Pim_Name: ' + PIM_Name)
    print('ICM_IPs: ' + icm_ips)
    print('ICM_Port: ' + icm_port)
    print('ICM_IPs ' + icm_ips)
    print('MPP_Config: ' + mpp_config)
    print( mpp_ip)
    print( mpp_trunk)

Thanks!

A: Check this out:
def salt():
    return "".join([random.choice(string.ascii_lowercase) for _ in range(4)])
apps_names = ["icm","mpp"]
clusters_dict = {}
for i,cluster in enumerate(cluster_params.split("\n")):
    salt_ = salt()
    icm,mpp = cluster.split(";")
    icm_ips,icm_port= icm.split(":")
    icm_ips=icm_ips.split(",")

    mpp_ips , mpp_trunks = [], []
    for entry in mpp.split(","):
        mpp_ip,mpp_trunk = entry.split("|")
        mpp_ips.append(mpp_ip)
        mpp_trunks.append(mpp_trunk)
    args_dict ={}
    args_dict["icm_"+str(icm_port)+"_"+salt_]=icm_ips
    args_dict["mpp_ips_and_ports"]=[mpp_ips[i]+"_"+mpp_trunks[i] for i in range(len(mpp_ips))]
    clusters_dict["cluster"+str(i+1)]=args_dict

print(clusters_dict)

output example :
{'cluster1': {'icm_5002_phua': ['1.1.1.1', '2.2.2.2'], 'mpp_ips_and_ports': ['10.10.0.1_17', '10.10.0.2_18', '10.10.0.3_19', '10.10.0.4_20']}, 'cluster2': {'icm_5003_ppkg': ['3.3.3.3', '4.4.4.4'], 'mpp_ips_and_ports': ['10.10.1.1_21', '10.10.1.2_22', '10.10.1.3_23', '10.10.1.4_24']}}


text:
Q: Developing novel association measure with t-SNE I am an MSc. student in computing and I am currently writing my thesis on radiogenomics (imaging genomics) for brain cancer research. I NEED YOUR HELP.
My supervisor and I are thinking about developing a novel tool to test association between two datasets.
Essentially, in this project, I will have two datasets: i) Gene mutations, and ii) Imaging data.
One way to find associations between the multi-view datasets is to perform Canonical Correlation Analysis (CCA). However, this has been done before and often with poor results.
So what we are thinking about is the following algorithmic approach:

*

*Reduce dimensions of both datasets using either PCA (reduction) or
random forest (selection)

*Visualise both datasets separately with
t-SNE

*Compare neighbors: Pick an ID/subject in one visualization and
find its neighbors. Then pick the same ID in the other visualisation
and see if neighbors are the same.

*Do this for all IDs

*Use some metric to assess performance. If neighbours are similar the
performance should be high.

How does this sound? More concretely:

*

*Does the overall approach make sense?

*To identify neighbors, I am thinking of using the Perplexity parameter of t-SNE (i.e. if perplexity = 30, pick 30 closest neighbours). Makes sense?

*What would be a good metric to report aggregate results for this new algorithm?

Thanks a lot!
Best,


text:
Q: SQLAlchemy / jsonpatch - how to make patch paths case-insensitive? I've been trying to find some documentation for jsonpatch==1.16 on how to make PATCH paths case-insensitive. The problem is that:
PATCH /users/123
[
    {"op": "add", "path": "/firstname", "value": "Spammer"}
]

Seems to mandate that the DB (MySQL / MariaDB) column is also exactly firstname and not for example Firstname or FirstName. When I change the path in the JSON to /FirstName, which is what the DB column is, then the patch works just fine. But I'm not sure if you are supposed to use CamelCase in the JSON in this case? It seems a bit non-standard.
How can I make jsonpatch at least case-insensitive? Or alternatively, is there some way to insert some mapping in the middle, for example like this:
def users_mapping(self, path):
    select = {
        "/firstname": "FirstName",
        "/lastname": "last_name",  # Just an example
    }
    return select.get(path, None)

Using Python 3.5, SQLAlchemy 1.1.13 and Flask-SQLAlchemy 2.2

A: Well, the answer is: yes, you can add mapping. Here's my implementation with some annotations:
The endpoint handler (eg. PATCH /news/123):
def patch(self, news_id):
    """Change an existing News item partially using an instruction-based JSON,
    as defined by: https://tools.ietf.org/html/rfc6902
    """
    news_item = News.query.get_or_404(news_id)
    self.patch_item(news_item, request.get_json())
    db.session.commit()

    # asdict() comes from dictalchemy method make_class_dictable(news)
    return make_response(jsonify(news_item.asdict()), 200)

The method it calls:
# news = the db.Model for News, from SQLAlchemy
# patchdata = the JSON from the request, like this:
# [{"op": "add", "path": "/title", "value": "Example"}]
def patch_item(self, news, patchdata, **kwargs):
    # Map the values to DB column names
    mapped_patchdata = []
    for p in patchdata:
        # Replace eg. /title with /Title
        p = self.patch_mapping(p)
        mapped_patchdata.append(p)

    # This follows the normal JsonPatch procedure
    data = news.asdict(exclude_pk=True, **kwargs)
    # The only difference is that I pass the mapped version of the list
    patch = JsonPatch(mapped_patchdata)
    data = patch.apply(data)
    news.fromdict(data)

And the mapping implementation:
def patch_mapping(self, patch):
    """This is used to map a patch "path" or "from" to a custom value.
    Useful for when the patch path/from is not the same as the DB column name.

    Eg.
    PATCH /news/123
    [{ "op": "move", "from": "/title", "path": "/author" }]

    If the News column is "Title", having "/title" would fail to patch
    because the case does not match. So the mapping converts this:
        { "op": "move", "from": "/title", "path": "/author" }
    To this:
        { "op": "move", "from": "/Title", "path": "/Author" }
    """

    # You can define arbitrary column names here.
    # As long as the DB column is identical, the patch will work just fine.
    mapping = {
        "/title": "/Title",
        "/contents": "/Contents",
        "/author": "/Author"
    }

    mutable = deepcopy(patch)
    for prop in patch:
        if prop == "path" or prop == "from":
            mutable[prop] = mapping.get(patch[prop], None)
    return mutable


text:
Q: Unable to show legend in seaborn distplot I am new to plotting in python and trying following code to plot distribution in seaborn but unable to see the legend, i.e., test_label1 and test_label1 on the plot.
import matplotlib.pylab as plt
import seaborn as sns
import numpy as np

plt.figure("Test Plots")
lst1 = list(np.random.rand(10))
lst2 = list(np.random.rand(10))
sns.distplot(lst1, label='test_label1', color="0.25")
sns.distplot(lst2, label='test_label2', color="0.25")

plt.show()

A: As you have already labelled your plots using label= inside your sns.distplot then all you have to do is show your legend. This is done by adding plt.legend() just before plt.show()
More information on matplotlib legends can be found in the documentation

A: I found some issue using "fig.legend()" to adding labels into legend in seaborn histogram. It reverse colors order in legend without changing colors of histogram bars...
fig.legend(labels=['label1','label2',...])

Histogram before using fig.legend()
Histogram after using fig.legend()
Modules versions:

*

*seborn '0.11.0'

*matplotlib '3.1.3'

Simple solution is to reverse the order of label_list by appling label_list.reverse() but I don't consider it as good solution. I don't have idea what is happening and how to block reversing the order of colors in legend.

A: By using fig.legend we can show legends in the distribution plot.
Here, an argument array of labels is passed to the function.
Labels in the legend will also be displayed as an order of array values.
import seaborn as sns
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10,6))
lst1 = list(np.random.rand(10))
lst2 = list(np.random.rand(10))
sns.distplot(lst1)
sns.distplot(lst1)
fig.legend(labels=['test_label1','test_label2'])
plt.show()


text:
Q: Nested tables: Insert values into specific columns of nested table I have a question regarding insert query for a nested table. I have an object like this:
 CREATE OR REPLACE TYPE obj_animals as OBJECT (
   row_id INTEGER,
   animal_id INTEGER,
   attr1 VARCHAR2(30),
   attr2 VARCHAR2(30),
   attr3 VARCHAR2(30)
 );

I have a table type like this:
CREATE OR REPLACE TYPE obj_animals_tab IS TABLE OF obj_animals;

Nested table is contained in this:
CREATE TABLE animals
(
     animal_id INTEGER,
     animal_ptr obj_animals_tab
)
 NESTED TABLE animals_ptr STORE AS obj_animals_tab;

How do I insert into (row_id,animal_id,attr1) columns or (row_id,animal_id & attr3) columns in the nested table using dynamic SQL?
I tried something like this:
INSERT INTO animals(animal_id,animal_ptr(row_id,animal_id,attr3))
VALUES(1,obj_animals_tab(obj_animals(1,1,'4')));

This threw me an error: Missing comma. Can you tell me a way to implement this? Thanks!

A: Insert statement must be like this:
INSERT INTO animals (animal_id, animal_ptr)
     VALUES (1, obj_animals_tab(obj_animals(1,1,'4')));

In order to update existing values you can use this syntax:
UPDATE
   (SELECT t.animal_id as animal_id_T, obj.animal_id as animal_id_OBJ,
      attr1, attr2, attr3
   FROM animals t
      NATURAL JOIN TABLE(obj_animals_tab) obj)
SET attr3 = 'xyz'
WHERE animal_id_T = 1
   AND animal_id_OBJ = 1;

Maybe it is not very smart to use animal_id in both table and object type.

A: INSERT INTO animals(animal_id,animal_ptr(row_id,animal_id,attr3))
VALUES(1,obj_animals_tab(obj_animals(
row_id => 1,
animal_id => 1,
attr3 => '4'
)));

Try this out. working for me.


text:
Q: How can I get more precise log sources from my Deis apps/containers? I have a Deis cluster running in a (hopefully-soon-to-be) Production environment, with quite a few different apps using the Dockerfile deployment method. Everything's running fine, but promoting this system to a true Production environment (that is, converting the DNS over) isn't really possible unless I can get some worthwhile log output.  Using the standard Deis logging platform, here's some sample output of a Web hit (with a bit more output, for context):
Feb 10 01:46:04 ip-10-21-2-154.ec2.internal systemd[1]: Starting Generate /run/coreos/motd...
Feb 10 01:46:04 ip-10-21-2-154.ec2.internal systemd[1]: Started Generate /run/coreos/motd.
Feb 10 01:46:08 ip-10-21-2-154.ec2.internal docker[1867]: [info] GET /containers/json
Feb 10 01:46:08 ip-10-21-2-154.ec2.internal docker[1867]: [215084df] +job containers()
Feb 10 01:46:08 ip-10-21-2-154.ec2.internal docker[1867]: [215084df] -job containers() = OK (0)
Feb 10 01:46:09 ip-10-21-2-154.ec2.internal sh[1316]: 2015/02/10 01:46:09 set /deis/services/production-web/production-web_v8.cmd.1 -> 10.21.2.154:49409
Feb 10 01:46:12 ip-10-21-2-154.ec2.internal sh[9844]: 2015-02-10 01:46:12.302721 7f213ae14700  0 mon.ip-10-21-2-154.ec2.internal@4(peon).data_health(58) update_stats avail 80% total 102400 MB, used 17621 MB, avail 82542 MB
Feb 10 01:46:18 ip-10-21-2-154.ec2.internal docker[1867]: [info] GET /containers/json
Feb 10 01:46:18 ip-10-21-2-154.ec2.internal docker[1867]: [215084df] +job containers()
Feb 10 01:46:18 ip-10-21-2-154.ec2.internal docker[1867]: [215084df] -job containers() = OK (0)
Feb 10 01:46:19 ip-10-23-1-151.ec2.internal sh[1521]: [INFO] - [10/Feb/2015:01:46:27 +0000] - 10.21.2.179 - - - 200 - "GET / HTTP/1.1" - 4927 - "-" - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36" - "~^production-web\x5C.(?<domain>.+)$" - 10.21.2.154:49409
Feb 10 01:46:19 ip-10-21-2-154.ec2.internal sh[8468]: ===========
Feb 10 01:46:19 ip-10-21-2-154.ec2.internal sh[8468]: HIT TRACKER
Feb 10 01:46:19 ip-10-21-2-154.ec2.internal sh[8468]: SLUG: public/javascripts/bundle.js
Feb 10 01:46:19 ip-10-21-2-154.ec2.internal sh[8468]: ===========

That contains alot of platform information – which is great to have, if only I could filter it out. The problem is all the lines for which the source is sh, but with different PIDs.  Those are each completely different containers:

*

*1316 is deis-publisher

*9844 is deis-store-monitor

*1521 is deis-router

*8468 is my web application, production-web

The only way for me to find that out is to ssh into the box and run ps.  What's worse, if I had any logs from my other containers at the same time, they would have also shown up as sh – in a production environment with several active apps all logging to the same stream, this situation is obviously untenable. The ideal situation would have sh replaced by the name of the Docker container or, preferably, the Deis app.
I've poured over the documentation and dug into the logspout and logger source code, but I can't find anything to fix this. Any chance I could get some pointers here?

A: In order to get at the name of the deis container that logged the line, the best way I've found is either:

*

*To run the output of journalctl -f -o short through netcat to a fluentd or logstash tcp listener. You can use these tools to summarize the fields like _SYSTEMD_UNIT that appeal to your needs.

*Use ianblenke/fluentd with LOG_DOCKER_JSON defined or fork and modify the autobuild source docker-ianblenke/fluentd. This uses the fluentd-docker plugin to follow the raw docker container json logs.

If you're using CoreOS, I use this fluentd.cloud-init to auto-feed my logs to a local elasticsearch instance on TCP 9200. Will fill find other useful CoreOS cloud-init configs in that project as well.


text:
Q: How to decode modbus frame to float value using Arduino code? Hello please I need your help, I am currently working on an emodbus project with arduino, I want to read the data from energy meter to the serial monitor on the arduino board,
I send for example the following frame of the arduino towards the meter to recover the value of the tension:
01 03 00 12 00 02 64 0E
in response from the counter to the arduino card I receive the following frame:
01 03 04 43 54 19 9A 25 9C
which must have the value: 212.1
my problem is that i could not display on the serial monitor
how can i decode this frame with arduino code to get the true value

A: Read here about the modbus library

Frame formats (This answers my question from the comment - you should have known that)
A Modbus "frame" consists of an Application Data Unit (ADU), which
  encapsulates a Protocol Data Unit (PDU):[10]
ADU = Address + PDU + Error check,
PDU = Function code + Data.

The byte order for values in Modbus data frames is most significant
  byte of a multi-byte value is sent before the others. All Modbus
  variants use one of the following frame formats.[1] Modbus RTU frame
  format (primarily used on asynchronous serial data lines like
  RS-485/EIA-485) Name  Length (bits)   Function Start  28  At least 3½
  character times of silence (mark condition) Address   8   Station
  address Function  8   Indicates the function code; e.g., read
  coils/holding registers Data  n × 8   Data + length will be filled
  depending on the message type CRC     16  Cyclic redundancy check End     28
    At least 3½ character times of silence between frames

Before using the library or building blocks from it read the issues first.
For the application to emodbus go here: Look into the files emodbus.h and emodbus.cpp and etools.h and etools.cpp


text:
Q: How to output emoji to console in Node.js (on Windows)? On Windows, there's some basic emoji support in the console, so that I can get a monochrome glyph if I type, e.g.  ☕ or .  I can output a string from PowerShell or a C# console application or Python and they all show those characters fine enough.
However, from Node.js, I can only get a couple of emoji to display (e.g. ☕), but not other (instead of  I see �).  However, if I throw a string with those characters, they display correctly.
console.log('  ☕ ');
throw '  ☕ ';

If I run the above script, the output is

 � ☕

C:\Code\emojitest\emojitest.js:2
throw '  ☕ ';
^
  ☕

Is there anyway that I can output those emojis correctly without throwing an error?  Or is that exception happening outside of what's available to me through the standard Node.js APIs?

A: (Disclaimer: I don't have a solution, I explored what makes exception handling special with regards to printing emoji, with the tools I have on Windows 10 -- With some luck that might sched some light on the issue, and perhaps someone will recognize something and come up with a solution)
Looks like Node's exception reporting code for Windows calls to a different Windows API, that happens to support Unicode better.
Let's see with Node 7.10 sources:
ReportException
 →
AppendExceptionLine
 →
PrintErrorString
In PrintErrorString, the Windows-specific section detects output type (tty/console or not):
 - For non-tty/console context it will print to stderr (e.g. if you redirect to a file)
 - In a cmd console (with no redirection), it will convert text with MultiByteToWideChar() and then pass that to WriteConsoleW().
If I run your program using ConEmu (easier than getting standard cmd to work with unicode & emoji -- yes I got a bit lazy here), I see something similar as what you saw: console.log fails to print emoji, but the emoji in exception message are printed OK (even the scroll glyph).
If I redirect all output to a file (node test.js > out.txt 2>&1, yes that works in Windows cmd too), I get "clean" Unicode in both cases.
So it seems when a program prints to stdout or stderr in a Windows console, the console does some (bad) reencoding work before printing. When the program uses Windows console API directly (doing the conversion itself with MultiByteToWideChar then write to console with WriteConsoleW()), the console shows the glorious unaltered emoji.
When a JS program uses console API to log stuff, maybe Node could try (on Windows) to detect console and do the same thing as it does for reporting exceptions. See @BrianNixon's answer that explains what is actually happening in libuv.

A: What you want may not be possible without a change to libuv. When you (or the
console) write to stdout or stderr on Windows and the stream is a TTY,
libuv does its own conversion from UTF‑8 to UTF‑16. In doing so it explicitly
refuses to output surrogate pairs, emitting instead the replacement character
U+FFFD � for any codepoint beyond the BMP.
Here's the culprit in uv/src/win/tty.c:
  /* We wouldn't mind emitting utf-16 surrogate pairs. Too bad, the */
  /* windows console doesn't really support UTF-16, so just emit the */
  /* replacement character. */
  if (utf8_codepoint > 0xffff) {
    utf8_codepoint = UNICODE_REPLACEMENT_CHARACTER;
  }

The throw message appears correctly because Node lets Windows do the
conversion from UTF‑8 to UTF‑16 with MultiByteToWideChar() (which does emit
surrogate pairs) before writing the message to the console. (See
PrintErrorString() in src/node.cc.)
Note: A pull request has been submitted to resolve this issue.

A: The next "Windows Terminal" (from Kayla Cinnamon) and the Microsoft/Terminal project should be able to display emojis.
This will be available starting  June 2019.
Through the use of the Consolas font, partial Unicode support will be provided.
The request is in progress in Microsoft/Terminal issue 387.
And Microsoft/Terminal issue 190 formally demands "Add emoji support to Windows Console".
But there are still issues (March 2019):

I updated my Win10 from 1803 to 1809 several days ago, and now all characters >= U+10000 (UTF-8 with 4 bytes or more) no longer display.
  I have also tried the newest insider version(Windows 10 Insider Preview 18358.1 (19h1_release)), unfortunately, this bug still exists.