text:
import numpy as _np
import theano as _th
import theano.tensor as _T
import numbers as _num
import logging as _log

import DeepFried.util as _u

def _info(msg, *a, **kw):
    log = _log.getLogger(__name__)
    log.info(msg.format(*a, **kw))

class Layer(object):
    """
    Abstract superclass of all layers with a dual purpose:

    1. Define common interface all layers should implement.
    2. Implement boilerplate code which is the same for any kind of layer.

    Note that only the second point is actually a valid one; introducing a
    hierarchy of classes for the first one would be unpythonic.

    Additional methods that *may* be implemented by some layers and (TODO)
    probably should be formalized and documented somewhere else:

    - `weightinitializer(self)`:
        Returns a function which can be used to initialize weights of a
        preceding layer. Which function is returned depends on the value of
        the `init` flag passed in the constructor.

        The returned function's signature is:

        def init(shape, rng, fan_in, fan_out)

        It returns a numpy array with initial values for the weights.

        - `shape`: The shape of the initial weights to return.
        - `rng`: The random number generator to be used.
        - `fan_in`: The fan-in of the weights, used in some initializations.
        - `fan_out`: The fan-out of the weights, used in some initializations.

    - `biasinitializer(self)`:
        See the documentation of `weightsinitializer`, the difference is that
        biases typically use a different (simper) initialization method.
    """

    def __init__(self):
        # A layer which doesn't have any parameters should still have an empty
        # attribute for that to make generic code easier.
        self.Ws = []
        self.bs = []
        self.params = []

        # This contains the initializers to be used for each parameter.
        self.inits = {}

    def train_expr(self, *Xs, **kw):
        """
        Returns an expression or a tuple of expressions computing the
        output(s) at training-time given the symbolic input(s) in `Xs`.

        The following may be contained in `kw`:

        - `updates`: A list to which extra Theano updates which should be
            performed during training can be added.
            The layout is the same as for `theano.function`: `updates` is a
            list of pairs where the first element is the shared variable to be
            updated and the second element is the update expression.
        """
        raise NotImplementedError("You need to implement `train_expr` or `train_exprs` for {}!".format(type(self).__name__))

    def pred_expr(self, *Xs):
        """
        Returns an expression or a tuple of expressions to be computed jointly
        during prediction given the symbolic input(s) in `Xs`.

        This defaults to calling `train_expr`, which is good enough for all
        layers which don't change between training and prediction.
        """
        return self.train_expr(*Xs)

    def make_inputs(self, name="Xin"):
        """
        Returns a Theano tensor or a tuple of Theano tensors with given `names`
        of the dimensions which this layer takes as input.

        **NOTE** that this needs to include a leading dimension for the
        minibatch.

        Defaults to returning a single matrix, i.e. each datapoint is a vector.
        """
        return _T.matrix(name)

    def newweight(self, *args, **kwargs):
        """
        Creates a new shared weight parameter variable called `name` and of
        given `shape` which will be learned by the optimizers.

        - `name`: The name the variable should have.
        - `shape`: The shape the weight should have.
        - `val`: Optionally a value (numpy array or shared array) to use as
                 initial value.
        - `empty`: function which should return a new value for the variable,
                   will only be called if `val` is None.
        """
        p = self._newparam(*args, **kwargs)
        self.Ws.append(p)
        return p

    def newbias(self, *args, **kwargs):
        """
        Creates a new shared bias parameter variable called `name` and of
        given `shape` which will be learned by the optimizers.

        - `name`: The name the variable should have.
        - `shape`: The shape the weight should have.
        - `val`: Optionally a value (numpy array or shared array) to use as
                 initial value.
        - `empty`: function which should return a new value for the variable,
                   will only be called if `val` is None.
        """
        p = self._newparam(*args, **kwargs)
        self.bs.append(p)
        return p

    def _newparam(self, name, shape, val=None, init=None):
        name = "{}{}".format(name, 'x'.join(map(str, shape)))

        if val is None and init is None:
            init = lambda shape, *a, **kw: _np.full(shape, _np.nan, dtype=_th.config.floatX)
        elif isinstance(val, _np.ndarray):
            init = lambda *a, **kw: val
        elif isinstance(val, _num.Real):
            init = lambda *a, **kw: _np.full(shape, val, dtype=_th.config.floatX)
        elif isinstance(val, _T.TensorVariable):
            # When using an existing theano shared variable, don't store nay
            # initializer as "the origina" probably already has one.
            return val, None
        else:
            raise ValueError("Couldn't understand parameters for parameter creation.")

        p = _th.shared(init(shape).astype(_th.config.floatX), name=name)
        self.params.append(p)
        self.inits[p] = init
        return p

    def reinit(self, rng):
        """
        Sets the value of each parameter to that returned by a call to the
        initializer which has been registered for it.

        If a parameter has a `_df_init_kw` attribute, it is supposed to be a
        dict and will be passed as additional keyword arguments to the
        initializer.
        """
        rng = _u.check_random_state(rng)

        for p in self.params:
            if p not in self.inits:
                raise RuntimeError("Want to reinit layer parameter '{}' but no initializer registered for it.".format(p.name))
            kw = {}
            if hasattr(p, "_df_init_kw"):
                kw = p._df_init_kw
            p.set_value(self.inits[p](p.get_value().shape, rng, **kw).astype(p.dtype))

    def batch_agg(self):
        """
        Returns a function which can be used for aggregating the outputs of
        minibatches in one epoch.

        If the layer has multiple outputs, it should return a tuple of
        aggregator functions.

        This default implementation just concatenates them, which is a
        sensible behaviour for almost all kinds of layers.
        """
        def agg(outputs):
            return _np.concatenate(outputs)
        return agg

    def ensembler(self):
        """
        Returns a function which, given a list of multiple outputs for a
        single minibatch, computes the output of ensembling them. This is
        useful e.g. for ensembling the predictions of multiple augmentations.

        If the layer has multiple outputs, it should return a tuple of
        ensembler functions.

        This default implementation computes the average of the outputs, whic
        is a sensible behaviour for most kinds of outputs.
        """
        def ens(outputs):
            return sum(outputs)/len(outputs)
        return ens

    # And a whole bunch of hooks that some weird layers may utilize.
    # (I'm thinking of you, BN!)

    def pre_epoch(self):
        pass

    def pre_minibatch(self):
        pass

    def post_minibatch(self):
        pass

    def post_epoch(self):
        pass

    def pre_finalize(self):
        pass

    def finalize_pre_minibatch(self):
        pass

    def finalize_post_minibatch(self):
        pass

    def post_finalize(self):
        pass

class FullyConnected(Layer):
    """
    Fully-connected layer is the typical "hidden" layer. Basically implements
    a GEMV or, because it's batched, a GEMM.
    """

    def __init__(self, inshape, outshape, bias=True, W=None, b=None):
        """
        Creates a fully-connected (i.e. linear, hidden) layer taking as input
        a minibatch of `inshape`-shaped elements and giving as output a
        minibatch of `outshape`-shaped elements.

        - `inshape`: The shape of the input, excluding the leading minibatch
                     dimension. Usually, this is just a number, but it may be a
                     tuple, in which case the input is first flattened.
        - `outshape`: The shape of the output, excluding the leading minibatch
                      dimension. Usually, this is just a number, but it may be
                      a tuple, in which case the output is reshaped to this.
        - `bias`: Whether to use a bias term or not.
                  For example, if a minibatch-normalization follows, a bias
                  term is useless.
        - `W`: Optional initial value for the weights.
        - `b`: Optional initial value for the bias.
        """
        super(FullyConnected, self).__init__()

        self.inshape = _u.tuplize(inshape)
        self.outshape = _u.tuplize(outshape)

        fan_in = _np.prod(self.inshape)
        fan_out = _np.prod(self.outshape)

        self.W_shape = (fan_in, fan_out)
        self.W = self.newweight("W_fc", self.W_shape, W)
        self.W._df_init_kw = dict(fan_in=fan_in, fan_out=fan_out)

        if bias:
            self.b_shape = (fan_out,)
            self.b = self.newbias("b_fc", self.b_shape, b)

    def make_inputs(self, name="Xin"):
        return _T.TensorType(_th.config.floatX, (False,)*(1+len(self.inshape)))(name)

    def train_expr(self, X, **kw):
        batchsize = X.shape[0]

        # For non-1D inputs, add a flattening step for convenience.
        if len(self.inshape) > 1:
            # (Don't forget the first dimension is the minibatch!)
            X = X.flatten(2)

        out = _T.dot(X, self.W)

        if hasattr(self, "b"):
            out += self.b

        # And for non-1D outputs, add a reshaping step for convenience.
        if len(self.outshape) > 1:
            # (Again, don't forget the first dimension is the minibatch!)
            out = out.reshape((batchsize,) + self.outshape)

        return out

class Softmax(Layer):
    """
    A softmax layer is commonly used as output layer in multi-class logistic
    regression, the default type of multi-class classification in current-gen
    nnets.

    This layer really should follow a fully-connected layer with the number of
    classes to be predicted as output.
    """

    def __init__(self):
        super(Softmax, self).__init__()

    def train_expr(self, X, **kw):
        """
        Returns an expression computing the output at training-time given a
        symbolic input `X`.
        """
        return _T.nnet.softmax(X)

    def weightinitializer(self):
        """ See the documentation of `Layer`. """
        def init(shape, rng, *a, **kw):
            _info("Init {} with zeros", shape)
            return _np.zeros(shape)
        return init

    def biasinitializer(self):
        """ See the documentation of `Layer`. """
        def init(shape, rng, *a, **kw):
            return _np.zeros(shape)
        return init

