text:
Q: Cannot read status the monit daemon, even with allowed group I cannot seem to get monit status or other CLI commands to work.

I've built monit v5.8 to run on a Raspberry Pi. I'm able to add services to be monitored, and the web interface can be accessed just fine, as I've set it up for public read-only access (it's a test server, not my final production setup, so not a big deal right now).
Problem is, when I run monit status while logged in as root I get:
# monit status
monit: cannot read status from the monit daemon

I also have monit started on boot via this /etc/inittab file entry:
mo:2345:respawn:/usr/local/bin/monit -Ic /etc/monitrc

I've verified that monit is running, and I'm getting email alerts anytime I either kill the monit process manually, or reboot my raspberry pi. So, next I check my monitrc file permissions to see which group is allowed access.
# ls -al /etc/monitrc
-rw------- 1 root root 2359 Aug 24 14:48 /etc/monitrc

Here's my relevant allow section of the control file.
set httpd port 80
    allow [omitted] readonly
    allow @root
    allow localhost
    allow 0.0.0.0/0.0.0.0

Also tried setting permissions on this file to 640 to allow group read permissions, but no matter what I try I either get the same error as noted above, or when the permissions are set to 640 I get:
# monit status
monit: The control file '/etc/monitrc' must have permissions no more than -rwx------ (0700); right now permissions are -rw-r----- (0640).

What am I missing here? I know that the httpd must be enabled, as that's the interface that the CLI uses to get information (or so I've read), so I've done that. And in terms of monit doing its monitoring job and sending email alerts, that's all working as well.

Here's my entire monitrc file - again, this is version v5.8, and it was build with both PAM and SSL support. The process runs under the root user:
# Global settings
set daemon 300
    with start delay 5
set logfile /var/log/monit.log
set pidfile /var/run/monit.pid
set idfile /var/run/.monit.id
set statefile /var/run/.monit.state

# Mail alerts
## Set the list of mail servers for alert delivery. Multiple servers may be
## specified using a comma separator. If the first mail server fails, Monit
# will use the second mail server in the list and so on. By default Monit uses
# port 25 - it is possible to override this with the PORT option.
#
set mailserver smtp.gmail.com port 587
               username [omitted] password [omitted]
               using tlsv1

## Send status and events to M/Monit (for more informations about M/Monit
## see http://mmonit.com/). By default Monit registers credentials with
## M/Monit so M/Monit can smoothly communicate back to Monit and you don't
## have to register Monit credentials manually in M/Monit. It is possible to
## disable credential registration using the commented out option below.
## Though, if safety is a concern we recommend instead using https when
## communicating with M/Monit and send credentials encrypted.
#
# set mmonit http://monit:monit@192.168.1.10:8080/collector
#     # and register without credentials     # Don't register credentials
#
#
## Monit by default uses the following format for alerts if the the mail-format
## statement is missing::
set mail-format {
    from: cmn.monit@gmail.com
 subject: $SERVICE $DESCRIPTION
 message: $EVENT

Service:     $SERVICE
Date:        $DATE
Action:      $ACTION
Host:        $HOST
Description: $DESCRIPTION

          Monit instance provided by chicagomeshnet.com
}

# Web status page
set httpd port 80
    allow [omitted] readonly
    allow @root
    allow localhost
    allow 0.0.0.0/0.0.0.0

## You can set alert recipients whom will receive alerts if/when a
## service defined in this file has errors. Alerts may be restricted on
## events by using a filter as in the second example below.

A: Try -v and -vv flags to increase status command verbosity.
The next great tool to debug such problems is strace. Install it and run:
strace -efile -o trace.log monit status

Most likely you'll find the reason near the end of the log. If that doesn't help, run:
strace -f -o trace.log monit status

to see all the syscall-s the program and its children are making. Search for not found, connection refused, and such kind of errors.

A: For me to get it working I had to have a allow admin:monit rule.
set httpd port 2812 and
    use address 0.0.0.0
    allow 0.0.0.0/0
    allow localhost
    allow admin:monit
    allow guest:guest read-only

From this answer and http://dasunhegoda.com/what-why-how-monit/756/


text:
Q: How to get customised message for Joi label What currently I have is this:

example: Joi.boolean()
        .required()
        .invalid(false)
        .label('Disclaimer Checkbox'),

and the output which I am getting is "Disclaimer checkbox contains invalid value".
What I need is label which contain only message which I wrote not  "contains invalid value"

A:   a: Joi.string()
    .min(2)
    .max(10)
    .required()
    .messages({
      'string.base': `"a" should be a type of 'text'`,
      'string.empty': `"a" cannot be an empty field`,
      'string.min': `"a" should have a minimum length of {#limit}`,
      'any.required': `"a" is a required field`
    })
});

A: When defining joi validations , you need to assert messages along with their validation string to define an error message against it , like the example below.
bodyValidation: Joi.integer()
    .min(1997)
    .max(2022)
    .regex(/[0-9],{4}/)
    .required()
    .messages({
      'integer.base': `Entered data should be an integer`,
      'integer.regex': `Entered field is not an year`,
      'integer.min': `Entered Year is less than 1997`,
      'any.required': `Entry is required`
    })
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Subclass references another subclass, accessible from the same getter/setter I am trying to achieve an OOP inheritance design in Java where, if I am presented with a subclass of OrderTypeA, and calling its getOrderLines(), it will return a collection of type OrderLineTypeA. Likewise, if I have an instance of Order, its getOrderLines() will return a collection of instance Collection<OrderLine>
I have tried the following, which does not seem to compile.
What I am trying to achieve:
Proposed Architecture:

Order
public class Order {
    protected List<? extends OrderLine> orderLines;

    public List<? extends OrderLine> getOrderLines() {
        return orderLines;
    }

    public void setOrderLines(List<OrderLine> orderLines) {
        this.orderLines = orderLines;
    }
}

OrderLine
public class OrderLine {
    private Order order;

    public Order getOrder() {
        return order;
    }

    public void setOrder(Order order) {
        this.order = order;
    }
}

OrderTypeA
public class OrderTypeA extends Order {
    protected List<OrderLineTypeA> orderLines;

    @Override
    public List<OrderLineTypeA> getOrderLines() {
        return orderLines;
    }

    @Override
    public void setOrderLines(List<OrderLine> orderLines) {
        this.orderLines = orderLines; // does not compile
    }
}

OrderLineTypeA
public class OrderLineTypeA extends OrderLine {
    private OrderTypeA order;

    @Override
    public Order getOrder() {
        return order;
    }

    @Override // does not compile, technically not an override
    public void setOrder(OrderTypeA order) {
        this.order = order;
    }
}

Other solutions I have tried, includes omitting field declarations in the child classes, in order to hide the field in the parent.
Other ideas include overriding methods in the child, and casting return statements to the type of the child.
Thanks!

A: I think at least one of the problems is here:
public class OrderTypeA extends Order {
protected List<OrderLineTypeA> orderLines;

@Override
public List<OrderLineTypeA> getOrderLines() {
    return orderLines;
}

@Override
public void setOrderLines(List<OrderLine> orderLines) {
    this.orderLines = (List<OrderLineTypeA>)orderLines; // does not compile
}
}

In setOrderLines() in OrderTypeA you try to assign a List of Type OrderLine to a list of type OrderLineTypeA. Assigning a sublclass its parent-type does not work.


text:
Q: Why is javaFX is too slow with arabic on runtime? When I run this code for example, it works normal:
public class AllControlsReff extends Application{

    @Override
    public void start(Stage Scr) throws Exception {
        Scr.show();
        Scr.setTitle("All Controls Reference");

        ScrollPane sp = new ScrollPane();
        VBox vb = new VBox(10);

        TitledPane Tp;
        TilePane numPad;

        for(int i=0;i<20;i++){
            Tp = new TitledPane();
            numPad = new TilePane();
            Tp.setText("English Title: " + i);
            for(int j=0;j<18;j++){
                numPad.setHgap(10);
                numPad.setVgap(10);
                numPad.setPrefColumns(9);
                numPad.setStyle("-fx-font-size:20;");
                Button btn = new Button("button " + j);
                btn.setOnAction(e -> System.out.println("-"));
                numPad.getChildren().add(btn);
            }
            Tp.setContent(numPad);
            vb.getChildren().add(Tp);
        }
        sp.setContent(vb);
        Scene pg = new Scene(sp,1280,720);
        Scr.setScene(pg);
    }
}

but when I use the same example with Arabic language, it works very slowly at runtime, hard to click on buttons or collapse the TitledPanes:
Tp.setText("عنوان بالعربية: " + i);
Button btn = new Button("العربية " + j);

I didn't test on Windows to see the different, currently I use Ubuntu, and run my Java application from terminal.

A: I encountered a similar slowdown on Windows 10 running Java 10 using both methods. I moved the Src.show() to the end of the start method and it seems to have fixed the initial slowdown.
I saw no discernible time delay on button presses in either case.


text:
Q: Разработка мобильного меню для сайта Здравствуйте!
Делаю меню для сайта (при маленьком разрешении)
Ссылка на сайт: Клик
Кажется, что-то получилось, столкнулся с такой проблемой, как незнающий человек спрашиваю у Вас - Как сделать чтобы меню в открытом состоянии скроллилось, а контент сайта нет?
Сейчас меню стоит на месте, а контент на фоне сайта листается, из-за fixed скорее всего.
Прикрепляю всю разметку связанную с меню

var main = function() {

  $('#menumobile').click(function() {

    $('.swipemenu').animate({

      left: '0px'

    }, 200);

    $('.menuoverlay').animate({
      opacity: 0.8
    }, 300);
    $('.menuoverlay').show();

  });

  $('#close').click(function() {

    $('.swipemenu').animate({

      left: '-500'

    }, 200);

    $('.menuoverlay').animate({
      opacity: 0
    }, 300);

    $('.menuoverlay').hide();
  });
};

$(document).ready(main);

$(document).ready(function() {
  $(".menu-list").on("click", "a", function(event) {
    event.preventDefault();

    var id = $(this).attr('href'),

      top = $(id).offset().top;

    $('.swipemenu').animate({

      left: '-500'

    }, 200);

    $('.menuoverlay').animate({
      opacity: 0
    }, 300);

    $('.menuoverlay').hide();

    $('body,html').animate({
      scrollTop: top
    }, 1500);
  });
});
.swipemenu {
  width: 80%;
  background: #eeeeee;
  height: 100%;
  position: fixed;
  top: 4%;
  bottom: 0;
  margin: 0;
  left: -400px;
  -webkit-transition: left 0.3s;
  -moz-transition: left 0.3s;
  transition: left 0.3s;
  z-index: 2000;
}

.imgonmenu {
  margin-left: 27.5%;
  margin-top: 8%;
  position: relative;
}

p.menutitle {
  font-family: 'oswald', sans-serif;
  font-size: 1.8em;
  position: relative;
  margin-left: 25%;
  display: inline-block;
  color: #404040;
}

p.subtitlemenu {
  font-family: 'roboto', sans-serif;
  font-size: 1em;
  position: relative;
  margin-left: 16%;
  display: inline-block;
  color: #404040;
}

.menu-list {
  padding: 0;
  margin: 0;
  max-width: 350px;
}

.menu-list>li {
  list-style: none;
}