class ReLU(Layer):
    """
    Typical ReLU nonlinearity layer of newschool nnets.
    """

    def __init__(self, leak=0, cap=None, init='Xavier'):
        """
        Creates a ReLU layer which computes the elementwise application of the
        optionally capped ReLU or Leaky ReLU function:

            out = min(max(leak*X, X), cap)

        - `leak`: Number to use as slope for the "0" part. Defaults to 0, i.e.
                  standard ReLU.
        - `cap`: Number to use as max value of the linear part, as in Alex'
                 CIFAR Convolutional Deep Belief Nets.
                 If `None` (the dfeault), do not apply any cropping.
        - `init`: The initialization technique to use for initializing another
                  layer's weights. Currently available techniques are:
            - `'Xavier'`: Uniform-random Xavier initialization from [1].
            - `'XavierN'`: Normal-random [2] way of achieving Xavier
                           initialization.
            - `'PReLU'`: Normal-random initialization for PReLU[2].
            - A number: Standard deviation (sigma) of the normal distribution
                        to sample from.

        1: Understanding the difficulty of training deep feedforward neural networks.
        2: Delving Deep into Rectifiers.
        """
        super(ReLU, self).__init__()

        self.leak = leak
        self.cap = cap
        self.init = init

    def train_expr(self, X, **kw):
        if self.cap is None:
            return _T.maximum(self.leak*X, X)
        else:
            return X.clip(self.leak*X, self.cap)

    def weightinitializer(self):
        """ See the documentation of `Layer`. """
        if self.init == 'Xavier':
            def init(shape, rng, fan_in, fan_out):
                fan_mean = (fan_in+fan_out)/2
                bound = _np.sqrt(6/fan_mean)
                _info("Init {} with u[{}]", shape, bound)
                return rng.uniform(-bound, bound, shape)
            return init
        elif self.init == 'XavierN':
            def init(shape, rng, fan_in, fan_out):
                fan_mean = (fan_in+fan_out)/2
                std = _np.sqrt(1/fan_mean)
                _info("Init {} with {}*std_normal", shape, std)
                return std*rng.standard_normal(shape)
            return init
        elif self.init == 'PReLU':
            def init(shape, rng, fan_in, fan_out):
                fan_mean = (fan_in+fan_out)/2
                std = _np.sqrt(2/fan_mean)
                _info("Init {} with {}*std_normal", shape, std)
                return std*rng.standard_normal(shape)
            return init
        else:
            def init(shape, rng, *a, **kw):
                _info("Init {} with {}*std_normal", shape, self.init)
                return self.init*rng.standard_normal(shape)
            return init

    def biasinitializer(self):
        """ See the documentation of `Layer`. """
        def init(shape, *a, **kw):
            return _np.zeros(shape)
        return init

class Tanh(Layer):
    """
    Typical tanh nonlinearity layer of oldschool nnets.
    """

    def __init__(self, init='Xavier'):
        """
        Creates a Tanh layer which computes the elementwise application of the
        tanh function:

            out = tanh(X)

        - `init`: The initialization technique to use for initializing another
                  layer's weights. Currently available techniques are:
            - `'Xavier'`: Uniform-random Xavier initialization from [1].
            - `'XavierN'`: Normal-random [2] way of achieving Xavier
                           initialization.
            - A number: Standard deviation (sigma) of the normal distribution
                        to sample from.

        1: Understanding the difficulty of training deep feedforward neural networks.
        2: Delving Deep into Rectifiers.
        """
        super(Tanh, self).__init__()
        self.init = init

    def train_expr(self, X, **kw):
        return _T.tanh(X)

    def weightinitializer(self):
        """ See the documentation of `Layer`. """
        if self.init == 'Xavier':
            def init(shape, rng, fan_in, fan_out):
                fan_mean = (fan_in+fan_out)/2
                bound = _np.sqrt(6/fan_mean)
                _info("Init {} with u[{}]", shape, bound)
                return rng.uniform(-bound, bound, shape)
            return init
        elif self.init == 'XavierN':
            def init(shape, rng, fan_in, fan_out):
                fan_mean = (fan_in+fan_out)/2
                std = _np.sqrt(1/fan_mean)
                _info("Init {} with {}*std_normal", shape, std)
                return std*rng.standard_normal(shape)
            return init
        else:
            def init(shape, rng, *a, **kw):
                _info("Init {} with {}*std_normal", shape, self.init)
                return self.init*rng.standard_normal(shape)
            return init

    def biasinitializer(self):
        """ See the documentation of `Layer`. """
        def init(shape, *a, **kw):
            return _np.zeros(shape)
        return init

class Sigmoid(Layer):
    """
    Difficult, sigmoid 1/(1+exp(-x)) nonlinearity layer of oldschool nnets.
    """

    def __init__(self, init='Xavier', alt=None):
        """
        Creates a Sigmoid layer which computes the elementwise application of the
        sigmoid function:

            out = 1/(1+exp(-X))

        - `init`: The initialization technique to use for initializing another
                  layer's weights. Currently available techniques are:
            - `'Xavier'`: Uniform-random Xavier initialization from [1].
            - A number: Standard deviation (sigma) of the normal distribution
                        to sample from.
        - `alt`: Whether to use an alternative sigmoid-function, one of:
            - `None`: Use the actual sigmoid function.
            - `ultrafast`: Use Theano's `ultra_fast_sigmoid` function. It's a
                           piecewise-linear approximation, ~2-3x faster.
            - `hard`: Use Theano's `hard_sigmoid` function. It's just like a
                      ReLU capped at 1 and centered around 0.

        1: Understanding the difficulty of training deep feedforward neural networks.
        """
        super(Sigmoid, self).__init__()
        self.init = init
        if alt is None:
            self.fn = _T.nnet.sigmoid
        elif alt == "ultrafast":
            self.fn = _T.nnet.ultra_fast_sigmoid
        elif alt == "hard":
            self.fn = _T.nnet.hard_sigmoid
        else:
            raise ValueError("Unknown alternative sigmoid formulation: " + repr(alt))

    def train_expr(self, X, **kw):
        return self.fn(X)

    def weightinitializer(self):
        """ See the documentation of `Layer`. """
        if self.init == 'Xavier':
            def init(shape, rng, fan_in, fan_out):
                fan_mean = (fan_in+fan_out)/2
                bound = 4*_np.sqrt(6/fan_mean)
                _info("Init {} with u[{}]", shape, bound)
                return rng.uniform(-bound, bound, shape)
            return init
        else:
            def init(shape, rng, *a, **kw):
                _info("Init {} with {}*std_normal", shape, self.init)
                return self.init*rng.standard_normal(shape)
            return init

    def biasinitializer(self):
        """ See the documentation of `Layer`. """
        def init(shape, *a, **kw):
            return _np.zeros(shape)
        return init

class Dropout(Layer):
    """
    See "Improving neural networks by preventing co-adaptation of feature detectors"
    by Hinton, Srivastava, Krizhevsky, Sutskever and Salakhutdinov.
    """

    def __init__(self, p=0.5):
        """
        The probability of dropping out.
        """
        super(Dropout, self).__init__()

        # We need 1-p here since p is the probability of dropping out,
        # i.e. being multiplied by zero,
        # while binomial expects the probability of 1, i.e. keeping.
        self.p_keep = 1-p
        self.seed = self.srng = None

    def reinit(self, rng):
        rng = _u.check_random_state(rng)
        self.seed = rng.randint(2**31)
        self.srng = _T.shared_randomstreams.RandomStreams(self.seed)

    def train_expr(self, *Xs, **kw):
        if self.srng is None:
            raise RuntimeError("You forgot to initialize the {} layer!".format(type(self).__name__))

        return _u.maybetuple(x * self.srng.binomial(n=1, p=self.p_keep,
                                                    size=x.shape,
                                                    dtype=x.dtype)
                           for x in _u.tuplize(Xs))

    def pred_expr(self, *Xs):
        return _u.maybetuple(x * self.p_keep for x in _u.tuplize(Xs))

class BatchNormalization(Layer):
    """
    See Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift
    by Sergey Ioffe and Christian Szegedy.

    This layer implements the fully-connected version of batch-normalization.

    This is the magic sauce =)
    """

    def __init__(self, nfeat, post=True, momentum=False, eps=1e-6):
        """
        Very sad we need to hardcode the inshape here!
        """
        super(BatchNormalization, self).__init__()

        self.eps = eps
        self.post = post
        self.momentum = momentum

        # Default value for undecided people.
        if self.momentum is True:
            self.momentum = 0.1

        # Use the method names corresponding to whether we want the to be run
        # during training, or in the finalization step.
        if self.post:
            self.pre_finalize = self._pre
            self.post_finalize = self._post
            self.finalize_pre_minibatch = self._pre_mini
        else:
            self.pre_epoch = self._pre
            self.post_epoch = self._post
            self.pre_minibatch = self._pre_mini

        shape = _u.tuplize(nfeat)

        self.gamma = self._newparam("bn_gamma", shape, val=1)
        self.beta = self._newparam("bn_beta", shape, val=0)

        # Just a utility to avoid code (and memory) repetition
        self._zero = _np.zeros(shape, dtype=_th.config.floatX)

        # These need to be filled during the switch from train to pred.
        # Add the leading dimension for easier correct broadcasting.
        self.sum_means = _th.shared(self._zero, name="bn_sum_means")
        self.sum_vars = _th.shared(self._zero, name="bn_sum_vars")

        _nan = _np.full(shape, _np.nan, dtype=_th.config.floatX)
        self.pgamma = _th.shared(_nan, name="bn_pgamma")
        self.pbeta = _th.shared(_nan, name="bn_pbeta")

    def train_expr(self, X, **kw):

        # The main difference for convolutional BN: also average over
        # all regions a filter has been applied.
        # There are some minor implementation differences which mainly
        # affect speed a little.
        conv = X.ndim == 4
        axes = [0, 2, 3] if conv else 0

        # Mean across minibatch examples. The output will be of `inshape`.
        mean = _T.mean(X, axis=axes, keepdims=True)

        # Computing it ourselves using above mean is marginally faster.
        var = _T.mean((X-mean)**2, axis=axes, keepdims=True)

        if self.post:
            key = 'fin_updates'
        else:
            key = 'fwd_updates'

        assert key in kw, "This should never happen, please file an issue!"

        if self.momentum is False:
            # In this approach, we sum all statistics throughout an epoch.
            kw[key].append((self.sum_means, self.sum_means + mean.squeeze()))
            kw[key].append((self.sum_vars, self.sum_vars + var.squeeze()))
        else:
            # Otherwise, we use a momentum-based running-mean.
            # This is how Torch does it, but there's no mention of it in
            # the original paper.
            kw[key].append((self.sum_means, (1 - self.momentum) * self.sum_means + self.momentum * mean.squeeze()))
            kw[key].append((self.sum_vars, (1 - self.momentum) * self.sum_vars + self.momentum * var.squeeze()))

        # Normalize.
        Xn = (X - mean)/_T.sqrt(var + self.eps)

        # Re-parametrize
        if conv:
            return Xn * self.gamma.dimshuffle('x', 0, 'x', 'x') + self.beta.dimshuffle('x', 0, 'x', 'x')
        else:
            return Xn * self.gamma + self.beta

    def _pre(self):
        """ This will be called at the beginning of an epoch/postprocessing. """
        self.nmini = 0

        # Reset the collected means/variances in the case where we count for a
        # whole epoch.
        if self.momentum is False:
            self.sum_means.set_value(self._zero)
            self.sum_vars.set_value(self._zero)

    def _pre_mini(self):
        """
        This will be called before each minibatch.
        Counts the number of minibatches we're going throug.
        """
        self.nmini += 1

    def _post(self):
        """ This will be called at the end of an epoch/postprocessing. """

        # Retrieve the means and variances.
        mean = self.sum_means.get_value()
        var = self.sum_vars.get_value()

        # If we're not momentum-based, convert sum over mini-batches to mean.
        if self.momentum is False and self.nmini > 1:
            mean /= self.nmini
            var /= self.nmini-1

        std = _np.sqrt(var + self.eps)

        # And compute the predictor's modified gamma and beta values.
        g = self.gamma.get_value()
        b = self.beta.get_value()

        pgamma = g/std
        self.pgamma.set_value(pgamma)
        self.pbeta.set_value(b - pgamma*mean)

        # TODO: If we did fuse this with FullyConnected, we could actually
        # merge the matrices, further speeding up prediction.

    def pred_expr(self, X):
        if X.ndim == 4:
            pgamma = self.pgamma.dimshuffle('x', 0, 'x', 'x')
            pbeta = self.pbeta.dimshuffle('x', 0, 'x', 'x')
            return X * pgamma + pbeta
        else:
            return X * self.pgamma + self.pbeta

    def reinit(self, rng):
        """
        We need a custom reinit because we also need to reinit our running
        means and averages!
        """
        super(BatchNormalization, self).reinit(rng)

        self.sum_means.set_value(self._zero)
        self.sum_vars.set_value(self._zero)