.menu-list>li>a {
  display: block;
  color: #000;
  left: 7.5%;
  padding: 10px 10px 10px 40px;
  position: relative;
  transition: .3s;
}

.menu-list>li>a i {
  position: absolute;
  top: 50%;
  left: 5px;
  width: 30px;
  text-align: center;
  transform: translateY(-50%);
}

.menu-list>li>a img {
  position: absolute;
  top: 50%;
  left: 5px;
  width: 30px;
  text-align: center;
  transform: translateY(-50%);
}

.iconsmargin {
  font-size: 1.2em;
  color: #404040;
}

a.menulinks {
  font-family: 'roboto', sans-serif;
  font-size: 1.375em;
  position: relative;
  color: #303030;
  text-decoration: none;
}

p.menutag {
  font-family: 'oswald', sans-serif;
  font-size: 1em;
  position: relative;
  margin-top: 15%;
  margin-left: 7.5%;
  color: #808080;
  display: inline;
}

div.offset {
  position: relative;
  margin-top: 7.5%;
}

div.lineonmenu {
  height: 1px;
  width: 95%;
  left: 5%;
  bottom: 10%;
  position: relative;
  background: #b8b8b8;
  margin-top: 1%;
}

.menuoverlay {
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 10;
  background-color: #000;
  opacity: 0;
  position: fixed;
  cursor: default;
}

  X

Ivan Tvarinsky

Front-end dev. | UI/UX Design

MENU

 Home

 About me

 Portfolio

 Comments

 Contact Info

CATEGORIES

         Home

         About me

         Portfolio

Как решил это я:
var main = function() {

    $('#menumobile').click(function() {

        $('.swipemenu').animate({

            left: '0px'

        }, 200);

        $('.menuoverlay').animate({ opacity: 0.7 }, 300);
        $('.menuoverlay').show();
        $('.swipemenu').css({"position" : "absolute"});
        $('.content').css({"position" : "fixed"});
        $('.footer').css({"display" : "none"});
        $('.container').css({"position" : "fixed"});
    });

    $('#close').click(function() {

        $('.swipemenu').animate({

            left: '-500'

        }, 200);

        $('.content').css({"position" : "inherit"});
        $('.footer').css({"display" : "block"});
        $('.container').css({"position" : "inherit"});
        $('.swipemenu').css({"position" : "fixed"});
        $('.menuoverlay').animate({ opacity: 0 }, 300);
        $('.menuoverlay').hide();

    });
};

$(document).ready(main);

$(document).ready(function(){
  $(".menu-list").on("click","a", function (event) {
  event.preventDefault();

  var id = $(this).attr('href'),

  top = $(id).offset().top;

        $('.swipemenu').animate({

            left: '-500'

        }, 200);

        $('.content').css({"position" : "inherit"});
        $('.footer').css({"display" : "block"});
        $('.container').css({"position" : "inherit"});
        $('.swipemenu').css({"position" : "fixed"});
        $('.menuoverlay').animate({ opacity: 0 }, 300);
        $('.menuoverlay').hide();

  $('body,html').animate({scrollTop: top}, 1500);
  });
});

A: Это маленький пример и не совпадает с вашей вёрсткой но принцип тот что нужен

$(document).ready(function(){
    $("button").click(function(){
        $(this).toggleClass("");
        $(".menu").toggleClass("open");
    });
    $(".menu").click(function(){
        $(this).removeClass("open");
    });
});
* {
  margin: 0;
  padding: 0;
  list-style: none;
  text-decoration: none;
}

html,
body {
  height: 100%;
}

main {
  width: 100%;
  background: #dfdfdf;
  position: relative;
}

.menu {
  background: linear-gradient(#ccc, #fff, #ccc);
  width: 20%;
  display: inline-block;
  height: 100%;
  padding: 10px;
  position: absolute;
  left: -22%;
  transition: .5s;
}

.menu:hover {
  left: 0;
}

.menu li {
  display: inline-block;
  padding: 10px 0;
  width: 100%;
  background-color: #bbb;
  margin: 1px 0;
}

.menu a {
  font-family: 'Keania One', cursive;
  padding-left: 14px;
}

.post a {
  font-family: 'Montserrat Subrayada', sans-serif;
  color: #fefefe;
}

a:hover {
  color: blue;
}

.content {
  margin: 20px auto;
  padding: 30px;
}

.post {
  padding: 30px 40px;
  background-color: #ccc;
  border-radius: 4px;
  margin: 10px 0;
}

.post-header {
  font-size: 30px;
}

button {
  padding: 10px 20px;
  border: none;
  outline: none;
  background: #777;
  color: #dfdfdf;
}

button.hidden {
  position: fixed;
  background: darkred;
}

.menu.open {
  left: 0;
  max-height: 600px;
  overflow: hidden;
  overflow-y: auto;
}
<link href="https://fonts.googleapis.com/css?family=Montserrat+Subrayada" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Keania+One" rel="stylesheet">

  <button>Кнопка</button>

      item 1

      item 2

      item 3

      item 4

      item 1

      item 2

      item 3

      item 4

      item 1

      item 2

      item 3

      item 4

      item 1

      item 2

      item 3

      item 4

        Post name #1

        Post name #2

        Post name #3

        Post name #4

        Post name #5

        Post name #6

        Post name #7

        Post name #8

        Post name #9

        Post name #10

A:

$(document).ready(function() {
  $(".button").click(function() {
    $(".leftmenu").toggleClass("open");
    $(".content").toggleClass("block");
  });
});
.content {
  top: 0;
  position: absolute;
  height: 100%;
  width: 100%;
}

.wrapper {
  min-height: 100%;
}

.leftmenu_wrapper {
  top: 0;
  position: absolute;
  height: 100%;
  width: 100%;
  z-index: 100;
  overflow-y: scroll;
}

.content.block {
  overflow: hidden;
}

.leftmenu {
  top: 0;
  display: none;
  background: #000;
  color: #fff;
  position: absolute;
  width: 30%;
  z-index: 100;
}

.leftmenu.open {
  display: block;
}

.leftmenu.open~.button {
  margin-left: 30%;
}

.button {
  background: #000;
  position: relative;
  z-index: 500;
  display: inline-block;
  color: #fff;
  padding: 10px;
}

.clear {
  clear: both;
  font-size: 0px;
  height: 0px;
}

@media (max-width: 500px) {
  .leftmenu {
    display: block;
  }
 .button {
  margin-left: 30%;
 }
  .content {
    overflow: hidden;
  }
}

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum error, doloremque repellat et unde beatae maxime, quae nesciunt natus repudiandae suscipit reprehenderit laboriosam amet quisquam sapiente, harum ullam veritatis quaerat excepturi perferendis
    voluptates! Inventore cupiditate, reprehenderit provident praesentium voluptates illum quis nobis quos aliquam eum molestiae, reiciendis enim nostrum iusto minima sed accusamus qui nam suscipit ipsam omnis. Accusamus sapiente autem quidem voluptatum
    cupiditate eos vero voluptates ab natus beatae architecto ea nobis voluptatibus omnis sunt ullam ut alias, voluptas ratione rem asperiores eum. Eius voluptas officia incidunt itaque, repellendus quasi animi illo mollitia in labore, rerum? Reiciendis
    illum voluptatem quo, atque dignissimos. Nostrum rem dicta esse, nulla iusto sunt omnis reiciendis qui, quo repellat suscipit odio, ipsum laboriosam ut ipsa incidunt veritatis quasi nobis tenetur sed excepturi. Architecto quae repellat veniam obcaecati
    est inventore libero nisi ex, illum vitae, ratione earum quod perspiciatis enim. Omnis, aliquid, accusantium. Inventore voluptate obcaecati vitae iste, rerum nihil corrupti recusandae sunt rem voluptas? Minus, ipsum. Consequuntur fugiat sit alias
    consectetur sed laborum, minima, tempore quibusdam cupiditate labore qui voluptatum maxime itaque et autem inventore? At ut quidem mollitia ipsam modi praesentium quae cumque deleniti nam quod quisquam, magnam rem asperiores delectus labore tempore,
    beatae dolorem vero impedit eaque officia aliquam enim harum, distinctio! Sequi quas in veritatis praesentium ad, cupiditate nobis eaque magni architecto assumenda, atque quisquam placeat tenetur aliquid asperiores minima, nihil voluptatum et provident
    dolores incidunt. Consectetur hic atque animi iure unde id facilis et doloribus suscipit inventore illo at in repudiandae dignissimos, dolorem numquam impedit temporibus, sequi iste labore dolores? Suscipit ut fugiat quaerat dolor tempora voluptas
    facere quam maiores. Voluptatem cum porro perspiciatis, obcaecati ratione repellat quasi voluptates. Quidem repudiandae, cum, necessitatibus autem laborum pariatur illum, omnis tempore doloribus nesciunt consequuntur temporibus nisi nostrum, voluptate
    eveniet deserunt repellendus? Ullam dicta ea tempore in nostrum natus, ipsam facilis, quidem cupiditate veritatis dolorum, sequi commodi illo rer

        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem expedita nisi, vero laborum nobis deleniti itaque ipsum eum non numquam enim est facere similique iure nostrum, dolorum totam dignissimos minima a. Officia delectus incidunt ea molestiae itaque
        molestias pariatur dolor quam eligendi quis rem, nihil magnam a, fugit deleniti id. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem expedita nisi, vero laborum nobis deleniti itaque ipsum eum non numquam enim est facere similique
        iure nostrum, dolorum totam dignissimos minima a. Officia delectus incidunt ea molestiae itaque molestias pariatur dolor quam eligendi quis rem, nihil magnam a, fugit deleniti id. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem expedita
        nisi, vero laborum nobis deleniti itaque ipsum eum non numquam enim est facere similique iure nostrum, dolorum totam dignissimos minima a. Officia delectus incidunt ea molestiae itaque molestias pariatur dolor quam eligendi quis rem, nihil magnam
        a, fugit deleniti id.
        iure nostrum, dolorum totam dignissimos minima a. Officia delectus incidunt ea molestiae itaque molestias pariatur dolor quam eligendi quis rem, nihil magnam a, fugit deleniti id. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem expedita
        nisi, vero laborum nobis deleniti itaque ipsum eum non numquam enim est facere similique iure nostrum, dolorum totam dignissimos minima a. Officia delectus incidunt ea molestiae itaque molestias pariatur dolor quam eligendi quis rem, nihil magnam
        a, fugit deleniti id.

Open leftmenu

Как я понял вам нужно подобное решение?
Это полностью реализуется на чистом css, media запросом. Js тут не нужен.


text:
Q: changed directory permissions of  So, I was changing some file permissions using gFTP, and somehow I managed to set the permissions of .. (idk how, last time I use gFTP)
The problem is I was working in the highest directory I could access. The log looks something like this:

SITE CHMOD 0 ..
200 SITE CHMOD command successful

I now can't log into my site using gFTP or using plain ftp. Does anyone have any suggestions of how to fix the issue, or do I have to talk to the guy who hosts the site? Given that it is hosted for free, I would like to avoid bugging him.

A: If you have SSH access you should be able to log in and change permissions, since you are (usually) the owner of your home directory. If not, you'll have to bug the administrator.


text:
Q: Showing that $f(x_n)n \rightarrow 1$ when $f$ is not continuous Define $$x_n = \inf \{ x \ | \ f(x) \le \frac{1}{n}\}$$
where $f(x) = \frac{g(x)}{x}$ and $g(x)$ is a function which is not continuous. It may be relevant to note that $g(x)$ is a slowly-growing function (of the same order as $\log x$), so for large $x$, $f(x)$ practically behaves like $1/x$. But I don't know how to formalize that.
If $g(x)$ was continuous (for example equal to $\log x$), then it is easy to see that $f(x_n)n = 1$.
But in the case where $g$ is unknown and possibly not continuous, how do we decude that $$f(x_n)n \rightarrow 1$$ as $n$ goes to $\infty$?
It "should" still be true using intuition, but the fact that $g$ is not continuous means I can't really argue that $x_n$ will exactly make $f(x_n)$ equal $1/n$ with strict equality ...
EDIT:
Further info.

*

*$f$ is always decreasing (but not necessarily strictly).

*The domain of $x$ is imagined to be "large $x$", i.e. some interval $[x_0, \infty)$ on which $f$ is decreasing.


text:
Q: can we make a convolution network that use more than one image to make a prediction I cropped the following image from a tutorial.

this diagram shows a rough structure of a standard neural network. takes one image as input and make a prediction.
what I am thinking about is some kind of parallel structure. think about something like the following image.

not exactly as in the above image. But you can see I am trying to use two images to make one prediction. this image is for you to get an idea about what I am trying to ask.
is it possible to use more than one (two, three ..) images like this or any other way in order to make one prediction. now, this is not to be used in actual photo classification. But I think such a technique can be used in a file like audio classification where a graphical representation of data is used with image classification techniques.
any advice, guidance or opinion on this?
if we consider implementing exactly what is in the diagram, if I use a high-level API like Keras (Keras.model.sequential) all we can do is keep adding a layer one after the other.
so what kind of technology can I use to implement the parallel structure

A: Yes, you can use more than one image as input. See for example the Siamese Neural Network which takes as input 2 images and passes them through a shared network architecture.
If instead you want to have an arbitrary and variable number of images as input you can use an architecture based on Recurrent Neural Networks like Convolutional LSTM, which essentially applies a CNN to every image of the input sequence using an LSTM recurrent network.


text:
Q: Set Validators on Nested FormControl objects with Angular 8 How do I set validators on a nested FormControl with child objects?
This product below, actually has members: productId, productName, productDescription (coming from a dropdown select)
I want to set validators productId > 4 .
this.editSharedForm = this.formBuilder.group({
   'customerName':[null,[Validators.maxLength(50)],
   'customerPhone': [null, [Validators.maxLength(10)]],
   'product': new FormControl('')

Following is not working:
this.editSharedForm.get('product').get('productId').setValidators(Validators.min(5))

this.editSharedForm.get('product').value['productId'].setValidators(Validators.min(5))

Errors being Undefined error for first one, not a function for second command.

A: You can simply use
this.editSharedForm.get('product').setValidators(yourValidators)

and then call
this.editSharedForm.get('product').updateValueAndValidity()

in order to run the new validators.


text:
Q: Difference-in-Differences with Repeated Cross-Sections I have a sample of individuals participating in two survey waves. The sample represents a repeated cross-section because there are different individuals in each survey wave.
Between the waves, there is a shock (i.e., the treatment in a difference-in-differences setup) at the ZIP code level, i.e., some areas (and all individuals living there) receive treatment, while others do not. The problem is that only a small share of areas is observed before and after the treatment (and with different individuals, if so). Therefore, the question is whether I can include people from ZIP code areas where these areas only appear either before or after the treatment. In my understanding, this should be OK as long as the survey participants have been selected randomly. Is this OK?


text:
Q: Spring MessageSource not using parameters I have the following code:
    System.out.println(ex.errorArgument[0]);
    String defaultErrorMessage = messages.getMessage(ex.errorMessage, ex.errorArgument, Locale.ENGLISH);
    String localErrorMessage = messages.getMessage(ex.errorMessage, ex.errorArgument, defaultErrorMessage, locale);
    Logger.error(this.getClass(), "handleApiException()", ex.status+": "+ex.errorCode+": "+defaultErrorMessage+": "
            +(ex.chainedException==null?"No further exception.":ex.chainedException.getMessage()));

With the following message
api.censored=Name cannot have the censored word '{0}' in it. Please choose another.

However, it is not replacing the parameters!
2019-05-20 23:02:46.484 ERROR 10884 --- [nio-8080-exec-1] c.example.apis.RestExceptionHandler   : handleApiException(): 406: CENSORED_WORD: Name cannot have the censored word {0} in it. Please choose another.: No further exception.

The JavaDocs says

String org.springframework.context.MessageSource.getMessage(String code, Object[] args, String defaultMessage, Locale locale)
Try to resolve the message. Return default message if no message was found.

*

*Parameters:

*

*code the code to lookup up, such as 'calculator.noRateSet'. Users of this class are encouraged to base message names on the relevant fully qualified class name, thus avoiding conflict and ensuring maximum clarity.

*args an array of arguments that will be filled in for params within the message (params look like "{0}", "{1,date}", "{2,time}" within a message), or null if none.

*defaultMessage a default message to return if the lookup fails

*locale the locale in which to do the lookup

Spring 4.3.24


text:
Q: Wine is not working under 18.04 LTS Wine (Stable) and (Development) appear in Ubuntu 18.04 Archive, but will not launch?

A: You appear to have some bad items in your sources list.  If you are running Ubuntu, wine-stable shouldn't have a xenial version.  The baseline version of wine-stable in 18.04 is 3.0-1ubuntu1.
I suggest removing all ppas that have to do with wine and try installing it from the baseline repos.


text:
Q: JFrame and ActionListener I'm a bit of a newbie to java, and I'm having an issue with a game I'm making in Swing. I have a class, guiPulUp, which has buttons and a text field. One of the buttons is "Magic". I'm trying to make it so if you click  the Magic button then a JFrame, another one called guiPullUpMagic, appears with preset "Spell" buttons.
Is that even possible? Or is there also a way to use .setVisible to make the spell GUI visible when clicked?
Please help! I can't find any topic related to this on the internet. Thanks! (If there's any other errors, let me know)
Also, I am getting VERY confused with how to get variables made in one class to work in another, such as getting my JButton "buttonMAGIC" to work in my guiPullUpMagic class.
For reference here's my code (It's pretty big!):

import javax.swing.*;

import java.lang.Math.*;

import java.awt.event.*;

/**
 * main GUI class
 */

public class guiPullUp extends JFrame
{

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

    //declaring buttons for main GUI

    private JButton buttonOK;
    private JButton buttonUP;
    private JButton buttonDOWN;
    private JButton buttonRIGHT;
    private JButton buttonLEFT;
    private JButton buttonMAGIC;
    private JButton buttonRUN;
    private JTextField userINPUT;
    private JLabel healthDisplay;

    public guiPullUp()
    {
        this.setSize(600,500);
        this.setTitle("Xenix V_1");
        this.setDefaultCloseOperation(
            JFrame.EXIT_ON_CLOSE);

         //button names to appear on panel1*
         //*button coordinates needed

         JButton buttonOK = new JButton ("OK");
        JButton buttonUP = new JButton ("Up");
        JButton buttonDOWN = new JButton ("Down");
        JButton buttonRIGHT = new JButton ("Right");
        JButton buttonLEFT = new JButton ("Left");
        JButton buttonMAGIC = new JButton ("Magic");
        JButton buttonRUN = new JButton ("RUN");
        JTextField userINPUT = new JTextField(30);
        JLabel healthDisplay = new JLabel("Health:  ");
        JPanel panel1 = new JPanel ();

        ButtonListener bl = new ButtonListener();

         buttonOK.addActionListener(bl);
         buttonUP.addActionListener(bl);
         buttonDOWN.addActionListener(bl);
         buttonRIGHT.addActionListener(bl);
         buttonLEFT.addActionListener(bl);
         buttonMAGIC.addActionListener(bl);
         buttonRUN.addActionListener(bl);

         panel1.add(buttonOK);
         panel1.add(buttonDOWN);
         panel1.add(buttonRIGHT);
         panel1.add(buttonLEFT);
         panel1.add(buttonMAGIC);
         panel1.add(buttonRUN);

         panel1.add(healthDisplay);

         panel1.add(userINPUT);

         this.add(panel1);

         this.setVisible(true);
        }

     //declaring variables "counters" for magic count,
    //health count, etc.

    int healthMAX = 100;
    int healthMINIMUM = 0;
    int magicMAX = 100;
    int magicMINIMUM = 0;
    int walletSizeMAX = 9999;
    int walletSizeMINIMUM = 0;

    /**
     * class used to create events
     * based on button sources
     */

    public class ButtonListener implements
        ActionListener
    {

        public void actionPerformed (ActionEvent e)
        {
            //Haven't made these codes yet but some WILL need to bring up a GUI
                }

        }
    }
}

The guiPullUpMagic class:

import javax.swing.*;

import java.awt.event.*;

import java.lang.Math.*;

/**
* class used to pull up the "spells" GUI
*/

public class guiPullUpMagic extends JFrame
{
    public void magic(String[] args)
    {
        new guiPullUpMagic();
    }

    private JButton buttonFIREMAGIC;
    private JButton buttonICEMAGIC;
    private JButton buttonHEALMAGIC;
    private JButton buttonSHOCKMAGIC;

    public guiPullUpMagic()
    {
        this.setSize(400,400);
        this.setTitle("Spells");
        this.setDefaultCloseOperation(
            JFrame.EXIT_ON_CLOSE);

        //button names to appear on panel2*
        //*button coordinates needed

        JButton buttonFIREMAGIC = new JButton ("FireBall");
        JButton buttonICEMAGIC = new JButton ("Ice Flurry");
        JButton buttonSHOCKMAGIC = new JButton ("Spark");
        JButton buttonHEALMAGIC = new JButton ("Heal Minor Wounds");
        JPanel panel2 = new JPanel();

        ButtonListener bl = new ButtonListener();

        buttonFIREMAGIC.addActionListener(bl);
        buttonICEMAGIC.addActionListener(bl);
        buttonSHOCKMAGIC.addActionListener(bl);
        buttonHEALMAGIC.addActionListener(bl);

        panel2.add(buttonFIREMAGIC);
        panel2.add(buttonICEMAGIC);
        panel2.add(buttonSHOCKMAGIC);
        panel2.add(buttonHEALMAGIC);

        this.add(panel2);

        this.setVisible(false);
    }

    public class ButtonListener implements
        ActionListener
    {

        public void actionPerformed (ActionEvent e)
        {
            if (e.getSource() == buttonMAGIC); //THIS is where I'll need
                                                           //the buttonMAGIC variable
                                                           //from guiPullUp
            {
                    //code to bring up the guiPullUpMagic GUI
            }
        }
    }
}

A: If you want to pass a field of a JFrame to another JFrame you can send a ComponentEvent to that jframe with that control
For example you can define a ComponentEvent(for example ShowPopUpEvent) for showing JFrame A and A would listen for that.
Whenever you would like to show a and pass that JButton to a you can dispatch that event.

A: Note the changes

*

*ActionListener is implemented in class GuiPullUp

*Class GuiPullUpMagic is JDialog

*Check method actionPerformed
Class GuiPullUp:
public class GuiPullUp extends JFrame implements ActionListener {

//declaring buttons for main GUI
private JButton buttonOK;
private JButton buttonUP;
private JButton buttonDOWN;
private JButton buttonRIGHT;
private JButton buttonLEFT;
private JButton buttonMAGIC;
private JButton buttonRUN;
private JTextField userINPUT;
private JLabel healthDisplay;

public GuiPullUp() {
    this.setSize(600, 500);
    this.setTitle("Xenix V_1");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    buttonOK = new JButton("OK");
    buttonUP = new JButton("Up");
    buttonDOWN = new JButton("Down");
    buttonRIGHT = new JButton("Right");
    buttonLEFT = new JButton("Left");
    buttonMAGIC = new JButton("Magic");
    buttonRUN = new JButton("RUN");
    userINPUT = new JTextField(30);
    healthDisplay = new JLabel("Health:  ");
    JPanel panel1 = new JPanel();

    buttonOK.addActionListener(this);
    buttonUP.addActionListener(this);
    buttonDOWN.addActionListener(this);
    buttonRIGHT.addActionListener(this);
    buttonLEFT.addActionListener(this);
    buttonMAGIC.addActionListener(this);
    buttonRUN.addActionListener(this);

    panel1.add(buttonOK);
    panel1.add(buttonDOWN);
    panel1.add(buttonRIGHT);
    panel1.add(buttonLEFT);
    panel1.add(buttonMAGIC);
    panel1.add(buttonRUN);

    panel1.add(healthDisplay);

    panel1.add(userINPUT);

    this.add(panel1);

}
//declaring variables "counters" for magic count,
//health count, etc.
int healthMAX = 100;
int healthMINIMUM = 0;
int magicMAX = 100;
int magicMINIMUM = 0;
int walletSizeMAX = 9999;
int walletSizeMINIMUM = 0;

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand().equals(buttonMAGIC.getActionCommand())) {
        new GuiPullUpMagic(this).setVisible(true);
    }
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            GuiPullUp guiPullUp = new GuiPullUp();
            guiPullUp.setVisible(true);
        }
    });
}
}