class Conv2D(Layer):
    """
    Your local neighborhood convolutional layer.

    If `*` is the convolution, it computes the following operation:

    out[b,k,:,:] = sum_d filt[k,d,:,:] * in[b,d,:,:] + b[k]

    `b` goes through the minibatch samples,
    `k` goes through the filterbank-kernels, and
    `d` sums across the input image dimensions.
    """

    def __init__(self, nconv, convshape, imdepth, imshape=None,
                 stride=(1,1), border_mode='valid',
                 bias=True, W=None, b=None):
        """
        Creates a 2D convolutional layer with the following properties:

        - `nconv`: The number of filters in the filterbank. This will also be
            the depth of the output image, since there's one layer per filter.
        - `convshape`: A number or a pair of numbers specifying the size (h,w)
            of the filters. If it's a single number, the filters are square.
        - `imdepth`: The number of layers the input image has. For RGB images,
            this would be three.
        - `imshape`: Optionally the shape (h,w) of the input image.
            If specified, the input will automatically be reshaped to this,
            taking `imdepth` and the batchsize into account.
            If `None`, the input could be images of any size,
            but needs to be shaped in the correct dimension, i.e. 4D.
        - `stride`: Factor by which the output is subsampled, *not* pooled.
            Note that this doesn't save computations as it's still doing the
            full convolution first. Isn't it almost pointless?
        - `border_mode`: From Theano's documentation:
            - `"valid"`: only apply filter to complete patches of the image.
                Output shape: image_shape - filter_shape + 1
            - `"full"`: zero-pads image to multiple of filter shape.
                Output shape: image_shape + filter_shape - 1
        - `bias`: Whether to use a bias term or not.
                  For example, if a minibatch-normalization follows,
                  a bias term is useless.
        - `W`: Optional initial value for the weights.
        - `b`: Optional initial value for the bias.
        """
        super(Conv2D, self).__init__()

        # Allow for specifying the conv shape as a single number if square.
        if isinstance(convshape, _num.Integral):
            convshape = (convshape, convshape)

        self.border_mode = border_mode
        self.stride = stride
        self.imshape = imshape
        self.imdepth = imdepth

        fan_in = imdepth * _np.prod(convshape)
        fan_out = nconv * _np.prod(convshape)

        self.W_shape = (nconv, imdepth) + convshape
        self.W = self.newweight("W_conv", self.W_shape, W)
        self.W._df_init_kw = dict(fan_in=fan_in, fan_out=fan_out)

        if bias:
            self.b_shape = (nconv,)
            self.b = self.newbias("b_conv", self.b_shape, b)

    def make_inputs(self, name="Xin"):
        if self.imshape is None:
            if self.imdepth > 1:
                return _T.tensor4(name)
            else:
                return _T.tensor3(name)
        else:
            return _T.matrix(name)

    def train_expr(self, X, **kw):
        if self.imshape is not None:
            X = X.reshape((X.shape[0], self.imdepth) + self.imshape)
        elif self.imdepth == 1:
            X = X.reshape((X.shape[0], 1, X.shape[1], X.shape[2]))

        out = _T.nnet.conv.conv2d(X, self.W,
            image_shape=(None, self.imdepth) + (self.imshape or (None, None)),
            filter_shape=self.W_shape,
            border_mode=self.border_mode,
            subsample=self.stride
        )

        if hasattr(self, "b"):
            out += self.b.dimshuffle('x', 0, 'x', 'x')

        return out

class SpatialMaxPool(Layer):
    """
    Your local neighborhood's pool. Quite full during summer.
    """

    def __init__(self, size, stride=None, ignore_border=False):
        """
        Creates a 2D max-pooling layer which pools over the 2 last dimensions.

        - `size`: The size (h,w) of the pooled patches.
        - `stride`: Not supported yet, will be in newer Theano version.
        - `ignore_border`: whether to make use of left-over border when sizes
            are not perfectly divisible, or just ignore it.
        """
        super(SpatialMaxPool, self).__init__()

        if isinstance(size, _num.Integral):
            size = (size, size)
        self.size = size

        if isinstance(stride, _num.Integral):
            stride = (stride, stride)
        self.stride = stride

        self.ignore_border = ignore_border

    def make_inputs(self, name="Xin"):
        # Actually, this could be anything > 2D.
        return _T.tensor4(name)

    def train_expr(self, X, **kw):
        return _T.signal.downsample.max_pool_2d(X, ds=self.size, ignore_border=self.ignore_border)

redpajama_set_name: RedPajamaGithub