Class GuiPullUpMagic
public class GuiPullUpMagic extends JDialog implements ActionListener {

    private JButton buttonFIREMAGIC;
    private JButton buttonICEMAGIC;
    private JButton buttonHEALMAGIC;
    private JButton buttonSHOCKMAGIC;

    public GuiPullUpMagic(JFrame parent) {
        super(parent);
        this.setSize(400, 400);
        this.setTitle("Spells");

        buttonFIREMAGIC = new JButton("FireBall");
        buttonICEMAGIC = new JButton("Ice Flurry");
        buttonSHOCKMAGIC = new JButton("Spark");
        buttonHEALMAGIC = new JButton("Heal Minor Wounds");
        JPanel panel2 = new JPanel();

        buttonFIREMAGIC.addActionListener(this);
        buttonICEMAGIC.addActionListener(this);
        buttonSHOCKMAGIC.addActionListener(this);
        buttonHEALMAGIC.addActionListener(this);

        panel2.add(buttonFIREMAGIC);
        panel2.add(buttonICEMAGIC);
        panel2.add(buttonSHOCKMAGIC);
        panel2.add(buttonHEALMAGIC);

        this.add(panel2);
    }

    @Override
    public void actionPerformed(ActionEvent e) {

    }
}


text:
Q: Javascript: document.body.appendchild has a null value I am loading a .js file I wrote. Within that .js file I am creating a Iframe like this
var frmSource = "http://MYLINK.com/mypage.php?" + encodeURI(URLBuilder);
ifrm = document.createElement("IFRAME");
ifrm.setAttribute("src", frmSource);a
ifrm.style.width = 0+"px";
ifrm.style.height = 0+"px";
ifrm.setAttribute("frameBorder", "0");
document.body.appendChild(ifrm);

URLBuilder contains the GET variables to the next page
The issue occurs at document.body.appendChild(ifrm);
and my error is
javascript typeerror: null is not an object (evaluating 'document.body.appendchild')
I suspect the issue is it is trying to append the iframe to the body but the body has not properly loaded. I am currently only getting this issue in safari.

A: If your script is in the head, then the body is not defined (null). Put the script in the footer.

A: I have done something like this to configure my IFrame creation and it is working fine
 var urlWithParam = url + encodeURI(URLBuilder)
        var iframe = document.createElement('iframe');
        iframe.src = urlWithParam;
        iframe.id = "iframe_" + done;
        iframe.style.position = "relative";
        iframe.style.height = "100%";
        iframe.style.width = "100%";
        iframe.style.top = "0";
        iframe.style.left = "0";
        iframe.style.right = "0";
        iframe.style.bottom = "0";
        iframe.style.frameBorder = "0";
        iframe.style.borderStyle = "none";
        iframe.style.display = "none;";

        //if you want to do something after the Iframe load
        iframe.onload = function(event) {

        };

A: Moved the script below the body. And it worked like a charm.


text:
Q: Azure Devops REST API documentation for policies is missing? We're building a web based self service for our employees, to speed up/improve everyones DevOps experience. The self service utilizes the Azure Devops REST API and most of it works fine but as I'm about to implement the branch policies I get stuck for lack of documentation (or my inability to find it).
I think I have found what documentation is available for creating policy configurations, like this article. There's just a general mention of "settings" needs to be a JObject and then seven examples for various scenarios but if there are any reference articles for the 14 supported policy types then I have missed it.
Am I just blind or did Microsoft just not bother with documenting how to form the JObjects for the different kinds of configurations?

A:
Azure Devops REST API documentation for policies is missing?

For me, I am more inclined that the document does not explicitly point out the content of JObject.
When we check that REST API document Configurations - Create, we could get following info:

Indeed, it only states that its type is a JSON object without specific content or examples.
To get the content of this JSON object, I use the REST API Configurations - Get to get the content of the Response body, I could get following response body:
        "settings": {
            "minimumApproverCount": 2,
            "creatorVoteCounts": false,
            "allowDownvotes": false,
            "resetOnSourcePush": false,
            "requireVoteOnLastIteration": false,
            "resetRejectionsOnSourcePush": false,
            "blockLastPusherVote": false,
            "scope": [
                {
                    "refName": "refs/heads/Dev",
                    "matchKind": "Exact",
                    "repositoryId": "dcb40ef6-dae0-4e3c-b581-2f71c76e09a6"
                }
            ]
        },

So, we could to know the content is indeed a JSON object and it will be different due to the different policies we set.
Now, we move back to the samples in that document, we could find that there are many such settings, like:
Approval count policy:
{
  "isEnabled": true,
  "isBlocking": false,
  "type": {
    "id": "fa4e907d-c16b-4a4c-9dfa-4906e5d171dd"
  },
  "settings": {
    "minimumApproverCount": 1,
    "creatorVoteCounts": false,
    "scope": [
      {
        "repositoryId": null,
        "refName": "refs/heads/master",
        "matchKind": "exact"
      }
    ]
  }
}

If we want to set any other supported policy types, we can manually set it on the UI, and then get the corresponding response body about it.


text:
Q: How to get dropdown in action column in magento admin grid I want to get dropdown of edit & delete in action column of admin grid in magento2 as like mention in the image. How it is possible?
$this->addColumn(
    'delete',
    [
        'header' => __('Action'),
        'type' => 'action',
        'getter' => 'getId',
        'actions' => [
            [
                'caption' => __('Delete'),
                'url' => [
                    'base' => 'abc/*/delete'
                ],
                'field' => 'abc_id'
            ]
        ],
        'filter' => false,
        'sortable' => false,
        'index' => 'stores',
        'header_css_class' => 'col-action',
        'column_css_class' => 'col-action'
    ]
);

A: Here i give your answer please follow bellow steps

your_grid.xml

 <actionsColumn name="actions" class="[vendor]\[module]\Ui\Component\Listing\Column\Actions">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="indexField" xsi:type="string">id</item>
        </item>
    </argument>
</actionsColumn>

app/code/[vendor]/[module]/Ui/Component/Listing/Column/Actions.php

<?php

namespace [vendor]\[module]\Ui\Component\Listing\Column;

use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;

class Actions extends Column
{

    const URL_PATH_EDIT = '[router]/[controller]/edit';
    const URL_PATH_DELETE = '[router]/[controller]/delete';
    const URL_PATH_DETAILS = '[router]/[controller]/details';

    protected $urlBuilder;

    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        UrlInterface $urlBuilder,
        array $components = [],
        array $data = []
    ) {
        $this->urlBuilder = $urlBuilder;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as & $item) {
                if (isset($item['primary_id'])) {
                    $item[$this->getData('name')] = [
                        'edit' => [
                            'href' => $this->urlBuilder->getUrl(
                                static::URL_PATH_EDIT,
                                [
                                    'id' => $item['primary_id']
                                ]
                            ),
                            'label' => __('Edit')
                        ],
                        'delete' => [
                            'href' => $this->urlBuilder->getUrl(
                                static::URL_PATH_DELETE,
                                [
                                    'id' => $item['primary_id']
                                ]
                            ),
                            'label' => __('Delete'),
                            'confirm' => [
                                'title' => __('Delete "${ $.$data.title }"'),
                                'message' => __('Are you sure you wan\'t to delete a "${ $.$data.title }" record?')
                            ]
                        ]
                    ];
                }
            }
        }

        return $dataSource;
    }
}

Below code for Magento 2.3.X

<?php

namespace [vendor]\[module]\Ui\Component\Listing\Column;

use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;

class Actions extends Column {

    /** Url path */
    const URL_PATH_EDIT = '[router]/[controller]/edit';
    const URL_PATH_DELETE = '[router]/[controller]/delete';
    const URL_PATH_VIEW = '[router]/[controller]/view';

    protected $actionUrlBuilder;
    protected $urlBuilder;

    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        UrlInterface $urlBuilder,
        array $components = [],
        array $data = []
    ) {
        $this->urlBuilder = $urlBuilder;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    public function prepareDataSource(array $dataSource) {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as & $item) {
                $name = $this->getData('name');
                if (isset($item['primary_id'])) {
                    $item[$name]['edit'] = [
                        'href' => $this->urlBuilder->getUrl(
                                self::URL_PATH_EDIT, [
                                    'primary_id' => $item['primary_id']
                                ]
                        ),
                        'label' => __('Edit')
                    ];
                    $item[$name]['delete'] = [
                        'href' => $this->urlBuilder->getUrl(
                                self::URL_PATH_DELETE, [
                                    'primary_id' => $item['primary_id']
                                ]
                        ),
                        'label' => __('Delete'),
                        'confirm' => [
                            'title' => __('Delete "${ $.$data.title }"'),
                            'message' => __('Are you sure you wan\'t to delete a "${ $.$data.title }" record?')
                        ]
                    ];
                    $item[$name]['preview'] = [
                        'href' => $this->urlBuilder->getUrl(
                                self::URL_PATH_VIEW, [
                                    'primary_id' => $item['primary_id']
                                ]
                        ),
                        'label' => __('View')
                    ];
                }
            }
        }

        return $dataSource;
    }

}


text:
Q: Call an object function from a text variable app = {
    echo: function(txt) {
       alert(txt)
    },
    start: function(func) {
        this.func('hello');
    }
}

app.start('echo');

I need to call whatever function passed as func. How to do that? the example doesn't work for me.

A: Use this[func] instead of this.func
   app={
          echo:function(txt){
          alert(txt)
          },
         start:function(func){
            this[func]('hello');
          }
        }

      app.start('echo');

A: I guess in it's simplest form you could do:
var app =
{
  echo: function(txt)
  {
    alert(txt);
  },

  start: function(func)
  {
    this[func]("hello");
  }
};

But you could get a little smarter with the arguments:
var app =
{
  echo: function(txt)
  {
    alert(txt);
  },

  start: function(func)
  {
    var method = this[func];
    var args = [];
    for (var i = 1; i < arguments.length; i++)
      args.push(arguments[i]);

    method.apply(this, args);
  }
};

That way you can call it as app.start("echo", "hello");

A: Try that way:
start: function(func) {
    this[func]('hello');
}

A: start:function(func){
this[func]('hello');
}


text:
Q: Remote Debugging in VS2010 - access denied I have VS2010 on my dev machine (Win7) and I run a virtual machine under XP SP3 (name PC), on which I installed the VS2010 remote debugger, as well as .Net Framework 4.
On both OS I have the same user name (User), with the same password, with admin privilege, who is allowed to debug programs (Local Policy/User Rights Assignment/Debug programs). The firewall is deactivated on both.
When I debug my program through VS2010 (specifying "Start external program" and "Use remote machine"), I get

Error while trying to run project: Unable to start debugging.
Access is denied. Can not connect to Microsoft Visual Studio Remote
  Debugging Monitor on the remote computer.

On the VM the Visual Studio Remote Debugging Monitor displays a line saying "PC\User connected".
If I try to attach a process using "Default" as transport and "User@PC" as qualifier, I get a similar error

Unable to connect to the Microsoft Visual Studio Remote Debugging
  Monitor named 'User@PC'. Access is denied. Can not connect to
  Microsoft Visual Studio Remote Debugging Monitor on the remote
  computer.

Again on the VM the Visual Studio Remote Debugging Monitor displays a line saying "PC\User connected".
If I try to attach a process using "Remote (Native only with no authentication)" as transport and "PC:4015" as qualifier (changing the "Authentication mode" to "No Authentication (native only)", then it works and I see all the available processes on the VM.
Any idea on why the access is denied even if the Visual Studio Remote Debugging Monitor seems to accept the connection? Also if I 1st use "Windows Authentication" and try to start the debugger, and then I try to change the "Authentication mode" to "No Authentication", I get

Your new options can not be applied. Cannot stop server because one or
  more users are currently connected.
View Msvsmon's help for more information.

A: I was eventually able to make it work by doing "Run as administrator" on VS.Net 2010 (I forgot that Windows 2008 and 7 are quite different when it comes to right management).


text:
Q: ASP.Net ObjectDataSource Data Binding I have two classes:
public class Contact{

     public string contact { get; set; }
     public string contact_type { get; set; }

 }

public class Person{

 public string first_name { get; set; }
 public string last_name { get; set; }
 Contact phone

}

In my asp.net application I need to see list of persons in a gridview.
I use ObjectDataSource to bind List. But only two columns: first_name and last_name are presents in the gridview. It is important to see contact of person.
In other words, how to bind subclass Contact to the same gridview.
What is the best way to do this? I don't like idea to use DataTable.
Thanks!

A: I think your best bet is to use template field and eval to access inner object fields:
<asp:TemplateField HeaderText="Contact">
    <ItemTemplate>
        <%# Eval("phone.contact") %>
    </ItemTemplate>
</asp:TemplateField>

If you are using auto generated columns feature, keep it, declared columns will be appended after generated ones.


text:
Q: Deleting on array item in Windows Phone C# app and never show it in next app launch I am developing a Windows Phone app with C#. It has 10000 elements in an array. My program sudo code is something like
Begin
Get a random element from array
Manipulate it
Delete it
End

And that array element should be permenetly deleted from the app, (ie, I should not get it on next app launch)
How to perform this task easily. Please give me some code so I can understand easily.

A: You have to store your data in an Isolated Storage or use
SQL Compact Fow Windows Phone

A: Pretty basic example of using storage folder with xml output/input.  You can modify it do what you wish. I use a more complicated version of it for my own windows phone app.
I'm assuming you having a hard time writing and reading the data back.  If you need help deleting a random element from the list, let me know.  I will edit this code for that as well.
private List<int> my_list = new List<int>();

public async Task GenericDataWrite()
{
    // Get the local folder.
    StorageFolder data_folder = Windows.Storage.ApplicationData.Current.LocalFolder;

    // Create a new file named data_file.xml
    StorageFile file = await data_folder.CreateFileAsync(@"data_file.xml", CreationCollisionOption.ReplaceExisting);

    // Write the data
    using (Stream s = await file.OpenStreamForWriteAsync())
    {
        try
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<int>));
            serializer.Serialize(s, my_list);
            s.Close();
        }
        catch(Exception ex)
        {
            string error_message = ex.Message;
        }
    }
}

public async Task GenericDataRead()
{
    // Get the local folder.
    StorageFolder data_folder = Windows.Storage.ApplicationData.Current.LocalFolder;

    if (data_folder != null)
    {
        StorageFile file = await data_folder.GetFileAsync(@"data_file.xml");

        // Get the file.
        System.IO.Stream file_stream = await file.OpenStreamForReadAsync();

        // Read the data.
        using (StreamReader streamReader = new StreamReader(file_stream))
        {

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<int>));
            my_list = (List<int>)serializer.Deserialize(streamReader);
            streamReader.Close();
        }
        file_stream.Close();
   }
}