Feeling a little lost these days? Considering the whirlwind days (often beginning before sunrise and ending after sunset …), a family caregiver can easily devote much of his/her own time, energy, and resources to helping an aging loved one and, in the process, lose much of him/herself. Caregiving days are anything but typical and can stretch you in many different directions, but they are similar in the fact that they are often busy and can include any number of caregiving tasks. Considering the amount of work involved, it's easy to get lost in caregiving but please be careful!
Losing yourself in caregiving typically comes as a result of succumbing to common caregiving beliefs including that it is your own responsibility and/or obligation, that no one else could provide better care and support than you, that your aging parent could not function without your constant care, that no one will completely understand your situation, or that there are no resources available to you. While you will play an integral part in the relationship – the hub in the wheel, as it were – you must remember your own health and well-being and will completely deserve your own attention as well. Step back for a minute to honestly evaluate how you are doing and/or feeling lately … have you felt more tired? Impatient? Frustrated? Depressed? Stressed? It's a good bet that these negative feelings are connected to your overworking yourself as a caregiver. If you want to confirm that may be suffering, book an appointment to see your doctor. You will have a lot on your plate right now and managing it all can prove to be overwhelming. But what happens to a machine if you work it too long or too hard? At some point, it will break down and lose its ability to work properly or effectively.
Now that you have recognized (or have been told by a medical professional) that you are not feeling yourself, it is time to do something about that (and don't delay doing so …). One very effective answer is to take your own caregiver respite – allow yourself some personal time away from your daily caregiving responsibilities to break away and find (or once again …) find yourself. As a former co-caregiver for both my own parents, I admittedly was a slow student when it came to taking respite; however, I did learn the importance of taking regular breaks away and am now a strong advocate for doing so – you can do this and you deserve to do this.
As part of your own caregiving days, ensure that you include time to care for yourself. Sure, you can continually multitask (and may be somewhat successful doing so for the short term …) for a period of time, this is not something that you can realistically expect to do on an ongoing basis. The number of balls that anyone can continually juggle simultaneously in the air is limited … one, or more, of those balls will eventually drop. If one of those balls is your own health, you can be in trouble and realizing this may come too late.
Losing yourself in caregiving is quite common and it can prove to be dangerous. For your own sake and for the sake of others, take regular respite breaks to, once again, find yourself. You are worth it!
Rick Lauber is the author of Caregiver's Guide for Canadians and The Successful Caregiver's Guide (both books are published by Self-Counsel Press) - valuable and practical resources for family members, friends, spouses, and/or partners providing care to seniors. Lauber, a former co-caregiver for both his own aging parents, has written extensively about caregiving and senior's issues for print and on-line markets, has guested on radio talk shows and television news programs, and serves, on a volunteer basis, on the Board of Directors for Caregivers Alberta.
Wouldn't Caregiving be Easier with an Extra Set of Hands?
Why not Reach Out for the Hand that is Available?
Is Your Caregiving Cup Half Full or Half Empty?


Denis Bourke, Ballinagranna, died in Perth.
Sat 7.30, Mary Condon. Sun 11am, Liam Ring.
Sat 7.30 Bridget Keogh. Sun 11am: Rita Quish.
. Peace-and-quiet time of personal prayer.
Stations of the Cross: Thurs, after 9.30 Mass.
Church Cleaning: This Tuesday 28th, 10.15am. . All welcome.
will appreciate your generosity & your prayers.
Our parish Confirmation preparation programm continues with a special Service of Light for the girls/boys, their parents, sponsors & godparents on Tuesday 4th April at 7.30pm. Will include also the Sacrament of Penance, available to all.
Draw takes place after 11am Mass on Sundays in Duhig House. Last week's winners; €200 – Breda O'Connor; 4 x €50 – Mary Phipps, Jim & Ann Quinlan, Mike Hale, Bridget Heffernan. Seller's Prize – Annie Lonergan. Thanks for your support.
The club will hold a cake sale & monster raffle on Sunday April 16th in Cupán Tae (Donies) after Mass. Tickets from all players, committee members, local shops & Post Office.
Anyone interested in joining 'Mothers and Others' (football for fun) – contact any committee member.
Best of luck to Gillian Kemp and the senior team in John the Baptist C.S. who play in the Senior 'A' final against Ballygawley, Tyrone, this Friday 31st .
County Hurling League Rnd 2 v. Grangemockler -Ballyneale this Sunday 26th in Ballyneale at 12.00.
U-16 B Football Emly/Treacys v Eire Óg-Anacarthy this Monday 27th in Emly at 6.30. U-12 C Football Emly v Rosegreen on Thursday 30th in Emly, 6.45.
Emly Lourdes fundraising church-gate collection next weekend 1st & 2nd April. Support appreciated.
"Lessons from the World of Sport." A major Forum at Mary Immaculate College (St. Patrick's College), Thurles on next Wed 29th , 7.00 – 9.30pm. Speakers: Pat Spillane (Kerry), Michael Ryan (Tipp Mgr.), Anna May McHugh (Ploughing), John Hayes (Rugby). Cost €10. Booking – see church Poster.


KATHARINE Jenkins has officially responded to to having her OBE called a "f***ing joke" in leaked emails written by David Beckham.
The mezzo-soprano was attacked by the ex-footballer four years ago as he fumed in an email about not getting a knighthood from "unappreciative c***s" at Buckingham Palace.
Beckham, 41, reportedly wrote this particularly angry email to long-time PR man Simon Oliveira after missing out in 2013.
The offending quote from the so-called Beckileaks correspondence reads: "Katherine Jenkins OBE for what? Singing at the rugby and going to see the troops plus taking coke. F***ing joke."
Now Katherine has made her standpoint clear after being asked what she thinks of the comment.
The 36-year-old said: "I didn't say anything about it at the time, which means I'm definitely not going to be saying anything now or in the future.
"It was a situation I didn't want to get dragged into. So I'd like to stay out of it please."
Katherine's manager, Professor Jonathan Shalit, previously hit out at Beckhams' claim that Katherine didn't deserve her title.
He said: "I say Katherine was awarded an OBE for her services to music and charity.
Elsewhere in his emails, Becks wrote: "I expected nothing less [of Buckingham Palace].
This week Victoria Beckham collected an OBE, 14 years after the Queen gave one to David, who'd just been signed to Real Madrid for £25m at the time.
Katherine has received rave reviews for her current West End role as Julie Jordan in Rodgers and Hammerstein musical Carousel.


The Hope Solo versus Greg Ryan and the rest of the US Women's National Team got a little more fuel added to the fire when Abby Wambach returned home for a clinic and Jeff got her on the record about the whole debacle.
As a goalkeeper, I understand where Hope Solo is coming from.
I also understand that there is the whole code of keeping things like that inside the locker room.
But, at the end of the day, the question should really be "Was Hope's summation of the situation correct?" And on that point, I doubt there are too many people that will say that Hope was wrong and that Greg Ryan was correct.
Right now, it seems like Greg Ryan is getting to deflect the blame he should be getting for creating the environment that led to Hope Solo's meltdown. The focus shouldn't be on Hope Solo and if she has a future with the US Women's National Team. The focus should be on replacing Greg Ryan with Anson Dorrance or Julie Foudy or Brandi Chastain.
Personally, Hope Solo needs to apologize to the team and learn the lesson of not taking comments like that to the media. And the rest of the team needs to get over it and give her a second chance.
If Microsoft isn't the jersey sponsor for the new MLS team in Seattle, it would be a surprise with Paul Allen coming on board.
Allen provides the type of deep pocketed investor that MLS loves. So, it is no surprise that there are a boatload of Seattle to MLS rumors with this news coming out.
The real interesting thing will be the stadium plan for a Seattle MLS team. They keep talking about using Qwest Field, the current home of the Sounders and the NFL's Seahawks. But, I can't see that working long term as the only team that has gotten a good atmosphere in an NFL stadium is DC United. And that's due to the fact that they are using a much smaller stadium and make it even smaller by only using the lower bowl.
For instance, I can't see Toronto FC having the kind of success that they have had this season if they were playing at Skydome.
- Here is a piece on a potential expansion team in Philly .
- Bob Bradley has announced his roster for next week's friendly versus the Swiss.
- Chivas USA is starting up a youth academy system .


The concept Self-reliance -- Fiction represents the subject, aboutness, idea or notion of resources found in San Francisco Public Library.
I want my yaya! : Nasaan ang Yaya ko?
Shuai dao le, wo zi ji zhan qi lai!
Wo de shi qing wo lai zuo!
Wo zi ji chi fan!
Wo zi ji zou lu!


text:
Merkel's conservatives hit new low, piling pressure on coalition
BERLIN (Reuters) - Germany Chancellor Angela Merkel's conservatives slumped to a record low and fell further behind the resurgent opposition Greens in a survey published on Saturday, reflecting growing disillusionment with the ruling coalition.
FILE PHOTO: German Chancellor Angela Merkel and Annegret Kramp-Karrenbauer, Chairwoman of Germany's Christian Democratic Union party (CDU) attend a party meeting in Berlin, Germany June 2, 2019. REUTERS/Hannibal Hanschke/File Photo
Doubts are mounting that Merkel's right-left alliance can last its full term until 2021, largely due to disarray within her Social Democrat (SPD) partners, and many experts now see increasing chances of a federal election next year.
The Forsa poll put the conservative bloc on 24%, down two points from a week ago.
The Social Democrats (SPD) remained stuck at their low of 12% - level with the far-right Alternative for Germany (AfD) - a week after their leader quit because of a dismal performance in regional and European elections. Many members want to quit government and rebuild in opposition.
The Greens, buoyed by growing concern across Europe about climate change, which helped propel them to second place in European Parliament elections, remained the most popular party, on 27%.
"The Greens are benefiting from high voter mobilization, the self-destruction of the SPD and attempts by the conservatives to trump the Greens on climate protection," said Forsa chief Manfred Guellner.
If Merkel's coalition collapses, Germany faces the possibilities of a snap election, a minority government or an unwieldy alliance of three blocs.
Any of those scenarios would be likely to hasten the exit of Merkel, chancellor for almost 14 years, who has handed over the leadership of her Christian Democrats (CDU) to protege Annegret Kramp-Karrenbauer. Merkel has said she will not stand again as chancellor of Europe's biggest economy.
Kramp-Karrenbauer has failed to boost the CDU and in the Forsa poll, only 19% of respondents said they would back her as chancellor in a direct vote, two points down from a week ago.
The SPD have yet to decide how to elect their next leader and no one has yet stepped forward.
The weekly Der Spiegel ran a title story on Kevin Kuehnert, the hoody-wearing 29-year-old head of the SPD youth wing, a divisive figure who campaigned against the grand coalition last year and wants to shift the party to the left.
It quoted some party members as saying they would like him to stand as leader and others saying it would be madness.
The media-savvy Kuehnert is no stranger to controversy; last month he caused a storm by saying companies such as carmaker BMW should be taken into collective ownership.
Reporting by Madeline Chambers; Editing by Kevin Liffey

redpajama_set_name: RedPajamaCommonCrawl


text:
Tornado watch canceled, but strong winds still expected
Corey Ohlenkamp
The Star Press
MUNCIE, Ind. – The National Weather Service canceled a tornado watch that had been issued for Delaware County on Thursday. The watch covered most of central, eastern and southern Indiana, including Henry, Wayne and Randolph counties.
A wind advisory is still in effect for the local area. The NWS issued an advisory that will last from 11 a.m.-11 p.m. with expected peak wind gusts of 45 to 55 mph.
The tornado watch was supposed to last until 5 p.m.
Tonight's forecast is calling for a chance of showers and thunderstorms before 9 p.m. with a slight chance of showers between 9-10 p.m. Some of the storms could be severe.
► Southern Indiana, northern Kentucky hit by tornadoes, strong storms
Friday's weather could see more rain showers after 9 a.m. mixing with snow after 11 a.m. The area will also have wind tomorrow with gusts as high as 29 mph.
Jill Coleman, a geography professor at Ball State University, says the early spring is prime time for conditions to develop a high-intensity storm system.
"Around this time of year, we have an influx of strong moisture-laden winds coming in from the south at the low levels and strong upper level winds coming in from the west," she said. "This configuration along with some other factors is prime for developing a strong low-pressure system with a variety of weather conditions."
Coleman said the central plains storm system currently moving into are area is getting widespread attention for having blizzard conditions in the central and northern plains while areas ahead of the storm are contending with thunderstorms, tornadoes and flash flooding.
The storm system that generated the local watch has already caused a tornado warning in Vanderburgh and East central Posey counties in southwestern Indiana as well as Northwestern Henderson County in northwestern Kentucky.
Evansville saw heavy rains, damaging winds and dime-sized hail. Multiple reports of downed trees, power lines and utility poles were also reported.


Powersystems UK Ltd is a high voltage engineering company specialising in electrical power infrastructure, grid connections and renewable energy generation. We are seeking a highly motivated individual with good administrative experience to join our friendly team as an Engineering Administrator in our Bristol office.
You will be the first point of contact for the company, in person, over the telephone and via email. You will be responsible for the general smooth running of the office and supporting our Engineering Department. This is a full-time role based in our Yate office. Hours of working are 9am - 5pm Monday to Friday.
Acting as first point of contact for the company, face to face, over the telephone and via email.
Compile operation & maintenance manuals, which could include editing technical drawings and other diagrams.
To carry out location of utility services in relation to specific projects. To include liaison with relevant council to obtain necessary licences to carry out road working, submittal of relevant licences and notice to work documents to council and liaison with civil contractor.
Highly competitive salary, dependent on experience and qualifications.
Powersystems UK Ltd is an Employee Owned Business and as such has a keen interest in the well-being of all its employees. We encourage and empower you to be imaginative, share great ideas and be involved in the success of our business.
We offer a positive working environment, relaxed in terms of some approaches, yet highly professional with excellent support mechanisms in place to develop your knowledge and career. If you believe that you have what it takes to power our future together then we wish to hear from you.


text:
Camp Lejeune Injury Lawsuits – CALL NOW
Near the sprawling Marine Corps Base Camp Lejeune along the North Carolina coastline, toxic agents seeped into the soil at fuel depots, base junkyards, and even a dry cleaner. The chemicals poisoned groundwater for over 34 years, beginning in 1953. Millions of Marines and their family members drank, cooked, and bathed in the water. Exposure to these dangerous chemicals is linked to serious health hazards.
When we sent our service members into harm's way, we promised to care for them and their loved ones—and pay for that care—upon their return. Yet, Congress has been slow to honor this pact. But the Camp Lejeune Justice Act of 2021 will change that.
The Camp Lejeune Justice Act allows anyone who lived or worked at the base from August 1, 1953, to December 31, 1987, for at least 30 days, exposed to the contaminated water and suffered injuries, to file a claim against the U.S. government.
The time frame to file a Camp Lejeune water contamination lawsuit is limited. So, it's essential to act quickly. All injury claims that occurred before the passage of the Camp Lejeune Justice Act of 2021 will have two years from the passing of the act to file their case.
When we sent our service members into harm's way, we promised to care for them and their loved ones—and pay for that care—upon their return. Yet, Congress has been slow to honor this pact. But the Camp Lejeune Justice Act under the Honoring Our PACT Act changed that.
The time frame to file a Camp Lejeune water contamination lawsuit is limited. So, it's essential to act quickly. All injury claims that occurred before the passage of the Camp Lejeune Justice Act have two years from August 10, 2022 to file their case.
CALL NOW FOR A FREE CASE EVALUATION


MEMPHIS, Tenn. — Authorities have made an arrest after a house was riddled with bullets last week.
That's when a man in the back seat opened fire, sending bullets flying into the home and nearby cars as the family ducked for cover. Authorities said there were at least two children inside the home at the time and the victim's husband and his mother were sitting on the front porch. Thankfully, no one was injured.
Several days after the shooting, two of the victims were able to identify Sherman James as the driver the night of the shooting. James voluntarily turned himself in and was booked into the Shelby County Jail.
He was charged with attempted first-degree murder and reckless endangerment with a deadly weapon.
Two other suspects are still at large.


text:
Q: FreeRTOS questions on LED control I'm trying to make an HTTP controlled LED. One end is a website (not made by me, but by the people that proposed this challenge) and the other end is just a button.
The website contains a toggle switch that controls the LED status:

And the tactile switch has no state retention.
I created a task with freeRTOS to constantly check the value of the LED variable and turn it on or off accordingly, but I feel thisn isn't the proper way to do this, since it's always setting the gpio pin to high, not just when it switches.
void LEDControl (void *parameter) {
    // ESP_LOGI(TAG, "Led status %d", LED);
    while (1)
    {
        if (LED)
        {
            gpio_set_level(LEDPIN, 1);
        } else if (!LED) {
            gpio_set_level(LEDPIN, 0);
        }
    }

}

What would be the best solution to this? An event handler?
I have no experience using event handlers or interrupts, so this is new for me.
Also, for my button status: should I have a task that monitors when the button is pressed? I think that this is not a proper implementation, also. Should I go for interrupts?
I'm constantly having watchdog triggers. I'm assuming my task is taking way too long and something is not working properly.
void buttonAction (void *parameter) {
    // setup
    char output_buffer[MAX_HTTP_OUTPUT_BUFFER] = {0};
    int content_length = 0;
    esp_http_client_config_t config = {
        .url = "link-to-web-api",
        .method = HTTP_METHOD_POST,
    };
    esp_http_client_handle_t client = esp_http_client_init(&config);
    esp_http_client_set_header(client, "Content-Type", "application/json");
    char *post_data;
    esp_err_t err;
    while (1)
    {
        if (gpio_get_level(Button) == 0) {
            if(xSemaphoreTake(LED_Mutex, 0)) {
                LED = !LED;
                // POST REQUEST,
                post_data = (char *) pvPortMalloc(15 * sizeof(char));
                if (LED == false)
                {
                    memcpy(post_data, "{\"value\":\"0\"}", 14);
                    ESP_LOGI("Post Data:", "%s", post_data);
                } else {
                    memcpy(post_data, "{\"value\":\"1\"}", 14);
                    ESP_LOGI("Post Data:", "%s", post_data);
                }
                err = esp_http_client_open(client, strlen(post_data));
                if (err == ESP_OK) {
                    esp_http_client_write(client, post_data, strlen(post_data));
                    ESP_LOGI(TAG, "%s", post_data);
                    vPortFree(post_data);
                    content_length = esp_http_client_fetch_headers(client);
                    if (content_length >= 0) {
                        esp_http_client_read_response(client, output_buffer, MAX_HTTP_OUTPUT_BUFFER);
                    }
                }
                esp_http_client_cleanup(client);
                xSemaphoreGive(LED_Mutex);
            }
        }
    }
}

A:
it's always setting the gpio pin to high, not just when it switches.

Since setting a GPIO output takes no significant time, repeatedly asserting an output to the same state is not generally a problem.

I'm constantly having watchdog triggers. I'm assuming my task is taking way too long

That is not the problem; rather your LED task loop never yields so will only be preempted by interrupts and higher priority tasks (or same priority tasks if you have round-robing scheduling enabled).  Well behaved tasks in an RTOS environment must block on some event be that time passed (a delay), a task event flag, a semaphore, message arrival or some other IPC or task-synchronisation mechanism.
In this case a simple delay would prevent LEDControl() from hogging the CPU:
void LEDControl( void* )
{
    for(;;)
    {
        // Update LED 10 times per second
        gpio_set_level( LEDPIN, LED ? 1 : 0 ) ;
        vTaskDelay( 100 / portTICK_PERIOD_MS ) ;
    }
}

Note also that your buttonAction() task has the same problem and does not yield the CPU while polling for button presses, and should have:
for(;;)
{
    if (gpio_get_level(Button) == 0)
    {
         ...
    }

    // Poll 10 times/second
    vTaskDelay( 100 / portTICK_PERIOD_MS ) ;
}

If you only want to update the LED on change of button state, you could do:
void LEDControl( void* )
{
    bool previous_LED = LED ;
    gpio_set_level( LEDPIN, LED ? 1 : 0 ) ;

    for(;;)
    {
        // On change of state...
        if( LED != previous_LED )
        {
            // Update LED state
            gpio_set_level( LEDPIN, LED ? 1 : 0 ) ;
            previous_LED = LED ;
        }
        vTaskDelay( 100 / portTICK_PERIOD_MS ) ;
    }
}

However there is no real benefit in terms of performance, and a distinct disbenefit in terms of complexity.  The general technique however may have merit in other circumstances - where you need to perform processing once-only on change of state.
That said a better method (and more generally applicable to other scenarios) is not to poll a shared memory variable (LED in this case), but to use the RTOS support for task signalling and synchronisation.  In this case buttonAction() might simply set a binary semaphore on change-of state, such that LEDControl() would become:
static volatile int LED_state = 0 ;

void LEDControl( void* )
{
    for(;;)
    {
        // wait for toggle semaphore
        xSempahoreTake( sem_led_toggle, portMAX_DELAY ) ;

        // Set LED state
        gpio_set_level( LEDPIN, LED_state ) ;
    }
}

That way LEDControl() is only active when a change of state is required - minimising CPU usage.  In this example, that is perhaps not critical, but in non-trivial applications with many tasks and scheduling events, the general pattern can be used to ensure optimum CPU utilisation.
Then in buttonAction() in place of:
LED = !LED ;

you would have:
LED_state = !LED_state ;
xSemaphoreGive( sem_led_toggle ) ;

With respect to the buttonAction() task, it is not clear what the mutex is for in buttonAction().  Mutexes are for protecting resources, but its name suggests that resource is the LED, or possibly simply the variable LED.  Neither seems to be necessary and the mutex is in any case held for much longer that the access to LED.  Moreover a mutex serves no purpose is only one task ever takes it - the resource is already mutually exclusive by virtue of being accessed in only one task.  If the mutex is in fact protecting some other resource, such as the HTTP stack, then a less misleading name should be used, but in that case I would hope that the HTTP API was already thread safe.
Also the large and permanently allocated output_buffer is wasteful and unnecessary since you do not actually use that data.  Use esp_http_client_flush_response to discard unwanted response data.  A further issue is the clear resource leak where post_data is allocated unconditionally, but only deallocated when esp_http_client_open is not in error.  It is a short and fixed length buffer and need not be dynamically allocated at all.
I would suggest something like:
void buttonAction( void* )
{
    // setup
    esp_http_client_config_t config = {
        .url = "link-to-web-api",
        .method = HTTP_METHOD_POST,
    };
    esp_http_client_handle_t client = esp_http_client_init(&config);
    esp_http_client_set_header(client, "Content-Type", "application/json");

    for(;;)
    {
        if (gpio_get_level(Button) == 0)
        {
            // Toggle LED
            LED_state = !LED_state ;
            cSemaphoreGive( sem_led_dem )

            char post_data[15] = {0} ;
            sprintf( post_data,
                     "{\"value\":\"%c\"}",
                     LED_State ? '1' : '0' ) ;
            ESP_LOGI("Post Data:", "%s", post_data);

            esp_err_t err = esp_http_client_open(client, strlen(post_data));
            if( err == ESP_OK )
            {
                esp_http_client_write(client, post_data, strlen(post_data));
                ESP_LOGI(TAG, "%s", post_data);

                int content_length = esp_http_client_fetch_headers(client);
                if( content_length >= 0 )
                {
                    int discard_count = 0 ;
                    esp_http_client_flush_response( client, *discard_count ) ;
                }
            }

            esp_http_client_cleanup(client);
        }

        // Button polling 10 per second
        vTaskDelay( 100 / portTICK_PERIOD_MS ) ;
    }
}

All that said, and with respect to:

Also, for my button status: should I have a task that monitors when the button is pressed? I think that this is not a proper implementation, also. Should I go for interrupts?

The task LEDControl() serves no real purpose here other than to demonstrate two communicating sequential processes.  Even if that is the sole purpose of this exercise it would make more sense from a design point of view to have one task that polls the button and toggles the LED, and gives a binary semaphore to separate task that deals with the HTTP interaction.  That would be a far more cohesive design and make more sense in a terms of real-time processing since the button polling and LED toggling are short and deterministic whereas you have no control over the timing and performance of the network interaction, which would in your implementation interfere with the timing of your button polling and responsiveness of the LED setting.
So in that case:
static volatile int LED_state = 0 ;

void buttonAction( void* )
{
    bool button_down = gpio_get_level(Button) == 0 ;
    gpio_set_level( LEDPIN, LED_state ? 1 : 0 ) ;

    for(;;)
    {
        // On button-down event...
        if( !button_down && gpio_get_level(Button) == 0 )
        {
            button_down = true ;

            // Toggle and set LED state
            LEDstate = !LED_state
            gpio_set_level( LEDPIN, LED_state ) ;

            // Trigger HTTP
            xSemaphoreGive( http_trigger_sem ) ;
        }
        // On button release...
        else if( gpio_get_level(Button) != 0 )
        {
            button_down = false ;
        }

        // Button polling 10 per second
        vTaskDelay( 100 / portTICK_PERIOD_MS ) ;
    }
}

void httpTask( void* )
{
    // setup
    esp_http_client_config_t config = {
        .url = "link-to-web-api",
        .method = HTTP_METHOD_POST,
    };
    esp_http_client_handle_t client = esp_http_client_init(&config);
    esp_http_client_set_header(client, "Content-Type", "application/json");

    for(;;)
    {
        // wait for event trigger`
        xSempahoreTake( http_trigger_sem, portMAX_DELAY ) ;

        char post_data[15] = {0} ;
        sprintf( post_data,
                 "{\"value\":\"%c\"}",
                 LED_State ? '1' : '0' ) ;
        ESP_LOGI("Post Data:", "%s", post_data);

        esp_err_t err = esp_http_client_open(client, strlen(post_data));
        if( err == ESP_OK )
        {
            esp_http_client_write(client, post_data, strlen(post_data));
            ESP_LOGI(TAG, "%s", post_data);

            int content_length = esp_http_client_fetch_headers(client);
            if( content_length >= 0 )
            {
                int discard_count = 0 ;
                esp_http_client_flush_response( client, *discard_count ) ;
            }
        }

        esp_http_client_cleanup(client);
    }
}

By using a binary rather then a counting semaphore it will prevent an HTTP traffic storm that the web interface might not keep up and which would lag the actual LED state. The current LED_state is passed regardless of how many times it may have toggled while the previous HTTP exchange was in progress.
While you could use an interrupt for the button rather then polling, it is probably unnecessarily complex and you would have to deal with switch debounce to prevent multiple interrupts toggling the LED repeatedly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: EmguCV Canny black window i have another question. Idk what is happening buti tried to make Canny edge detector. Problem is that when i want to detect edges on simple shape like square, the program is able to detect it. But when i want to detect shapes on not very simple image program just gives me image filled by only black color. Do you guys have an idea what is going on?
I use this code below:
 public Bitmap CannyEdge(Bitmap bmp)
    {
        Image<Gray, Byte> Cannybmp;
        Image<Gray, Byte> GrayBmp;
        Image<Bgr, Byte> orig = new Image<Bgr, Byte>(bmp);
        Image<Bgr, Byte> imgSmooth;
        Bitmap output;

        imgSmooth = orig.PyrDown().PyrUp();
        imgSmooth._SmoothGaussian(3);
        GrayBmp = imgSmooth.Convert<Gray, byte>();

        Gray grayCannyThreshold = new Gray(160.0);
        Gray grayThreshLinking = new Gray(80.0);

        Cannybmp = GrayBmp.Canny(grayCannyThreshold.Intensity, grayThreshLinking.Intensity);
        output = Cannybmp.ToBitmap();

        //int a = 5;
        return output;

    }

private void button1_Click(object sender, EventArgs e)
    {
        Bitmap bmp = new Bitmap(pictureBox1.Image);
        pictureBox2.Image = CannyEdge(bmp);
    }

A: Did you try to set your grayCannyThreshold to become lesser the value of your grayThreshLinking?
Gray grayCannyThreshold = new Gray(80.0);
Gray grayThreshLinking = new Gray(160.0);


Suzannah B. Troy artist: Lance Armstrong Could Pay $135 Mill if he loses lawsuits and Like Joe Tacopina addicted to suing Sports Reporters? Athletes Politicians from Albany to City Hall to NYPD Commit Perjury Not Arrested?
Lance Armstrong Could Pay $135 Mill if he loses lawsuits and Like Joe Tacopina addicted to suing Sports Reporters? Athletes Politicians from Albany to City Hall to NYPD Commit Perjury Not Arrested?
Lance Armstrong who repeatedly lied under oath as well sued newspaper reporters and newspapers and won even though he commuted the crime of perjury.
Juliet Macur writes Armstrong may have to pay $135 Million dollars if he loses ever lawsuit!
She doesn't hit upon the fact Lance Armstrong should be in jail for perjury.
How many NY NYC political officials NYPD IAB DA ADAs former ADAs willing to commit perjury not concerned about jail like Lance Armstromg? Mayor Bloomberg and accidental gov Paterson I allege commited perjury no jail.
NYPD chief Marino sure likes his HGH doesn't he?
Joe Tacopina A-Fraud's foul loud mouth lawyer is small time compared to Armstrong but like LA he is addicted to intimidating threatening people and the need for face time as well as portraying himself as a victim. By the way what ever happened to Baby Lisa.
Tacopina ratted out his client BFF KERIK like Sheryl Crow took a proffer agreement along with A-Rod -- proffer agreements aka spill the beans and avoid jail is the new Black?
Tacopina, A-Rod and even Crow used drugs? Just wondering. Crow looked especially fit while dating Armstrong. She knew he was cheating.
Joe Tacopina do you have any knowledge of NYPD Internal Affairs DA corruption fixing favors intimidation?
A question I want him to answer under oath along with questions I have for top brass NYC gov NYPD re NY Pensions. For Cy Vance I have questions re NYPD IAB PBA 911 St Vincent Hospital OWS and a lot more.
Joe Tacopina Loses Super Liar oops Super Lawyer Status?


text:
Art Watch: First Delco art studio tour
Posted by ChaddsFordLive on October 11th, 2016
Joe Milligan's Art Studio
Following the tremendous success of the Chester County Studio Tour that is held every spring, Delaware County now has its very first Delaware County Studio Tour this Saturday, Oct. 15, from 10 a.m. to 6 p.m., and Sunday, Oct. 16 from 11 a.m. to 5 p.m.
The Studio Tours were created by artist Jeff Schaller to promote regional art by presenting a brought variety of original art works by local artists, in the inspiring setting of the artist's studio.
This weekend, visitors will have the opportunity to visit 17 studios, many of which will also host other visiting artists. Most every artistic medium is represented, including: painting, sculpture, jewelry, photography, clay, glass, paper and fiber. In all, 45 artists will be showing and selling their original art work over this very special weekend for art in Delaware County.
Visitors are encouraged to design their own self-guided tour of the art studios with the catalogue and map, which can be downloaded from www.DelawareCountyStudioTour.com. Additionally, the printed catalogues will be available at the studios the week of the tour and at local businesses around Delaware County..
All of the artists will be on hand to talk about their work and meet buyers and browsers alike. Whether this is your first time buying art or you are a seasoned collector, this tour has something for everyone, in a wide range of mediums and prices.
Try to get up early to get to your favorite artist studio so that you can purchase the "County Collector" piece. The "County Collector Series", well-known from the Chester County Studio Tour, is an opportunity to collect an original framed 6" x 6" piece of art for the special pricing of $75. Two-dimensional artists have created an original work of art in a simple and elegant 6" x 6" frame, and three-dimensional artists have also created special pieces for this Collector Series. A photo of each work in this series is included in the event catalogue, and may also be seen currently on the website.
One of the great artists in the tour is painter Alan Soffer, who recently has a solo show at Church Street Gallery in West Chester. Soffer's art studio is open to the public at 2 Blackhorn Road in Wallingford, and ceramic artist Mitch Lyons will be at that location as well. Offer says that he will be showing a very broad range of his work, encaustic paintings, figurative work, ceramics, and more experimental pieces including solar prints.
Lacunae by Alan Soffer
He says that he "loves doing an open studio show" and that he "can have all kinds of work from past to present which I rarely show in galleries." He explains that his studio "is probably more cluttered than most as it is in constant motion," but isn't that part of the fun of a studio tour? See the artwork, meet the artists, and get a sense of the artistic process, inspiration and fun that goes into creating a piece of art.
Also on the map are six of the fine art galleries and art associations in Delaware County. This is an excellent opportunity to check out The Main Line Art Center , The Beauty Art Gallery, Community Art Center, Art on the Avenue of the Stars and the Wayne Art Center. The Main Line Art Center, located at 746 Panmure Road in Haverford, will be exhibiting "Panorama 2016, Enlightened Earth" in October, which "investigates the delicate imbalance of nature, technology, and humanity through photography and digital media." This show features works by Mark Dorf, Julianna Foster, and Nick Pedersen, curated by new Executive Director Amie Potsic.
Ceramic work by Marcia Reiver
About CFLive Staff
See Contributors Page http://chaddsfordlive.com/writers/
A Virtual Gallery


text:
Primary Appearance:
The Batman/Superman Adventure Hour Cartoon Series
Color(s):
Black exterior/Red interior
Although the Batman TV series was cancelled, Batman wouldn't be off the air for long. Thanks to Filmation, Batman appeared as an animated TV character for the first time in 1968. The cartoon didn't last too long the first time around, but Filmation tried their hand at Batman again in 1977 with the new The New Adventures of Batman paired with the second-season Tarzan, Lord Of The Jungle to create The Batman/Tarzan Adventure Hour. This new series retained most of the elements from the previous show, along with some new additions like the Bat Mite.
Though it does draw some influence from the Futura Batmobile, this car isn't as strong an homage as other cars of the time: the nose, "Coke bottle" sides and full-width tail light are clearly late-'60s items. Another unusual design combination was the single solid windshield with twin headrest designs that mimicked the rear canopies from the Futura. Other special features included a retractable jet exhaust, drag and rescue parachutes, a chain slicer, a "hover" mode, and emergency flotation pontoons.


text:
VDOT RoadWatch: Route 819 in Union Hall To Temporarily Close April 22
(NEW 4-10-20) * ROUTE 819 CLOSURE – Effective at 8 a.m. on April 22, a section of Route 819 (Buckscrape Road) is scheduled to be closed for a culvert installation. The closure is located .3 miles north of Route 40 (Old Franklin Turnpike) to .85 miles south of 662 (Old Salem School Road). The road is scheduled to be closed until 5 p.m. on April 24.
The intersection of Old Franklin Turnpike (Route 40) and Buckscrape Road (Route 819) in the Union Hall area of Franklin County via Google Maps.
(UPDATED 3-20-20) * CALLAWAY ROAD UTILITY WORK – MMI will be installing fiber optic along Callaway Road from Grassy Hill Road to Bent Mountain Road during daytime hours, 9 a.m. to 3 p.m., Monday through Friday and 7 a.m. to 3:30 p.m. on Saturdays. Motorists should expect shoulder or lane closures for travel in both directions. Intermittent full closures of the highway will be required for periods lasting no longer than 15 minutes.
(UPDATED 4-17-20) * ROUTE 789 CLOSURE – On April 6, at 8 a.m., a section of Route 789 (Dry Hill Road) is scheduled to be closed for a pipe replacement. This closure is located .690 mile from Route 964 (Barton Spur Road) and .405 mile from Route 637 (Griffith Hill). The road is scheduled to be closed until midnight on April 23, 2020.
(UPDATED 3-20-20) * ROUTE 775 CLOSURE – Route 775 (Iron Ridge Road) is closed to traffic as an emergency closure due to a washout. The road will remain closed until further notice.
(UPDATED 2-14-20) * ROUTE 122 BRIDGE REPLACEMENT – Route 122 (Booker T Washington Highway) will be under a flagging operation during daytime hours for a bridge replacement project over Blackwater River. The bridge is located between Route 40 and the intersection with Angle Plantation Road. Drivers can expect some delays for flagging during construction of the new bridge, Monday through Friday, 9 a.m. to 3 p.m. and Saturday, 7 p.m. to 6 a.m. the following morning. A barrier wall will be in place. The project is expected to be completed in November 2020.
Previous Mad Iguanas, Monster Atlantic Stream Via Cable 12 at the Harvester This Weekend
Next Replay: Ask Our Local Virginia Department of Health Spokesperson Your Questions


The European Conference on Plasma Diagnostics is a biennial event which aims at bringing together physicists or other scientists working on diagnostics for magnetic confinement fusion, beam plasmas and inertial fusion, low-temperature and industrial plasmas, and basic and astrophysical plasmas.
The third edition of the Conference will take place in Lisbon, Portugal starting from 6th and finishing on 9th of May 2019. In the previous edition held in Bordeaux in 2017 more than 200 scientists from all over Europe and overseas took part in this event and an even bigger number is expected to take part in the third edition of the conference in Lisbon.
The ECPD will take place in alternate years with respect to the HTPD conference in the USA.
3 prizes (350 €/each) will be sponsored by EPS for the best poster for students.


text:
Q: Java and Algebra I'm making a program that will find a fraction of the distance between two points from a point. The Problem is, is that I need an algorithm to find the X distance between two points as well as the Y distance, not just the straight distance in itself.
For example, 2/3 the distance from A to B. (A and B being on a graph)

try {
                String a;
                a = x1_tf.getText().toString();
                double x1 = Integer.parseInt(a);

                a = y1_tf.getText().toString();
                double y1 = Integer.parseInt(a);

                a = x2_tf.getText().toString();
                double x2 = Integer.parseInt(a);

                a = y2_tf.getText().toString();
                double y2 = Integer.parseInt(a);

                double Ax,Ay, x = 0,y = 0,nx,ny,fx = 0,fy = 0;
                double numerator = Integer.parseInt(fracx_tf.getText().toString());
                double denominator = Integer.parseInt(fracy_tf.getText().toString());

                if(fromwhat_combobox.getSelectedIndex()==0) {
                    Ax = Integer.parseInt(x1_tf.getText().toString());
                    Ay = Integer.parseInt(y1_tf.getText().toString());

                    //problem below
                    x += Math.sqrt(Math.pow(Ax, 2)) + Math.sqrt(Math.pow(Ay, 2));
                    y += Math.sqrt(Math.pow(Ay, 2)) + Math.sqrt(Math.pow(Ax, 2));
                    //problem lies here ^^^^
                }
                else {
                    Ax = Integer.parseInt(x2_tf.getText().toString());
                    Ay = Integer.parseInt(y2_tf.getText().toString());

                    //problem below
                    x += Math.sqrt(Math.pow(Ax, 2)) + Math.sqrt(Math.pow(Ay, 2));
                    y += Math.sqrt(Math.pow(Ay, 2)) + Math.sqrt(Math.pow(Ax, 2));
                    //problem lies here ^^^^
                }

                nx = (x*numerator)/denominator;
                ny = (y*numerator)/denominator;
                fx = Ax + nx;

                if((y2-y1)/(x2-x1)>=0) {
                    fy = Ay + ny;
                }
                else {
                    fy = Ay - ny;
                }

                String answer = "("+fx+","+fy+") is "+numerator+"/"+denominator+" way from ";
                output_pane.setText(answer);
            }catch(Exception e){}

All of the other code works fine, I just need help with an algorithm that finds the distance between two points on the x-grid as well as the y-grid. The only thing I can think of is a complicated for-loop or a giant nest of if loops.
JUST TO CLARIFY :
fromwhat_combobox is a selection of what point to use, IE, 2/5 the distance from which point, Ax and Ay represent the coordinates of that point. The rest is easy to figure.
Complete code...
import java.awt.event.FocusEvent;

public class DistanceBetweenPointsCALC extends javax.swing.JFrame {

    public DistanceBetweenPointsCALC() {
        initComponents();  //default init components
        cinitComponents(); // custom init components
        oinitComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        calc_button = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        output_pane = new javax.swing.JTextPane();
        y1_tf = new javax.swing.JTextField();
        x2_tf = new javax.swing.JTextField();
        y2_tf = new javax.swing.JTextField();
        x1_tf = new javax.swing.JTextField();
        frac_checkbox = new javax.swing.JCheckBox();
        fromwhat_combobox = new javax.swing.JComboBox();
        fracx_tf = new javax.swing.JTextField();
        fracy_tf = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        calc_button.setText("Calc");

        jScrollPane1.setViewportView(output_pane);

        y1_tf.setText("Y1");

        x2_tf.setText("X2");

        y2_tf.setText("Y2");

        x1_tf.setText("X1");

        frac_checkbox.setText("Fraction of the Distance");

        fromwhat_combobox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "From X1", "From X2" }));

        fracx_tf.setText("frac x");

        fracy_tf.setText("frac y");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(calc_button, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(x2_tf, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
                                    .addComponent(x1_tf))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(y1_tf, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE)
                                    .addComponent(y2_tf))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(fromwhat_combobox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(fracy_tf)
                            .addComponent(fracx_tf)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(frac_checkbox)
                        .addGap(0, 254, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(x1_tf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(y1_tf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(fromwhat_combobox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(x2_tf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(y2_tf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(fracx_tf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(calc_button)
                    .addComponent(fracy_tf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(frac_checkbox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    public void cinitComponents() {

        calc_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                calc_buttonAP(evt);
            }
        });

        frac_checkbox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                frac_checkboxAP(evt);
            }
        });

        fracx_tf.setEnabled(false);
        fracy_tf.setEnabled(false);
        fromwhat_combobox.setEnabled(false);
    }

    public void oinitComponents() {
        x1_tf.addFocusListener(new java.awt.event.FocusListener() {
            String DEFAULT_TEXT = "X1";
            @Override
            public void focusGained(FocusEvent e){
                String s = x1_tf.getText();
                if(s.equals(DEFAULT_TEXT)) { x1_tf.selectAll(); }
            }
            @Override
            public void focusLost(FocusEvent e) {
                String s = x1_tf.getText();
                if(s.length()<=0) { x1_tf.setText("X1"); }
            }
        });

        y1_tf.addFocusListener(new java.awt.event.FocusListener() {
            String DEFAULT_TEXT = "Y1";
            @Override
            public void focusGained(FocusEvent e){
                String s = y1_tf.getText();
                if(s.equals(DEFAULT_TEXT)) { y1_tf.selectAll(); }
            }
            @Override
            public void focusLost(FocusEvent e) {
                String s = y1_tf.getText();
                if(s.length()<=0) { y1_tf.setText("Y1"); }
            }
        });

        x2_tf.addFocusListener(new java.awt.event.FocusListener() {
            String DEFAULT_TEXT = "X2";
            @Override
            public void focusGained(FocusEvent e){
                String s = x2_tf.getText();
                if(s.equals(DEFAULT_TEXT)) { x2_tf.selectAll(); }
            }
            @Override
            public void focusLost(FocusEvent e) {
                String s = x2_tf.getText();
                if(s.length()<=0) { x2_tf.setText("X2"); }
            }
        });

        y2_tf.addFocusListener(new java.awt.event.FocusListener() {
            String DEFAULT_TEXT = "Y2";
            @Override
            public void focusGained(FocusEvent e){
                String s = y2_tf.getText();
                if(s.equals(DEFAULT_TEXT)) { y2_tf.selectAll(); }
            }
            @Override
            public void focusLost(FocusEvent e) {
                String s = y2_tf.getText();
                if(s.length()<=0) { y2_tf.setText("Y2"); }
            }
        });
    }

    public static void main(String args[]) {
        /*Look and feel set to Windows*/
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DistanceBetweenPointsCALC.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DistanceBetweenPointsCALC.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DistanceBetweenPointsCALC.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DistanceBetweenPointsCALC.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DistanceBetweenPointsCALC().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    public static javax.swing.JButton calc_button;
    public static javax.swing.JCheckBox frac_checkbox;
    public static javax.swing.JTextField fracx_tf;
    public static javax.swing.JTextField fracy_tf;
    public static javax.swing.JComboBox fromwhat_combobox;
    public static javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane output_pane;
    public static javax.swing.JTextField x1_tf;
    public static javax.swing.JTextField x2_tf;
    public static javax.swing.JTextField y1_tf;
    public static javax.swing.JTextField y2_tf;
    // End of variables declaration

    /**
     * Action(s) performed below
     */

    public void calc_buttonAP(java.awt.event.ActionEvent evt) {
        if(frac_checkbox.isSelected()) {
            try {
                String a;
                a = x1_tf.getText().toString();
                double x1 = Integer.parseInt(a);

                a = y1_tf.getText().toString();
                double y1 = Integer.parseInt(a);

                a = x2_tf.getText().toString();
                double x2 = Integer.parseInt(a);

                a = y2_tf.getText().toString();
                double y2 = Integer.parseInt(a);

                double Ax,Ay, x = 0,y = 0,nx,ny,fx = 0,fy = 0;
                double numerator = Integer.parseInt(fracx_tf.getText().toString());
                double denominator = Integer.parseInt(fracy_tf.getText().toString());

                if(fromwhat_combobox.getSelectedIndex()==0) {
                    Ax = Integer.parseInt(x1_tf.getText().toString());
                    Ay = Integer.parseInt(y1_tf.getText().toString());
                    x += Math.sqrt(Math.pow(Ax, 2)) + Math.sqrt(Math.pow(Ay, 2));
                    y += Math.sqrt(Math.pow(Ay, 2)) + Math.sqrt(Math.pow(Ax, 2));
                    //problem lies here ^^^^
                }
                else {
                    Ax = Integer.parseInt(x2_tf.getText().toString());
                    Ay = Integer.parseInt(y2_tf.getText().toString());
                    x += Math.sqrt(Math.pow(Ax, 2)) + Math.sqrt(Math.pow(Ay, 2));
                    y += Math.sqrt(Math.pow(Ay, 2)) + Math.sqrt(Math.pow(Ax, 2));
                    //problem lies here ^^^^
                }

                nx = (x*numerator)/denominator;
                ny = (y*numerator)/denominator;
                fx = Ax + nx;

                if((y2-y1)/(x2-x1)>=0) {
                    fy = Ay + ny;
                }
                else {
                    fy = Ay - ny;
                }

                String answer = "("+fx+","+fy+") is "+numerator+"/"+denominator+" way from ";
                output_pane.setText(answer);
            }catch(Exception e){}
        }
        else if(!frac_checkbox.isSelected()) {
            try {
            String a;
            a = x1_tf.getText().toString();
            double x1 = Integer.parseInt(a);

            a = y1_tf.getText().toString();
            double y1 = Integer.parseInt(a);

            a = x2_tf.getText().toString();
            double x2 = Integer.parseInt(a);

            a = y2_tf.getText().toString();
            double y2 = Integer.parseInt(a);

            double finalAnswer = Math.sqrt(Math.pow((x2-x1),2)+Math.pow((y2-y1),2));
            double var1 = x2-x1;
            double var2 = y2-y1;
            double var3 = Math.pow(var1, 2);
            double var4 = Math.pow(var2, 2);
            double var5 = var3+var4;
            String answer = "Formula : sqrt( (x2 - x1)^2 + (y2 - y1)^2 )\n"
                          + "sqrt( ("+x2+" - "+x1+")^2 + ("+y2+" - "+y1+")^2 )\n"
                          + "sqrt( ("+var1+")^2 + ("+var2+")^2 )\n"
                          + "sqrt( "+var3+" + "+var4+" )\n"
                          + "sqrt( "+var5+" )\n"
                          + "answer = "+ finalAnswer;
            output_pane.setText(answer);
        }catch(Exception e){ e.printStackTrace(); }
        }
    }

    public void frac_checkboxAP(java.awt.event.ActionEvent evt) {
        if(!frac_checkbox.isSelected()) {
            fracx_tf.setEnabled(false);
            fracy_tf.setEnabled(false);
            fromwhat_combobox.setEnabled(false);
        }
        else if(frac_checkbox.isSelected()) {

            fracx_tf.setEnabled(true);
            fracy_tf.setEnabled(true);
            fromwhat_combobox.setEnabled(true);
        }
    }

    /**
     * EOF
     */
}

A: Here is the distance formula in java code
Math.sqrt( Math.pow( (p1.getX() - p2.getX()) , 2 )) - Math.pow( p1.getY() - p2.getY()) , 2)));

Read square root of x1 - x2 squared minus y1 - y2 squared
a = x1_tf.getText().toString();
double x1 = Integer.parseInt(a);

a = y1_tf.getText().toString();
double y1 = Integer.parseInt(a);

a = x2_tf.getText().toString();
double x2 = Integer.parseInt(a);

a = y2_tf.getText().toString();
double y2 = Integer.parseInt(a);

Math.sqrt( Math.pow( (x1 - x2) , 2 ) - Math.pow( (y1 - y2) , 2) );

See Distance Formula


The Ministry is headed by the Minister of Diaspora of the Republic of Armenia who is appointed and removed from office by the President of the Republic of Armenia by the recommendation of the Prime Minister. The Minister has deputies whom the Prime Minister of the Republic of Armenia appoints and removes from office through consultation with the Minister. During act of service, the Minister is guided by the Constitution, legislation and international treaties of the Republic of Armenia, decrees issued by the President of the Republic of Armenia, the government and resolutions of the Prime Minister of the Republic of Armenia, the existing charter and other legal acts. One of the deputies assigned by the Minister fulfills the duties in the Minister's absence. The Minister has advisers, assistants and a press secretary in Armenia and the Diaspora (also by social order). The Minister may set forms and measures for promotion. The Minister's advisers, assistants and press secretary work together, with the chief of staff, as well as heads of structural subdivisions of the staff and Diaspora Armenian organizations while fulfilling the functions and assignments established by the Minister.


text:
Modern By Design
June 4–August 21, 2011
As part of the High's ongoing collaboration with The Museum of Modern Art, Modern by Design presents groundbreaking designs of the past, present, and future.
Selected Images
Click on an image below to learn more.
Digital Matter by Joris Laarman Lab
Over the past several decades, the transition from analog to digital has begun to define an evolution in the way we manufacture, distribute, and recycle products. With the use of robots and other digital fabrication tools, many materials can be used to create a form of "digital matter," a term used here to describe the three-dimensional realization of digital images through the use of voxels, or volumetric pixels. Robots can perform a variety of tasks, faster and more precisely for longer periods of time than people. With the press of a single button a complex design can be customized, in contrast to traditional manufacturing methods, which require extensive retooling to make the same change. This is due in part to the modular character of the material out of which the object is made, such as Laarman's voxels.
For their installation at the High Museum, Joris Laarman Lab has programmed a robot arm to build ornamented side tables based on a digital blueprint. The video will give you a peek behind the scenes at the Laarman Lab's process. The robot builds the table upside down, from the top to the legs.
The table can be built with varying degrees of detail or resolution, so the smaller the voxel, the higher the resolution. The tables are re-programmable; the high-performance adhesive used to keep the voxels in place can be dissolved, and the voxels can be reassembled and reused to create a different shape without any wasted material.
The Joris Laarman Lab was established in 2004 by Joris Laarman and his partner, filmmaker Anita Star. They consider the lab an experimental playground where craftsmen, scientists, engineers, and many other young, motivated people strive to add cultural meaning to technological progress. Their goal is to show the beauty of how things could work using a hands-on approach and a sense of poetry.
"To me art, design, and science, although traditionally different, have many similar universal qualities. They express human curiosity and inventiveness in the most profound way. When scientists make use of the freedom and emotional creativity of artists, and artists make use of the skill and discipline of scientists, great things can happen." — Joris Laarman
As part of the High's ongoing collaboration with The Museum of Modern Art, Modern by Design presents groundbreaking designs of the past, present, and future. The exhibition features a selection of works chronicling three key moments in MoMA's design collection and exhibition history—"Machine Art" (1934); "Good Design" (1950-1955); and "Italy: The New Domestic Landscape" (1972). Nearly 150 objects created by over 120 of the most influential artists and designers of the twentieth century are included.
Also on view are a group of late-twentieth- and early-twenty-first–century designs drawn from the High's own growing permanent collection. Two new major commissioned installations by Dutch designer Joris Laarman and the Japanese design collective nendo are featured: Laarman's "Digital Matter" and nendo's "Visible Structures." In total, eleven artists represent the diversity and international character of the field today.
Featured artists and designers include Ron Arad, FRONT Design, Johanna Grawunder, Zaha Hadid, Hella Jongerius, Patrick Jouin, Shiro Kuramata, Joris Laarman, nendo, Marc Newson, and Ettore Sottsass Jr.
Organization and Support
This exhibition is a collaboration between The Museum of Modern Art, New York, and the High Museum of Art, Atlanta.
The exhibitions and programs of the MoMA Series are made possible by Presenting Sponsor Bank of America, Lead Sponsors: Portman, The Gary W. and Ruth M. Rollins Foundation, The Coca-Cola Company, Delta Air Lines, Accenture, Turner Broadcasting System, Inc., and Planning Partner The Rich Foundation. The Modern Masters Circle: Margaretta Taylor, Sue and John Wieland. Additional support provided by Carey and Doug Benham, Dr. Robert L. and Lucinda W. Bunnen, Mr. and Mrs. Holcombe T. Green, Jr., Louise Sams and Jerome Grilhot, Paul Hagedorn, Jane and Clay Jackson, Barbara and Sanford Orkin, Catherine N. Rawson, Sara and John Shlesinger, Joan Whitcomb, Tull Charitable Foundation, Jane Smith Turner Foundation, Vasser Woolley Foundation and the Wish Foundation. Support also provided by the Alfred and Adele Davis Exhibition Endowment Fund and the Dorothy Smith Hopkins Exhibition Endowment Fund and an indemnity from the Federal Council on the Arts and Humanities.


TWO LUXURY SAILING YACHTS SOLD IN ONE DAY!
Burgess has announced the sale of two yachts from its luxury sailing fleet on the same day.
The 34.2m (112.2ft) Royal Huisman UNFURLED (pictured above) is a beautiful classic sloop with an Andrew Winch interior and an impressive regatta record. She was sold on Wednesday, as was the 38.8m (127.3ft) GANESHA 1.
Built by Fitzroy Yachts in New Zealand and designed by Dubois, GANESHA 1 (pictured below) has won regattas in St Barth, Palma and Sardinia and boasts a stylish Redman Whiteley Dixon interior.
To find out more about the luxury sailing yachts in the Burgess fleet, please contact a broker now or get in touch with one of our offices directly: London, Monaco, New York, Miami, or all other locations.