text:
Q: How do I know actual SQL Server client side connection pool utilization? My C# code uses SqlConnection to connect to SQL Azure. Sometimes I will face the following:
System.InvalidOperationException
Timeout expired.  The timeout period elapsed prior to obtaining a connection
from the pool.  This may have occurred because all pooled connections were
in use and max pool size was reached.
 at System.Data.ProviderBase.DbConnectionFactory.GetConnection(
    DbConnection owningConnection)
 at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(
    DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
// my code calling SqlConnection.Open()

I'd like to find why I'm facing this exception. The exception is likely because I've exhausted the connection pool, but I'm not completely sure and if I were sure I'd like to know how I got there.
Is is possible for my code to obtain the maximum pool size and current pool utilization (number of used and unused connections)?

A: The Max number of connections for SQL Azure database is 180 connections. This is a hard limit.
http://msdn.microsoft.com/en-us/library/windowsazure/ff394114.aspx

-- monitor connections
SELECT
      e.connection_id,
      s.session_id,
      s.login_name,
      s.last_request_end_time,
      s.cpu_time
FROM
      sys.dm_exec_sessions s
      INNER JOIN sys.dm_exec_connections e
      ON s.session_id = e.session_id
GO

This query will allow to see the current connections. The link above also has some really useful querys for working out where connections are coming from.
I use this query as part of diagnostics setup and reporting which we run in cron job to make sure we are not heading towards an outage.
Max pool as already pointed out will help, but this depends on the number of compute in front of SQL Azure.
When you get this type of problem, you need to work out if you have a connection issue in terms of closing or that you need to start to look at more advanced solutions like sharding.
hths, James

A: You can checkout this link.
Although max pool size, if not specified, is 100.


text:
Q: First mover advantage stackelberg case. So in the Stackelberg problem, there is usually a first mover advantage for the leading firm (where the first firm to enter has a competitive advantage). Is there ever a case where the leader firm produces less than a follower firm?

A: Yes, if you are willing to consider Nash equilibria that are not subgame perfect Nash equilibria.
For example, suppose that the follower firm, let's call it $F_{2}$, can always choose a quantity $y_{2}$ in response to the first firm's quantity $y_{1}$ such that the price falls to zero.
In that case, the following strategy profile is a Nash equilibrium:

*

*For $F_{2}$, if $y_{1} = 0$, then choose $y_{2}$ equal to the monopolist's solution. If $y_{1} > 0$, then choose $y_{2}$ such that the price falls to zero.

*For $F_{1}$, choose $y_{1} = 0$.

$F_{1}$ has no incentive to deviate since all quantities that it might choose yield a profit of zero. $F_{2}$ has no incentive to deviate since along the path of play it gets the profit that it would get in a monopoly.
Of course, this profile being a Nash equilibrium hinges on the fact that $F_{2}$ is threatening to let the price drop to zero if $F_{1}$ chooses a non-zero quantity, and it is therefore not a subgame perfect NE.

A related question has also been asked in this post: First mover advantage in a Stackelberg game, but that example consider price instead of quantity competition.


text:
Q: In Mysql Workbench, where is Synchronize Model with Database As displayed in Mysql Database Synchronization documentation.
I cannot find this particular Synchronize Model with Database window / wizard under Database ->
I have Mysql Workbench 6.0.9.11421 build 1170 Community Edition

A: You must have a model open that you want to synchronize. Without an open model neither of the database actions (like forward engineering or synch) are possible.
Update:
Oh, I missed the exact menu item title. I was implicitely reading it as the existing ones. Well, sometimes items are renamed, so what you have in mind is now simply Database -> Synchronize Model...


text:
Q: Git ignore dir but unignore files in dir Yes, this is a duplicate question. But the answers thus far are not working for me. I'm running git v 2.6.4 on osX.
Here's my .gitignore:
/src/artwork/dist
/dist/*
!/dist/dandelion.yml

For line 2, I've also tried /dist/**, but running git status still does not show /dist/dandelion.yml.
Note that /dist is also a git repo, and I'd like to avoid using git add -f if I have to. To me forcing means you're doing something wrong.

A: Why not adding .gitignore to each folder you want to include the file. Since you have multiple dist folders you should place .gitignore with a specific rules per folder.
If i understood you correctly this is your folder structure:
|
|-dist
.
.
|-src
   |- artwork
         |- dist

What you have done so far:
# ignore the dist folder under src/artwork
/src/artwork/dist

# ignore dist folder under the root folder
/dist/*

# DO NOT ignore the dandelion.yml under the root/dist folder
!/dist/dandelion.yml

Note that /dist is also a git repo,

Why not adding it as submodule? This will save you the need to add the desired files to the .gitignore & its make much more sense if its an inner repo.

submodule


text:
Q: How to get the Server object from SpringApplication.run After looking at the logs, I see that when I run my application, it starts a TomCat WebServer
SpringApplication.run(SampleApplication.class, args);

Logs:
main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path

Currently, I have metrics being exposed to a /metrics endpoint and different port. This is done by creating a new Server like this:

SpringApplication.run(SampleApplication.class, args);
try {
    Server server = new Server(8080);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");

    server.start();
    server.join();

Logs:
STARTED @2880ms ManagedSelector@2f953efd{STARTED} id=1 keys=0 selected=0 updates=0

Selector sun.nio.ch.WindowsSelectorImpl@71a81a3e waiting with 0 keys
STARTED @2880ms SelectorManager@ServerConnector@550ee7e5{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}

ServerConnector@550ee7e5{HTTP/1.1, (http/1.1)}{0.0.0.0:8080} added {acceptor-0@13526e59,POJO}

Started ServerConnector@550ee7e5{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}

run acceptor-0@13526e59 in QueuedThreadPool[qtp1437654187]@55b0dcab{STARTED,8<=8<=200,i=5,r=-1,q=0}
[ReservedThreadExecutor@74e28667{reserved=0/4,pending=0}]
10:44:35.454 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle - STARTED @2882ms ServerConnector@550ee7e5{HTTP/1.1, (http/1.1)}{0.0.0.0:8080}
10:44:35.455 [main] INFO org.eclipse.jetty.server.Server - Started Server@3e96bacf{STARTING}[11.0.9,sto=0] @2887ms
10:44:35.455 [main] DEBUG org.eclipse.jetty.util.component.AbstractLifeCycle - STARTED @2887ms Server@3e96bacf{STARTED}[11.0.9,sto=0]

The problem is, I want to access the initial TomCat Webserver and add the ServletHolder to it (therefore exposing metrics endpoint but by linking it to tomcat webserver).
I guess my question is, can it be done this way and is it a good practice?
I've tried creating a @GetMapping("/metrics") endpoint within my SampleApplication, but I couldn't add the MetricsServlet that way


text:
Q: What is the workflow to get live data updates from NodeJS/MongoDB API? I need to fetch live data in Android App from a NodeJS/MongoDB API. For exemple, I have a list of tasks on the Android screen (fetched from the API). Then one of this documents (tasks) have changed in the MongoDB, the Android screen needs to update the data on the screen once this data have been changed on the server.
Can anyone help with some workflow? I am not looking for code. Ideias (Arquitecture/Libs) only.
Thanks in advance!

A: You can do this in two way.

*

*Use silent push notification.

*

*When data change in server then server send push notification
to app.

*App receive notification Then app get call API to update Data.

*Your app sends a request(s) to server periodically (After some
interval of time)
Reference link for same: link1, link2


text:
Q: How to diagnose that a user is online or offline in asp.net How can I diagnose someone( a user) is offline or online in asp.net.
For example in web application in asp.net when two people are chatting together if one of them is offline system can diagnose it and be able to show that user is offline.
Thank you

A: Have a flag column in the user table.. set it as '1' whenever a user logs in, and set it as zero whenever he logs out. So u can track whether the user is in offline or online..


text:
Q: Do HTML5 tags has special properties and behaviors? From what I've read, HTML5 new tags like section header article give meaning and readability to a web page instead using too many meaningless divs.
However, my question is: Do they have any special behavior or limitations in browsers or CSS properties?
This question came to me when I knew that <img> tags can't have pseudo elements :before, :after
So what other tags have some differences?

A: They are called semantic elements.
They don't typically behave differently while being rendered by the browser. Usually, they're used by search engines or other applications which parse the data on a website.

A: In a way
All tags in HTML do something that do other tags do.
However, while some tags (like <img>, as you have found) restrict what you can do, and others provide functionality (such as <button> or <video>), some offer more of a semantic role.
When being rendered on the page, these elements may not appear any different to other elements (for some, such as <blockquote>, browsers may provide default styles, however these should not be relied upon as they will be different / non-existent on other browsers or Operating Systems), they still provide functionality.
How?

*

*Screenreaders will use semantic elements to change their tone of voice, volume, or announce a new section, etc, depending on semantic tags;

*Services such as Google will scan pages and find content based around semantic tags (for example, they could be used when creating featured snippets)

There are many other use cases. It is mainly so that computers (and other programmers looking at your code) can understand immediately what each element can contain. We can look at a website and see an item's styles to figure out it's a navbar, but a computer's job is made easier if it is a <nav> rather than <div class="second-navi-bar">, etc.
In Summary...
Semantic elements provide structure for your site's code, rather than styles for it's users. For those semantic elements that do provide styles (such as <code> or <blockquote>), these styles will change depending on your browser - you should always style semantic elements yourself.


text:
Q: Value of Riemann zeta function at $-1$ This claim is false $\sum_{n=1}^{\infty}n=\sum_{n=1}^{\infty}n^{-(-1)}= \zeta(-1)=-1/12$.
The error is that we should
$\sum_{n=1}^{\infty}n=\sum_{n=1}^{\infty}(1/n ^1)^{-1}=(0)^{-1}$.
Am I correct? It's difficult to say that an infinite sum like that don't diverge and that sum of positive numbers can give negative number.

A: Use the functional equation:
$$\zeta(s)=2^s\pi^{-1+s}\Gamma(1-s)\sin\frac{\pi s}2\zeta(1-s)\;,\;\;s\neq1\implies$$
$$\zeta(-1)=\frac1{2\pi^2}\cdot1\cdot(-1)\zeta(2)=-\frac1{12}$$

A: Ralph Mellish said :

$\zeta(s)=\sum_{n=1}^{\infty}n^{-s}$  is only true when Re(s)>1. To evaluate at s=−1 you would need to use the functional equation. Point being: the error you're making is with your second equality: ∑∞n=1n−(−1)≠ζ(−1).
  Also, no: ∑∞n=1(1/n1)−1≠(0)−1. It seems as though you're thinking that ∑(stuff)−1=(∑stuff)−1, which is not true, and you seem to be be thinking that ∑∞n=11/n=0, which is not true (perhaps you're not thinking these things, but it is the only way I can interpret what you wrote above "i'm i correct?"). –

but he doesnt know that this trick is often used in string theory which is the final theory of everything
(this was posted as an answer in the place of a comment because have small inductive reputation)


text:
Q: Multiple apps with a shared db, what should I use to make it? I am pretty new to programming and have so far only learnt HTML, CSS and a little bit of javascript and Jquery.  What I would like to do is make a website which has a variety of apps (both web and mobile).  All of these apps would need to share a DB with the website, not only for login but also various forms of data each app deals with.
A friend suggested to me that I should be using AngularJS with Firebase and just make one big app with all the apps and website included in that, but I would rather a more flexible option so the app doesn't become huge.  So I would rather have a website which links to each app but also has access to the data.
So I have a few questions regarding this:
1 - What languages would I best to use to make this?
2 - If I went with angular and firebase for each app would I be able to use a language like php or rails to also tap into that db?
3 - What would be the easiest way to achieve this?
Thanks,
Marty

A: Yes , I'm making a big app like you and I've searched a lot and the easiest way is to use angular and php
although u can do better than this.
For example for your backend , you can use NODE.js , but its a matter of your knowledge and timing and how much energy you want to spare and consume.(But if you use php the right way , its very lightwaight/simple/fully supported/well known/free)
Angular is very wasy to learn and fast to use , and also PHP , because both od them have been tested and fully supported with lots of communities(thats very important)
for learning Angular Go to egghead.com , you can find lots of interesting angular video learning for free , And also you can simply search the youtube


text:
Q: JavaScript/jQuery - scroll up button I'm new to web development and came across a lot of tutorials on jQuery but there wasn't a lot on pure JS. I'm trying to convert this piece of code I found online which scrolls the page up when user clicks a button in the bottom right into pure JavaScript but I'm having some trouble.
function main() {
    $('.back-to-top').hide();
    $(window).scroll(function(){
        if($(window).scrollTop()>400){
            $('.back-to-top').fadeIn('fast');
        }else{
            $('.back-to-top').fadeOut('fast');
        }
    })

    $('.back-to-top').click(function(){
        $('body').animate({
            scrollTop: 0
        }, 1000)

        return false;
    })
}

This is what I have so far but it doesn't work:
var scrollUp = document.getElementsByClassName('back-to-top');

window.onscroll = function(){
    if(window.pageYOffset >= 400){
        scrollUp.style.display = 'block';
    }else{
        scrollUp.style.display = 'none';
    }
}

scrollUp.onclick = function(){
    window.scrollTo(0,0);
}

HTML

Scroll Up

This is for web development assignment, can I have some advice?

A: The problem is that document.getElementsByClassName('back-to-top') returns  an array-like object. Check documentation here: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
Solution:
    var scrollUp = document.getElementsByClassName('back-to-top')[0];

    window.onscroll = function(){
      if(window.pageYOffset >= 400){
        scrollUp.style.display = 'block';
      }else{
        scrollUp.style.display = 'none';
      }
    }

    scrollUp.onclick = function(){
      window.scrollTo(0,0);
    }

See working example here:
   https://jsfiddle.net/9m7doq1m/
To avoid this issue, you can use the id selector (getElementById) instead of the class selector.

A:

var scrollUp = document.getElementsByClassName('back-to-top');
scrollUp.onclick = function(){
    window.scrollTo(0,0);
}
#content {
  height: 1000px;
}

Scroll Up


text:
Q: Getting the pixel value of BMP file i got a question for reading an bmp image. How can i get the pixel value(R, G, B values) in an bmp image?
Can anyone help me using the C programming language?

A: The easy way would be to find a good image manipulation library for your chosen platform and use that.

*

*Linux ImLib / GDK-Pixbuf (Gnome/GTK) / QT Image (KDE/Qt) should be able to do what you need.

*Windows I'm not familiar with the appropriate system library, but an MSDN Search for "Bitmap" is probably a good place to start.

*Mac OSX Cocoa has some image manipulation capabilities, see this article.

The hard way would be to open the file and actually interpret the binary data within. To do that you'll need the BMP File Specification. I'd recommend trying the easy way first.

A: You need to study the BMP file format. It is easier to read uncompressed 24-bit BMP files. They just contain a header at the beginning and RGB values of each pixel.
To start with this, check the example of 2x2 bitmap image at http://en.wikipedia.org/wiki/BMP_file_format. Follow the below steps.

*

*Create the 2x2 BMP image shown on Wikipedia.

*Open the file in binary mode using your C program.

*Seek to byte position 54.

*Read 3 bytes.

The bytes would be 0, 0 and 255 respectively. (Not sure whether the order is RGB. I had done this long back and I think the order is not RGB. Just verify this.)
As simple as that! Study the header of the BMP to understand more about the format.

A: Note: you may need to grab an extra byte for the alpha values if your BMP has alpha channel. In that case image would be image[pixelcount][4], and you would add another getc(streamIn) line to hold that fourth index. My BMP turned out to not need that.
 // super-simplified BMP read algorithm to pull out RGB data
 // read image for coloring scheme
 int image[1024][3]; // first number here is 1024 pixels in my image, 3 is for RGB values
 FILE *streamIn;
 streamIn = fopen("./mybitmap.bmp", "r");
 if (streamIn == (FILE *)0){
   printf("File opening error ocurred. Exiting program.\n");
   exit(0);
 }

 int byte;
 int count = 0;
 for(i=0;i<54;i++) byte = getc(streamIn);  // strip out BMP header

 for(i=0;i<1024;i++){    // foreach pixel
    image[i][2] = getc(streamIn);  // use BMP 24bit with no alpha channel
    image[i][1] = getc(streamIn);  // BMP uses BGR but we want RGB, grab byte-by-byte
    image[i][0] = getc(streamIn);  // reverse-order array indexing fixes RGB issue...
    printf("pixel %d : [%d,%d,%d]\n",i+1,image[i][0],image[i][1],image[i][2]);
 }

 fclose(streamIn);

~Locutus


text:
Q: Extracting unique 7-digit string in a cell...Excel In excel, I want to extract  unique 7 digits in a cell with a string of digits. After the first 7 unique digits are extracted (placed in an adjacent column), the next 7 unique digits begin after the last digit of the previous unique 7-digit string.
e.g.(I have inserted separations to see where the following string ought to begin)
120381634|782540251|996314825168993247556112006387453961284587863952145786329520048752123666520473015444

1st  (unique 7-digits) 1203864
2nd                    7825401

A: This udf will allow you to set the length of unique characters per string and which value to return:
Function UniqueSeven(str As String, lngth As Long, k As Long) As String

Dim dict As Object
Set dict = CreateObject("scripting.Dictionary")

Dim test() As Variant
ReDim test(1 To Len(str) / lngth)

Dim j As Long
j = 1
Dim i As Long
For i = 1 To Len(str)
        If dict.Count < lngth And i < Len(str) Then
            On Error Resume Next
                dict.Add Mid(str, i, 1), Mid(str, i, 1)
            On Error GoTo 0
        Else
            Dim key As Variant
            For Each key In dict.keys
                test(j) = test(j) & dict(key)
            Next key
            j = j + 1
            dict.RemoveAll
            dict.Add Mid(str, i, 1), Mid(str, i, 1)
        End If
Next i

UniqueSeven = test(k)

End Function

You would use it thus:
With your string in A1, put this in a cell:
=IFERROR(UniqueSeven($A$1,7,ROW(A1)),"")

And copy down till you get blanks.
The second argument is the length of the string output.  I used ROW(A1) as a counter so it will return 1,2,3,4,... as it is dragged down the column.  It can be hard coded number also.


text:
Q: how to execute spark program efficient in cluster I have 2 node hadoop cluster. Each with 16GB RAM and 512GB Harddisk.
I have written spark program like below one
Code :
val input = sc.wholeTextFiles("folderpath/*")

do some operations on input.
convert it to dataframe. then register temptable. execute insert command to insert the dataframe value to hive table.

Then I open host 1 (which is my namenode of the cluster) terminal & I run spark submit command like
>spark-submit --class com.sample.parser --master yarn Parser.jar.

But it takes more than 50 mins to process 25 files which totals around 1gb.And when I check spark UI, executor list has only my host 2. host 1 is listed as driver.
So practically only one node is executing the program(host 2). Why?
Is there a way that I can have my driver also to execute the program. so that it runs little faster? Am I doing something wrong? Basically I want my driver node also to be part of executor(Both machines have 8 cores).
Thanks in Advance.

A: spark-submit by default runs in client(local) mode, in order to submit spark job in cluster mode use --deploy-mode as:
spark-submit \
--class com.sample.parser \
--master yarn \
--deploy-mode cluster \
Parser.jar

--deploy-mode: Whether to deploy your driver on the worker nodes
  (cluster) or locally as an external client (client) (default: client)

also, experiment with --num-executors <n> - with different <n> values...and see if it make any difference with perfomance of your app.


text:
Q: How can I check if the Data table contains the value I want and possibly click on the link? I'm using web driver and need to check whether the Data table contains the value I want and possibly click on the link?
I guess it should work with xpath?
For example:
I have web application that has datatable with 3 columns, where

    Using Automation

    Using Design

    Using Development

I tried the following, but it did not work:
    String abc = driver.findElement(By.xpath(".//*[@id='studyResultsId']/div/table/tbody/tr/td")).getText();

    //Retrieving the data from the Td of table in to a string
    if(abc.contains("Automation")) {
        System.out.println("contains Automation");
    } else {
        System.out.println("does not contains Automation");
    }
}

A: As per your html, I would like to talk about your xpath first,
driver.findElement(By.xpath(".//*[@id='studyResultsId']/div/table/tbody/tr/td")).getText();

The String 'foo' in following line is what you are able to get by your xpath above.

foo

Back to your html. Basically when you were searching by id='studyResultsId' you had already access the first div tag. So don't need the second '/div' again. Then you tried to locate 'td', yeah in current situation you had get the first 'td' element. But as you can see, all of the tag td have no text. It's tag a who has text. So you need to archive tag a and traverse it. Following code is my suggestion
//Initilize your webdriver first
List<WebElement> wl = driver.findElements(By.xpath("//div[@id='studyResultsId']//a"));

        for(int i=0; i<wl.size(); i++) {
            WebElement current = wl.get(i);

            if(current.getText().contains("Automation")) {
                System.out.println("Current tag '" + current.getText() + "' has text Automation");
            }  else {
                System.out.println("Current tag '" + current.getText() + "' has no text Automation");
            }
        }

A: As J.Lyu and sideshowbarker have already offered concise suggestions for your XPath expression I'll decline to offer another, however for brevity's sake here is how I would locate the required link WebElement(s) using other locators:
First I would start by locating the table WebElement using its id attribute:
WebElement table = driver.findElement(By.id("studyResultsId"));

There are two approaches you could now take to locate the required link(s):

*

*By Partial Link Text -
// This will return all link WebElements within the table
// that have partial matching visible text.

List<WebElement> matchingLinks = table.findElements(By.partialLinkText("Automation"));

*By Tag Name -
// This will return all link WebElements within the table

List<WebElement> tableLinks = table.findElements(By.tagName("a"));

To identify which of these link elements contain the text 'Automation', you can use a standard Java expression like so:
List<WebElement> matchingLinks = new ArrayList<>();

for (WebElement link : tableLinks) {
   if (link.contains("Automation")) {
      matchingLinks.add(link);
   }
}

You can then use either matchingLinks list of WebElements as required.


text:
Q: What is the likelihood in this situation? Suppose X and Y are binary and we assume
$P(X=1|Y=0)=0$;
$P(X=0|Y=0)=1$;
$P(X=1|Y=1)=\theta$; and
$P(X=0|Y=1)=1-\theta$
Does the likelihood function look like this?
$$L(\theta|X,Y)=0^{\text{#instances where X=1 and Y=0}} \cdot 1^{\text{# instances where X=0 and Y=0}} \cdot \theta^{\text{#instances where X=1 and Y=1}} \cdot (1-\theta)^{\text{#instances where X=0 and Y=1}}
$$
If this is correct, how can I deal with the situation when I observe some instances {X=1 and Y=0}? Does the MLE of theta remain the same given that the likelihood function becomes 0?


text:
Q: Minecraft error - says not downloaded When I try to run Minecraft (using JDK 6) it says login failed, not downloaded.
How do I rectify this? I don't know what to do and all the instructions say that the game should run right out of the launcher.


text:
Q: Bottom footer + Sticky nav bar I've been trying quite many of css guides to put the footer at the bottom of the page and the example below is the one that I find the simplest.

html,
body,
#root {
  height: 100%;
}

#root {
  display: flex;
  flex-direction: column;
}

nav {
  position: sticky;
  top: 0;
}

section {
  flex: 1;
}

section>div {
  height: 1000px;
}

  Header
  Navigation

Test

Test

Test

  Footer

It is working fine in terms of putting the footer at the bottom of the page, but the nav bar actually fails to follow the scroll at some point.
I am pretty sure this is because I've set the height of #root element to 100%.
The problem is even if I could guess "why" this is happening, I ain't sure "how" to fix this and keep the element (nav) staying at the top of the page.
Any helps, please?

A: Add some javascript there to add a class sticky to the navbar when the window gets scrolled and when the scroll is not on the top.
The class sticky contains some simple CSS like:

*

*position: fixed to make your div fix anywhere you want;

*top: 0 to make it stick on top;

*width: 100% to occupy all the screen width.

var navbarElement = document.getElementById("navbar");
var navbarScroll = navbarElement.offsetTop;

window.onscroll = function() {
  addClassOnScroll()
};

function addClassOnScroll() {
  if (window.pageYOffset >= navbarScroll) {
    navbarElement.classList.add("sticky")
  } else {
    navbarElement.classList.remove("sticky");
  }
}
html,
body,
#root {
  height: 100%;
  margin: 0;
}

#root {
  display: flex;
  flex-direction: column;
}

header {
  padding: 15px
}

nav {
  top: 0;
  background-color: yellow;
}

section {
  flex: 1;
}

section>div {
  height: 1000px;
}

footer {
  padding: 15px;
}

.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

  Header
  Navigation

Test

Test

Test

  Footer

A: I think you're almost there. You just need to replace height:100%; with min-height: 100vh; for #root. And then apply margin-top: auto; to the footer element.

html,
body {
  height: 100%;
  margin: 0; /*Reset the default margin of the browser*/
}

#root {
  display: flex;
  flex-direction: column;
  min-height: 100vh; /*The default height should be 100% of view port*/
}

nav {
  position: sticky;
  top: 0;
}

section {
  flex: 1;
}

footer {
  margin-top: auto; /*Push the footer to the bottom*/
}

  Header
  Navigation

Test

Test

Test

  Footer

A: according to your HTML, you don't need to style the HTML and the body. just leave them alone. you just need to reset your CSS if you want.
You can easily achieve that without any javascript by making #root fixed with 100vh and 100vw and overflow auto. that's it.

  * {
    scroll-behavior: smooth;
    margin: 0;
    padding: 0;
    text-decoration-line: none;

    border: 1px dashed;
  }

  #root {
    height: 100vh;
    width: 100vw;
    position: fixed;
    background: lightblue;
    display: flex;
    flex-direction: column;
    overflow: auto;
  }

  nav {
    position: sticky;
    top: 0;
  }

  section {
    flex: 1;
  }

  section>div {
    height: 400px;
  }

    Header
    Navigation

Test

Test

Test

    Footer


text:
Q: Getting Excel to handle CRLF's correctly in CSV I am creating CSV files to be opened in Excel.  The rows are separated by CRLF and that's fine, but some of the input data contains CRLF data in it as well.  Per the usual standards, I surround them with quotes, but Excel doesn't seem to recognize the CR character and puts a little box with a question mark in it instead.  I can strip the CR's out of the CSV file, but it seems like an unnecessary step.  Is there an easy way to get Excel to recognize a CRLF inside a row of a CSV file?

A: It looks like just using vbLf is the answer.  You are going to need to strip the carriage returns.
Take a look over at this StackOverflow question.

A: This works for me:

first record,"line one
line two",1
second record,only one line,2

In other words, the first record takes up more than one line in the CSV.


text:
Q: iAd Banner Not Displaying I have an iAd Banner that is not displaying. Here is my code:
The .h file:
#import <UIKit/UIKit.h>
#import <iAd/iAd.h>

@interface PopViewController : UIViewController <ADBannerViewDelegate>
{

}
@end

The .m file
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.

}

- (void)bannerViewDidLoadAd:(ADBannerView *)banner {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[banner setAlpha:1.0];
[UIView commitAnimations];
}

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error     {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[banner setAlpha:0];
[UIView commitAnimations];
}

The banner does not display at all. Can someone please fix this code? I have already linked the banner to files owner and made it a delegate. Thank you

A: I've seen that code too, and it also didn't work for me. Try this instead.
Lemme know how this goes. I can help you more if it didn't work.
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{

    if (banner.isBannerLoaded)
    {
        [UIView beginAnimations:@"animateAdBannerOff" context:NULL];
        // Assumes the banner view is placed at the bottom of the screen.

        banner.frame = CGRectOffset(banner.frame, 0, banner.frame.size.height);
        [UIView commitAnimations];
    }

}

- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{

    if (!banner.isBannerLoaded)
    {
        [UIView beginAnimations:@"animateAdBannerOn" context:NULL];
        // Assumes the banner view is just off the bottom of the screen.
        //banner.frame = CGPointMake(self.size.width/2, self.size.height);
        banner.frame = CGRectOffset(banner.frame, 0, -banner.frame.size.height);

        [UIView commitAnimations];
    }
}


text:
Q: Numpy arange floating point inconsistency I have a rather simple numpy task: create an long array with each element incremented by 0.001. Of course, np.arange is the answer. I am limiting myself to the default precision (float64). A simple check for the result is that every 1000th element of the array should have the same fractional part. I check that by a plot (see blue line in attached figure), and that is not the case.
tmin = 212990552.75436273
tmax = 213001474.74473435
tbins = np.arange(tmin, tmax, 0.001)
plt.plot(tbins[::1000] % 1)

Hmm, I think... the floating point monster strikes again. My start value is large, but not that large that it screws up 64 bit floats. On I hunch, I try the following, which I think should mean the same thing:
nbins = tmin + np.arange(0, tmax-tmin, 0.001)
plt.plot(nbins[::1000] % 1)

Tada! There's a discrepancy right there. The difference monotonically creeps up to 0.14 over the ~10^7 elements in the array. Note that since tmin is x.xxx36273, I expect all numbers to be of the form x.xxx36273. nbins has that, tbins does not.
In [68]: tbins[-1]
Out[68]: 213001474.60374644

In [69]: nbins[-1]
Out[69]: 213001474.74436274

A call to numpy gurus out there - why is this happening?

A: You are basically correct; use the second method if you care for the exact decimals of the elements of the array.
In your first attempt, tbins = np.arange(tmin, tmax, 0.001), you are mixing large and small floats in a single computation. The exact value of a given element is computed as the sum of the previous element and 0.001. This previous value is always huge compared to 0.001, so this summation will not be very accurate (for best accuracy when doing floating point addition, the two operands should be of the same order of magnitude).
In your second attempt, nbins = tmin + np.arange(0, tmax-tmin, 0.001), the summations in the np.arange(0, tmax-tmin, 0.001) part are all very accurate, because the huge number tmin is left out, and only added on in the end. This last addition of tmin to each element will have poor accuracy, meaning that in the end, each element will have gone through one operation with poor accuracy. Compare that to the first attempt, where the value of a given element has the accumulated error of all previous elements. That is, the further on in the array an element is located, the worse off it is (as your plot confirms).

A:
every 1000th element of the array should have the same fractional part

That would be true for actual numbers but not for floating point values. The floating points values you get do not always match the actual numbers you would expect. For instance you would expect tbins[1] to be the number 212990552.75536273, but you get 212990552.75536272 instead, which is the nearest float64 value:
In [58]: tbins[0]
Out[58]: 212990552.75436273

In [59]: tbins[1]
Out[59]: 212990552.75536272

In [60]: tbins[0] + 0.001
Out[60]: 212990552.75536272

In [61]: 212990552.75536273
Out[61]: 212990552.75536272


text:
Q: Shell command works in terminal but not during Jenkins build I have a Jenkins build server that runs the following command before each build is completed:
sudo make -f nameOfMakeFile.mak

When I'm in the terminal and in the appropriate directory, this command works perfectly and produces the desired OUTDIR file. But for some reason when Jenkins runs the same command I get this error:
sudo make -f nameOfMakeFile.mak
/bin/sh: 1: cd: can't cd to ../../ThirdParty/aes/

At which point it proceeds to CD into another directory and fails.
Any idea why my terminal command works but Jenkins running the same command does not?

A: ../../ThirdParty/aes/ is obviously a relative path. You have no idea where Jenkins is starting from when it executes that cd command. You will have to make the path global, or have a known starting point for your script.

A: Your jenkins user probably has no access to ../../ThirdParty/aes/


text:
Q: top hat filter running time I have a problem with speed of a top hat filter. In an IEEE transaction paper, the running time of top hat applied to an image with resolution 320× 256 is estimated 0.0062 second with MATLAB software on a PC with 8-GB memory and 4-GHz Intel i7 processor. table_time I run the following code with openCV on a laptop with 6-GB memory and 2.6-GHz Intel i5 processor for this image with the same resolution:
enter image description here
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(){
    double t0 = (double)getTickCount();
    Mat src,dst;
    src=imread("E:/tree.jpg",0);
    Mat element = getStructuringElement(MORPH_ELLIPSE,Size(15,15));
    morphologyEx(src,dst,MORPH_TOPHAT,element,Point(-1,-1));
    double elapsed=((double)getTickCount()-t0)/getTickFrequency();
    cout<<elapsed<<"second"<<"\n";
    return -1;}

It takes .05375 second. In spite of the the fact that C++ and openCV are fast, but why the running time of top hat is 6 ms in matlab and 54 ms in opencv. how I could accelerate it?

A: First and most important, you are counting the image loading from the disk, which is usually the slowest part of the program. If you want to compare to the paper, time only the tophat function without anything else.
Furthermore, there are many other compiling options which can effect this. You can try to compile OpenCV with all kind of processor specific optimization, CUDA, etc.. which can have a great effect.

A: here is my test result on my laptop ( Intel(R)_Core(TM)_i5-3230M_CPU_@_2.60GHz)
0.00129578 seconds!!
i think the most important thing is how did you compile OpenCV. there is many options. i attached my output of getBuildInformation()
test code (improved version of your code)
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main() {

    Mat src, dst;
    src = imread("tree.jpg", 0);
    Mat element = getStructuringElement(MORPH_ELLIPSE, Size(15, 15));
    double elapsed = 0;
    for (int i = 0; i < 100; i++)
    {
        double t0 = (double)getTickCount();
        morphologyEx(src, dst, MORPH_TOPHAT, element, Point(-1, -1));
        elapsed += ((double)getTickCount() - t0) / getTickFrequency();
    }

    cout << elapsed / 100 << " seconds" << "\n";
    cout << getBuildInformation();
    imshow("result", dst);
    waitKey();
    return -1;
}

output of the test code
0.00129578 seconds

General configuration for OpenCV 3.1.0-dev =====================================
  Version control:               unknown

  Extra modules:
    Location (extra):            D:/git/opencv_contrib/modules
    Version control (extra):     unknown

  Platform:
    Timestamp:                   2016-05-27T19:59:05Z
    Host:                        Windows 10.0.10586 AMD64
    CMake:                       3.5.0-rc3
    CMake generator:             Visual Studio 14 2015 Win64
    CMake build tool:            C:/Program Files (x86)/MSBuild/14.0/bin/MSBuild.exe
    MSVC:                        1900

  C/C++:
    Built as dynamic libs?:      YES
    C++ Compiler:                C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe  (ver 19.0.23506.0)
    C++ flags (Release):         /DWIN32 /D_WINDOWS /W4 /GR /EHa  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:AVX /Oi  /wd4251 /wd4324 /wd4275 /wd4589 /MP4  /MD /O2 /Ob2 /D NDEBUG
    C++ flags (Debug):           /DWIN32 /D_WINDOWS /W4 /GR /EHa  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:AVX /Oi  /wd4251 /wd4324 /wd4275 /wd4589 /MP4  /D_DEBUG /MDd /Zi /Ob0 /Od /RTC1
    C Compiler:                  C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe
    C flags (Release):           /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:AVX /Oi    /MP4  /MD /O2 /Ob2 /D NDEBUG
    C flags (Debug):             /DWIN32 /D_WINDOWS /W3  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /arch:AVX /Oi    /MP4  /D_DEBUG /MDd /Zi /Ob0 /Od /RTC1
    Linker flags (Release):      /machine:x64  /INCREMENTAL:NO
    Linker flags (Debug):        /machine:x64  /debug /INCREMENTAL
    Precompiled headers:         NO
    Extra dependencies:          comctl32 gdi32 ole32 setupapi ws2_32 D:/git/pthreadVC2.lib
    3rdparty dependencies:       zlib libjpeg libpng libtiff libjasper IlmImf libprotobuf

  OpenCV modules:
    To be built:                 core flann imgproc ml photo reg surface_matching video dnn fuzzy imgcodecs shape videoio highgui objdetect plot superres ts xobjdetect xphoto bgsegm bioinspired cvblobslib dpm face features2d line_descriptor saliency text calib3d ccalib datasets rgbd stereo structured_light videostab xfeatures2d ximgproc aruco optflow stitching tracking ayvos java
    Disabled:                    world contrib_world
    Disabled by dependency:      -
    Unavailable:                 cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev python2 python3 viz cvv hdf matlab sfm

  Windows RT support:            NO

  GUI:
    QT:                          NO
    Win32 UI:                    YES
    OpenGL support:              NO
    VTK support:                 NO

  Media I/O:
    ZLib:                        build (ver 1.2.8)
    JPEG:                        build (ver 90)
    WEBP:                        NO
    PNG:                         build (ver 1.6.19)
    TIFF:                        build (ver 42 - 4.0.2)
    JPEG 2000:                   build (ver 1.900.1)
    OpenEXR:                     build (ver 1.7.1)
    GDAL:                        NO

  Video I/O:
    Video for Windows:           NO
    DC1394 1.x:                  NO
    DC1394 2.x:                  NO
    FFMPEG:                      YES (prebuilt binaries)
      codec:                     YES (ver 56.41.100)
      format:                    YES (ver 56.36.101)
      util:                      YES (ver 54.27.100)
      swscale:                   YES (ver 3.1.101)
      resample:                  NO
      gentoo-style:              YES
    GStreamer:                   NO
    OpenNI:                      NO
    OpenNI PrimeSensor Modules:  NO
    OpenNI2:                     NO
    PvAPI:                       NO
    GigEVisionSDK:               NO
    DirectShow:                  YES
    Media Foundation:            NO
    XIMEA:                       NO
    Intel PerC:                  NO

  Parallel framework:            Concurrency

  Other third-party libraries:
    Use IPP:                     NO
    Use IPP Async:               NO
    Use Eigen:                   NO
    Use Cuda:                    NO
    Use OpenCL:                  YES
    Use custom HAL:              NO

  OpenCL:                        <Dynamic loading of OpenCL library>
    Include path:                D:/git/opencv/3rdparty/include/opencl/1.2
    Use AMDFFT:                  NO
    Use AMDBLAS:                 NO

  Python 2:
    Interpreter:                 C:/Python27/python.exe (ver 2.7.11)

  Python 3:
    Interpreter:                 NO

  Python (for build):            C:/Python27/python.exe

  Java:
    ant:                         C:/Program Files/apache-ant/bin/ant.bat (ver 1.9.6)
    JNI:                         C:/Program Files/Java/jdk1.8.0_74/include C:/Program Files/Java/jdk1.8.0_74/include/win32 C:/Program Files/Java/jdk1.8.0_74/include
    Java wrappers:               YES
    Java tests:                  NO

  Matlab:                        NO

  Tests and samples:
    Tests:                       NO
    Performance tests:           YES
    C/C++ Examples:              YES

  Install path:                  D:/opencv-build/install

  cvconfig.h is in:              D:/opencv-build
-----------------------------------------------------------------