text:
Q: Bootstrap 3 modal vertical position center This is a two part question:

*

*How can you position the modal vertically in the center when you don't know the exact height of the modal?

*Is it possible to have the modal centered and have overflow:auto in the modal-body, but only if the modal exceeds the screen height?
I have tried using this:
.modal-dialog {
  height: 80% !important;
  padding-top:10%;
}

.modal-content {
  height: 100% !important;
  overflow:visible;
}

.modal-body {
  height: 80%;
  overflow: auto;
}

This gives me the result I need when the content is much larger than vertical screen size, but for small modal contents it's pretty much unusable.

A: The most universal solution I wrote. Dynamicaly computes with dialog height. (Next step could be recalculating of dialogs' height on window resize.)
JSfiddle: http://jsfiddle.net/8Fvg9/3/
// initialise on document ready
jQuery(document).ready(function ($) {
    'use strict';

    // CENTERED MODALS
    // phase one - store every dialog's height
    $('.modal').each(function () {
        var t = $(this),
            d = t.find('.modal-dialog'),
            fadeClass = (t.is('.fade') ? 'fade' : '');
        // render dialog
        t.removeClass('fade')
            .addClass('invisible')
            .css('display', 'block');
        // read and store dialog height
        d.data('height', d.height());
        // hide dialog again
        t.css('display', '')
            .removeClass('invisible')
            .addClass(fadeClass);
    });
    // phase two - set margin-top on every dialog show
    $('.modal').on('show.bs.modal', function () {
        var t = $(this),
            d = t.find('.modal-dialog'),
            dh = d.data('height'),
            w = $(window).width(),
            h = $(window).height();
        // if it is desktop & dialog is lower than viewport
        // (set your own values)
        if (w > 380 && (dh + 60) < h) {
            d.css('margin-top', Math.round(0.96 * (h - dh) / 2));
        } else {
            d.css('margin-top', '');
        }
    });

});

A: This is quite old and specifically asks for a solution using Bootstrap 3, but for anyone wondering: from Bootstrap 4 on there is a built-in solution called .modal-dialog-centered. Here's the issue: https://github.com/twbs/bootstrap/issues/23638
So using v4 you just need to add .modal-dialog-centered to .modal-dialog to vertically center the modal:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
  Launch demo modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        ...

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Demo

A: Found the perfect solution from here
$(function() {
    function reposition() {
        var modal = $(this),
            dialog = modal.find('.modal-dialog');
        modal.css('display', 'block');

        // Dividing by two centers the modal exactly, but dividing by three
        // or four works better for larger screens.
        dialog.css("margin-top", Math.max(0, ($(window).height() - dialog.height()) / 2));
    }
    // Reposition when a modal is shown
    $('.modal').on('show.bs.modal', reposition);
    // Reposition when the window is resized
    $(window).on('resize', function() {
        $('.modal:visible').each(reposition);
    });
});

A: My solution
.modal-dialog-center {
    margin-top: 25%;
}

                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

A: $('#myModal').on('shown.bs.modal', function() {
    var initModalHeight = $('#modal-dialog').outerHeight(); //give an id to .mobile-dialog
    var userScreenHeight = $(document).outerHeight();
    if (initModalHeight > userScreenHeight) {
        $('#modal-dialog').css('overflow', 'auto'); //set to overflow if no fit
    } else {
        $('#modal-dialog').css('margin-top',
        (userScreenHeight / 2) - (initModalHeight/2)); //center it if it does fit
    }
});

A: Here's one other css only method that works pretty well and is based on this:
http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/
sass:
.modal {
    height: 100%;

    .modal-dialog {
        top: 50% !important;
        margin-top:0;
        margin-bottom:0;
    }

    //keep proper transitions on fade in
    &.fade .modal-dialog {
        transform: translateY(-100%) !important;
    }
    &.in .modal-dialog {
        transform: translateY(-50%) !important;
    }
}

A: This works for me:
.modal {
  text-align: center;
  padding: 0!important;
}

.modal:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -4px;
}

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}

A: .modal {
  text-align: center;
}

@media screen and (min-width: 768px) {
  .modal:before {
    display: inline-block;
    vertical-align: middle;
    content: " ";
    height: 100%;
  }
}

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}

And adjust a little bit .fade class to make sure it appears out of the top border of window, instead of center

A: It can simply can be fixed with display: flex
.modal-dialog {
  margin-top: 0;
  margin-bottom: 0;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.modal.fade .modal-dialog {
  transform: translate(0, -100%);
}

.modal.in .modal-dialog {
  transform: translate(0, 0);
}

With prefix
.modal-dialog {
  margin-top: 0;
  margin-bottom: 0;
  height: 100vh;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
      -ms-flex-direction: column;
          flex-direction: column;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
      -ms-flex-pack: center;
          justify-content: center;
}

.modal.fade .modal-dialog {
  -webkit-transform: translate(0, -100%);
          transform: translate(0, -100%);
}
.modal.in .modal-dialog {
  -webkit-transform: translate(0, 0);
          transform: translate(0, 0);
}

A: i have downloaded bootstrap3-dialog from bellow link and modified the open function in  bootstrap-dialog.js
https://github.com/nakupanda/bootstrap3-dialog
Code
open: function () {
            !this.isRealized() && this.realize();
            this.updateClosable();
            //Custom To Vertically centering Bootstrap
            var $mymodal = this.getModal();
            $mymodal = $mymodal.append('

');
            $mymodal = $mymodal.find(".modal-dialog").appendTo($mymodal.find(".centerModal"));
            //END
            this.getModal().modal('show');
            return this;
        }

Css
.centerModal .modal-header{
    text-align:left;
}
.centerModal .modal-body{
    text-align:left;
}

A: If you're okay with using flexbox then this should help solve it.
.modal-dialog {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
}

.modal-content {
  margin: 0 auto;
}

A: I came up with a pure css solution! It's css3 though, which means ie8 or lower is not supported, but other than this it's tested and working on ios, android, ie9+, chrome, firefox, desktop safari..
I am using the following css:
.modal-dialog {
  position:absolute;
  top:50% !important;
  transform: translate(0, -50%) !important;
  -ms-transform: translate(0, -50%) !important;
  -webkit-transform: translate(0, -50%) !important;
  margin:auto 5%;
  width:90%;
  height:80%;
}
.modal-content {
  min-height:100%;
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;
}
.modal-body {
  position:absolute;
  top:45px; /** height of header **/
  bottom:45px;  /** height of footer **/
  left:0;
  right:0;
  overflow-y:auto;
}
.modal-footer {
  position:absolute;
  bottom:0;
  left:0;
  right:0;
}

Here is a fiddle.
http://codepen.io/anon/pen/Hiskj
..selecting this as the correct answer since there's no extra heavy javascript that brings the browser to its knees in case of more than one modals.

A: My solution:
.modal.in .modal-dialog
{
    -webkit-transform: translate(0, calc(50vh - 50%));
    -ms-transform: translate(0, 50vh) translate(0, -50%);
    -o-transform: translate(0, calc(50vh - 50%));
    transform: translate(0, 50vh) translate(0, -50%);
}

A: Adding this simple css also works.
.modal-dialog {
  height: 100vh !important;
  display: flex;
}

.modal-content {
  margin: auto !important;
  height: fit-content !important;
}

A: All what I did in my case is to set the Top in my css knowing the height of the modal

 ...

in my css i set
#myModal{
    height: 400px;
    top: calc(50% - 200px) !important;
}

A: Try something like this:
.popup__overlay {
    position: fixed;
    left:  0;
    top:  0;
    width: 100%;
    height: 100%;
    z-index: 999;
    text-align: center
    }
.popup {
    display: inline-block;
    vertical-align: middle
    }

A: 1. How can you position the modal vertically in the center when you don't know the exact height of the modal?
To absolute center the Bootstrap 3 Modal without declaring a height, you will first need to overwrite the Bootstrap CSS by adding this to your style sheet:
.modal-dialog-center { /* Edited classname 10/03/2014 */
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
}

This will position the modal-dialogs top-left corner in the center of the window.
We have to add this media query or else the modal margin-left is wrong on small devices:
@media (max-width: 767px) {
  .modal-dialog-center { /* Edited classname 10/03/2014 */
    width: 100%;
  }
}

Now we will need to adjust its position with JavaScript. To do that we give the element a negative top and left margin equal to half of its height and width. In this example we will be using jQuery since it is available with Bootstrap.
$('.modal').on('shown.bs.modal', function() {
    $(this).find('.modal-dialog').css({
        'margin-top': function () {
            return -($(this).outerHeight() / 2);
        },
        'margin-left': function () {
            return -($(this).outerWidth() / 2);
        }
    });
});

Update (01/10/2015):
Adding on Finik's answer. Credits to Centering in the Unknown.
.modal {
  text-align: center;
  padding: 0!important;
}

.modal:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -4px; /* Adjusts for spacing */
}

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}

Notice the negative margin-right? This removes the space added by inline-block. That space causes the modal to jump to the bottom of the page @media width < 768px.
2. Is it possible to have the modal centered and have overflow:auto in the modal-body, but only if the modal exceeds the screen height?

This is possible by giving the modal-body an overflow-y:auto and a max-height. This takes a bit more work to get it working properly. Start with adding this to your style sheet:
.modal-body {
    overflow-y: auto;
}
.modal-footer {
    margin-top: 0;
}

We will use jQuery again to get the window height and set the max-height of the modal-content first. Then we have to set the max-height of the modal-body, by subtracting the modal-content with the modal-header and modal-footer:
$('.modal').on('shown.bs.modal', function() {
    var contentHeight = $(window).height() - 60;
    var headerHeight = $(this).find('.modal-header').outerHeight() || 2;
    var footerHeight = $(this).find('.modal-footer').outerHeight() || 2;

    $(this).find('.modal-content').css({
        'max-height': function () {
            return contentHeight;
        }
    });

    $(this).find('.modal-body').css({
        'max-height': function () {
            return (contentHeight - (headerHeight + footerHeight));
        }
    });

    $(this).find('.modal-dialog').css({
        'margin-top': function () {
            return -($(this).outerHeight() / 2);
        },
        'margin-left': function () {
            return -($(this).outerWidth() / 2);
        }
    });
});

You can find a working demo here with Bootstrap 3.0.3: http://cdpn.io/GwvrJ
EDIT: I recommend using the updated version instead for a more responsive solution: http://cdpn.io/mKfCc
Update (30/11/2015):
function setModalMaxHeight(element) {
  this.$element     = $(element);
  this.$content     = this.$element.find('.modal-content');
  var borderWidth   = this.$content.outerHeight() - this.$content.innerHeight();
  var dialogMargin  = $(window).width() < 768 ? 20 : 60;
  var contentHeight = $(window).height() - (dialogMargin + borderWidth);
  var headerHeight  = this.$element.find('.modal-header').outerHeight() || 0;
  var footerHeight  = this.$element.find('.modal-footer').outerHeight() || 0;
  var maxHeight     = contentHeight - (headerHeight + footerHeight);

  this.$content.css({
      'overflow': 'hidden'
  });

  this.$element
    .find('.modal-body').css({
      'max-height': maxHeight,
      'overflow-y': 'auto'
  });
}

$('.modal').on('show.bs.modal', function() {
  $(this).show();
  setModalMaxHeight(this);
});

$(window).resize(function() {
  if ($('.modal.in').length != 0) {
    setModalMaxHeight($('.modal.in'));
  }
});

(Updated 30/11/2015 http://cdpn.io/mKfCc with above edit)

A: There is an easiest way to do this using css:
.modal-dialog {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    width:500px;
    height:300px;
}

That's it. Notice that it is only needed to be applied to the .modal-dialog container div.
Demo: https://jsfiddle.net/darioferrer/0ueu4dmy/

A: Expanding on @Finik's excellent answer, this fix is only applied to non-mobile devices. I tested in IE8, Chrome, and Firefox 22 - it works with very long or short content.
.modal {
  text-align: center;
}
@media screen and (min-device-width: 768px) {
  .modal:before {
    display: inline-block;
    vertical-align: middle;
    content: " ";
    height: 100%;
  }
}

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}

A: You might want to check out this collection of methods for absolute centering a div: http://codepen.io/shshaw/full/gEiDt

A: A simple way. Work for me. Thks rensdenobel :)
http://jsfiddle.net/rensdenobel/sRmLV/13/

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>

                    <button type="button" class="close" data-dismiss="modal">×Close

                    </button>

Modal title

...

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>

A: yet another solution which will set a valid position for each visible modal on window.resize event and on show.bs.modal:
(function ($) {
    "use strict";
    function centerModal() {
        $(this).css('display', 'block');
        var $dialog  = $(this).find(".modal-dialog"),
            offset       = ($(window).height() - $dialog.height()) / 2,
            bottomMargin = parseInt($dialog.css('marginBottom'), 10);

        // Make sure you don't hide the top part of the modal w/ a negative margin if it's longer than the screen height, and keep the margin equal to the bottom margin of the modal
        if(offset < bottomMargin) offset = bottomMargin;
        $dialog.css("margin-top", offset);
    }

    $(document).on('show.bs.modal', '.modal', centerModal);
    $(window).on("resize", function () {
        $('.modal:visible').each(centerModal);

    });
})(jQuery);

A: var modalVerticalCenterClass = ".modal";
function centerModals($element) {
    var $modals;
    if ($element.length) {
        $modals = $element;
    } else {
        $modals = $(modalVerticalCenterClass + ':visible');
    }
    $modals.each( function(i) {
        var $clone = $(this).clone().css('display', 'block').appendTo('body');
        var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2);
        top = top > 0 ? top : 0;
        $clone.remove();
        $(this).find('.modal-content').css("margin-top", top);
    });
}
$(modalVerticalCenterClass).on('show.bs.modal', function(e) {
    centerModals($(this));
});
$(window).on('resize', centerModals);

A: I know it's a bit late, but I am adding a new answer so that it doesn't get lost in the crowd. It's a cross-desktop-mobile-browser solution that works everywhere properly as it should.
It just needs the modal-dialog to be wrapped inside a modal-dialog-wrap class and need to have the following code additions:
.modal-dialog-wrap {
  display: table;
  table-layout: fixed;
  width: 100%;
  height: 100%;
}

.modal-dialog {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

.modal-content {
  display: inline-block;
  text-align: left;
}

The dialog starts centered and in cases of large content it simply grows vertically until a scrollbar appears.
Here is a working fiddle for your pleasure!
https://jsfiddle.net/v6u82mvu/1/

A:

.modal {
}
.vertical-alignment-helper {
    display:table;
    height: 100%;
    width: 100%;
}
.vertical-align-center {
    /* To center vertically */
    display: table-cell;
    vertical-align: middle;
}
.modal-content {
    /* Bootstrap sets the size of the modal in the modal-dialog class, we need to inherit it */
    width:inherit;
    height:inherit;
    /* To center horizontally */
    margin: 0 auto;
}

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>

                    <button type="button" class="close" data-dismiss="modal">×Close

                    </button>

Modal title

...

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>

CSS:
.modal {
}
.vertical-alignment-helper {
    display:table;
    height: 100%;
    width: 100%;
}
.vertical-align-center {
    /* To center vertically */
    display: table-cell;
    vertical-align: middle;
}
.modal-content {
    /* Bootstrap sets the size of the modal in the modal-dialog class, we need to inherit it */
    width:inherit;
    height:inherit;
    /* To center horizontally */
    margin: 0 auto;
}

HTML:

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>

                    <button type="button" class="close" data-dismiss="modal">×Close

                    </button>

Modal title

...

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>

Reference: http://jsfiddle.net/rensdenobel/sRmLV/13/

A: Consider using the bootstrap-modal plugin found here - https://github.com/jschr/bootstrap-modal
The plugin will center all of your modals

A: For the centering, I don't get what's with the overly complicated solutions. bootstrap already centers it horizontally for you, so you don't need to mess with this. My solution is just set a top margin only using jQuery.
$('#myModal').on('loaded.bs.modal', function() {
    $(this).find('.modal-dialog').css({
        'margin-top': function () {
            return (($(window).outerHeight() / 2) - ($(this).outerHeight() / 2));
        }
    });
});

I've used the loaded.bs.modal event as I am remotely loading content, and using the shown.ba.modal event causes the height calculation to be incorrect. You can of course add in an event for the window being resized if you need it to be that responsive.

A: Very very easy way to achieve this concept and you will get modal always in the moddle of your screen by css as fllow : http://jsfiddle.net/jy0zc2jc/1/
you have to just modal class display as table by following css:
display:table

and modal-dialog as display:table-cell
see full working example in given fiddle

A: it's not that complicated.
please try this:
$(document).ready(function(){
    var modalId = "#myModal";
    resize: function(){
            var new_margin = Math.ceil(($(window).height() - $(modalId).find('.modal-dialog').height()) / 2);
            $(modalId).find('.modal-dialog').css('margin-top', new_margin + 'px');
    }
    $(window).resize(function(){
        resize();
    });
    $(modalId).on('shown.bs.modal', function(){
        resize();
    });
});

A: Use this simple script that centers the modals.
If you want you can set a custom class (ex: .modal.modal-vcenter instead of .modal) to limit the functionality only to some modals.
var modalVerticalCenterClass = ".modal";

function centerModals($element) {
    var $modals;
    if ($element.length) {
    $modals = $element;
    } else {
    $modals = $(modalVerticalCenterClass + ':visible');
}
$modals.each( function(i) {
    var $clone = $(this).clone().css('display', 'block').appendTo('body');
    var top = Math.round(($clone.height() - $clone.find('.modal-content').height()) / 2);
    top = top > 0 ? top : 0;
    $clone.remove();
    $(this).find('.modal-content').css("margin-top", top);
    });
}
$(modalVerticalCenterClass).on('show.bs.modal', function(e) {
    centerModals($(this));
});
$(window).on('resize', centerModals);

Also add this CSS fix for the modal's horizontal spacing; we show the scroll on the modals, the body scrolls is hidden automatically by Bootstrap:
/* scroll fixes */
.modal-open .modal {
    padding-left: 0px !important;
    padding-right: 0px !important;
    overflow-y: scroll;
}

A: In mobile plantform it might look a little different, here's my code.

Basic Modal Example

Div for modal

确定要取消本次订单嘛?

              取消
              确定

A: set modal center to screen
.modal {
  text-align: center;
  padding: 0!important;
}
.modal:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -4px;
}
.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}

A: The simplest solution is to add modal dialog styles to the top of the page or import css with this code:

Modal declaration:

Modal title

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                ...

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>

Modal usage:

 ...

A: This is responsive code and also open with different size in mobile view please check once.
.modal {
  text-align: center;
  padding: 0!important;
}

.modal:before {
  content: '';
  display: inline-block;
  height: 20%;
  vertical-align: middle;
  margin-right: -4px;
}

.modal-dialog {
  display: inline-block;
  text-align: left;
  vertical-align: middle;
}


text:
Q: My program "stuck in this line" reading stream This
So I am reading a stream like usual. Then it just stuck. It doesn't throw exception or anything. It just stucks.
            Try
                Do
                    read = stream.Read(datain, 0, datain.Length) 'Stuck here
                    responseData = System.Text.Encoding.ASCII.GetString(datain, 0, read)
                    finalResponse = finalResponse + responseData
                Loop While read > 0
            Catch ex As Exception

What should I do so that the program would never get stuck like that? Notice I already put the code inside try catch block
Here is the full program.
  Public Function getWhoisInfoAsText4(strDomainName As String, whoisServerToTry As String) As String
        'testAsisWhois()
        Dim data = System.Text.Encoding.ASCII.GetBytes(strDomainName & Microsoft.VisualBasic.vbCr & Microsoft.VisualBasic.vbLf)
        Dim finalResponse = String.Empty
        Dim client As TcpClient
        Try
            client = New TcpClient(whoisServerToTry, 43)
        Catch ex As Exception
            Return ""
        End Try

        Dim stream = client.GetStream()
        Using stream

            stream.Write(data, 0, data.Length)

            Dim datain = New Byte(254) {}
            Dim responseData = String.Empty
            Dim read As Integer
            Try
                Do
                    read = stream.Read(datain, 0, datain.Length)
                    responseData = System.Text.Encoding.ASCII.GetString(datain, 0, read)
                    finalResponse = finalResponse + responseData
                Loop While read > 0
            Catch ex As Exception

            End Try

        End Using

        If finalResponse.Contains("Name Server:") Then
            appendToTextFile(whoisServerToTry + vbNewLine, "appendfiles", Scripting.IOMode.ForAppending)
        End If

        finalResponse += (whoisServerUsed + whoisServerToTry + vbNewLine)
        Return finalResponse
    End Function

A: does your program stuck at the first loop sequence?
According to MSDN mabye this should help
            Dim numBytesRead as Integer = 0
            Do
                read = stream.Read(datain, numBytesRead, datain.Length)
                responseData = System.Text.Encoding.ASCII.GetString(datain, 0, read)
                finalResponse = finalResponse + responseData
                numBytesRead += read
            Loop While read > 0

A: Stream.Read waits always until the amount of bytes it is expecting is coming, if there is an interruption on the communication just in the moment the program is exactly on the Read and the connection get close the program will be forever in this point waiting for the rest of the bytes to come unless you will configure a ReadTimeout, then after not receiving any bytes during this time it will throw an exception.
You should then make a try catch and restart the connection.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does the author concludes that the expected score is $k + 0,5$ between $(n,n)$ and $(n-k, n-k)$ In this paper, at page 302, the author calculates the expected score of a gamer who plays the game that a player guesses the colour of the next card, red of black, in a normal 52 deck, if it gets right, it scores 1, and not it gets 0.
The author defines a "game path" in n-n lattice such that one each vertex specifies the number of red/black card in the remaining deck. Then he argues that between $(n,n)$ and $(n-k, n-k)$, the expected score of the gamer is $k + 0,5$ provided that the contribution of the first card to the expected score is $0,5$.
But I couldn't understand how he did reasoned that the expected score is $k + 0,5$ between $(n,n)$ and $(n-k, n-k)$ provided that in this "interval" he always guesses the colour which is not the colour of the first card.
Any help is appreciated.

A paradoxical aspect to counting cards in "Red or Black" is that the
  expected score  grows proportionally with the number of times that
  card counting gives no information. Those situations occur on the
  diagonal: red = black. Suppose that we started at  $(n, n)$ and that
  the first card in the deck is black. We can assume that this first
  card  contributes $1/2$ to our expected score. Now suppose that our
  game path meets the diagonal next at $(n - k,n - k)$. In the course of
  traversing this path we would  continue to guess that the next card is
  red since red $>$ black in that portion of the  path; therefore, we
  will be correct exactly $k$ times and incorrect $k - 1 $ times during
  this part of the game. In the path from $(n, n)$ to $(n - k, n - k)$,
  our expected score is  then $k + 0.5$ of a possible $2k$.

A: Between two positions on the diagonal, one colour will continuoiusly be more likely than the other (namely the colour that is not the colour of the first card). So obviously, the best strategy to use suring that time is to always guess the more likely colour. On the way from $(n-1,n)$ or $(n-n-1)$ to $(n-k,n-k)$, this guess will be correct exactly $k$ times. Add the $\frac12$ from the first guess, and we have our $k+\frac12$.


text:
Q: How to Find a String in a Text File And Replace Each Time With User Input in a Python Script? I am new to python so excuse my ignorance.
Currently, I have a text file with some words marked as <>.
My goal is to essentially build a script which runs through a text file with such marked words. Each time the script finds such a word, it would ask the user for what it wants to replace it with.
For example, if I had a text file:
Today was a <<feeling>> day.

The script would run through the text file so the output would be:
Running script...
feeling? great
Script finished.

And generate a text file which would say:
Today was a great day.

Advice?
Edit: Thanks for the great advice! I have made a script that works for the most part like I wanted. Just one thing. Now I am working on if I have multiple variables with the same name (for instance, "I am <>. Bob is also <>.") the script would only prompt, feeling?, once and fill in all the variables with the same name.
Thanks so much for your help again.

A: import re
with open('in.txt') as infile:
    text = infile.read()
search = re.compile('<<([^>]*)>>')
text = search.sub(lambda m: raw_input(m.group(1) + '? '), text)
with open('out.txt', 'w') as outfile:
    outfile.write(text)

A: To open a file and loop through it:
Use raw_input to get input from user
Now, put this together and update you question if you run into problems :-)

A: I understand you want advice on how to structure your script, right? Here's what I would do:

*

*Read the file at once and close it (I personally don't like to have open file objects, especially if my filesystem is remote).

*Use a regular expression (phihag has suggested one in his answer, so I won't repeat it) to match the pattern of your placeholders. Find all of your placeholders and store them in a dictionary as keys.

*For each word in the dictionary, ask the user with raw_input (not just input). And store them as values in the dictionary.

*When done, parse your text substituting any instance of a given placeholder (key) with the user word (value). This is also done with regex.

The reason for using a dictionary is that a given placeholder could occur more than once and you probably don't want to make the user repeat the entry over and over again...

A: Basically the same solution as that offerred by @phihag, but in script form
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import re
from os import path

pattern = '<<([^>]*)>>'

def user_replace(match):
    return raw_input('%s? ' % match.group(1))

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', type=argparse.FileType('r'))
    parser.add_argument('outfile', type=argparse.FileType('w'))
    args = parser.parse_args()

    matcher = re.compile(pattern)

    for line in args.infile:
        new_line = matcher.sub(user_replace, line)
        args.outfile.write(new_line)

    args.infile.close()
    args.outfile.close()

if __name__ == '__main__':
    main()

Usage: python script.py input.txt output.txt
Note that this script does not account for non-ascii file encoding.

A: Try something like this
lines = []
with open(myfile, "r") as infile:
    lines = infile.readlines()

outlines = []
for line in lines:
    index = line.find("<<")
    if index > 0:
        word = line[index+2:line.find(">>")]
        input = raw_input(word+"? ")
        outlines.append(line.replace("<<"+word+">>", input))
    else:
        outlines.append(line)

with open(outfile, "w") as output:
    for line in outlines:
        outfile.write(line)

Disclaimer: I haven't actually run this, so it might not work, but it looks about right and is similar to something I've done in the past.
How it works:

*

*It parses the file in as a list where each element is one line of the file.

*It builds the output list of lines. It iterates through the lines in the input, checking if the string << exist. If it does, it rips out the word inside the << and >> brackets, using it as the question for a raw_input query. It takes the input from that query and replaces the value inside the arrows (and the arrows) with the input. It then appends this value to the list. If it didn't see the arrows it simply appended the line.

*After running through all the lines, it writes them to the output file. You can make this whatever file you want.

Some issues:

*

*As written, this will work for only one arrow statement per line. So if you had <<firstname>> <<lastname>> on the same line it would ignore the lastname portion. Fixing this wouldn't be too hard to implement - you could place a while loop using the index > 0 statement and holding the lines inside that if statement. Just remember to update the index again if you do that!

*It iterates through the list three times. You could likely reduce this to two, but if you have a small text file this shouldn't be a huge problem.

*It could be sensitive to encoding - I'm not entirely sure about that however. Worst case there you need to cast as a string.

Edit: Moved the +2 to fix the broken if statement.


text:
Q: ion-select-option selected attribute doesn't work selected = "m.selected" shows the selectbox empty when the page opens, even though the value is True. (This problem is experienced in ionic 4 & 5.)
details.page.html
<ion-item mode="ios">
     <ion-label>Unit</ion-label>
    <ion-select [(ngModel)]="selectedModel" mode="ios" interface="action-sheet">
       <ion-select-option *ngFor="let m of details?.unit" [value]="m" [selected]="m.selected">{{m.title}}</ion-select-option>
     </ion-select>
  </ion-item>

<div *ngIf="selectedModel">
<div>
{{selectedModel.name}}
</div>
...
 </div>

details.page.ts
selectedModel:any;
  constructor(private route:ActivatedRoute, private unitService: UnitService) { }

  ngOnInit() {
    let index = this.route.snapshot.paramMap.get('index');
    this.unitService.getUnDetails(index).subscribe(details =>{
      console.log('Details:', details);
      this.details = details;
    })
  }

}

data.json
[
    {
        "id":1,
        "name":"Food",
        "img":"food.jpg",
        "gm":"gr",
        "vitc":"0",
        "vita":"0.04",
        "unit":[
            {
                "i":1,
                "selected":"true",
                "title":"Full",
                "name":"Joe",
                "amount":"25"
            },
            {
                "i":2,
                "selected":"false",
                "title":"Half",
                "name":"Brad",
                "amount":"150"
            }
        ]
    },
    ...
   ]

How do I get the first value selected? I'm getting the data from Api.

A: EDIT
Try setting the selectedModel to the selected value in ngOnInit. So something like:
this.selectedModel = this.details.unit.find(u => u.selected);

I don't have full info on the this.details.unit variable, so I'm assuming a little bit on that info.


text:
Q: Trouble during generate XLS programmatically This code i have deployed on server side to convert a rep file (BO File )to xls file using macro of XLs.I invoked the macro through this jsp call and Macro convert .rep file to xls file . . When invoke the jsp from client side  on server system donot open xls sheet , but when i try to run same code as a standalone java code it work. Here i hjave attached a sample code.Could please help me.
<%@ page import="java.io.*" %><%@ page contentType="application/vnd.ms-excel"%> <html><head></head> <body> <% String cmdLine = "\"C:/Program Files (x86)/Microsoft Office/Office12/EXCEL.EXE\" /e/\"D:\\North%20America\\Workspace%20Defined_2013-03-23-06-50-50.rep\" D:\\NewFolder\\Converter.xlsm"; try{Process p = Runtime.getRuntime().exec(cmdLine); } catch(Exception e){ e.printStackTrace(); } %> </body> </html>

A: you cant do it like that. If you need to open excel when you call a jsp you need to set the content type of response. ie. application/vnd.ms-excel
<%@ page contentType="application/vnd.ms-excel" %>

This will indicate the browser incoming data stream is ms excel and browser will handle it accordingly


text:
Q: angular 4 nested formGroup array reset counter for internal group count I have a segment(id, time) that can have one or several people (role, infos). The field are generated dynamically. After generating several people for each segment I notice that the index for people does not restart with each segment created. When i go to remove a person the person selected is not the one removed (deleted).
So I have :
segment 1
-----person 1  (index = 0)
--segment 2
-----person 1  (index = 1)
-----person 2  (index = 2)
-----person 3  (index = 3)
--segment 3
-----person 1  (index = 4)
-----person 2  (index = 5)

How can I reset the counter for person so I can remove the selected person. How can I have the right index like :
segment 1
-----person 1  (index = 0)
--segment 2
-----person 1  (index = 0)
-----person 2  (index = 1)
-----person 3  (index = 2)
--segment 3
-----person 1  (index = 1)
-----person 2  (index = 2)

Here are my .html code

                Segment ID
                    <input type="text" formControlName="segmentId3" id="segmentId3" class="form-control" value="{{i+1}}" [attr.disabled]="true" required >

                Segment time :  {{mySummaryForm.value.segmentTime3 | json}}

                 1" (click)="deleteSegment(i)" class="btn btn-danger">Remove segment
                <button type="button" (click)="addPerson(i)" class="btn btn-info">Add a person</button>

   #{{j+1}}
                                person Role
                                <input formControlName="personR3" [typeahead]="personRole" [typeaheadOptionsLimit]="10" [typeaheadMinLength]="0" type="text" id="personR3" class="form-control" placeholder="select a role" (ngModelChange)="onChange($event)" required>

                                Person infos
                                <input formControlName="personI3" [typeahead]="states" [typeaheadOptionsLimit]="10" [typeaheadMinLength]="0" type="text" id="personI3" class="form-control" placeholder="select infos" (ngModelChange)="onChange($event)" required>

                                 1" (click)="deletePerson(i, j)" class="btn btn-warning">Remove

                Topic
                <textarea formControlName="topic" id="topic" class="form-control" (ngModelChange)="onChange($event)" required></textarea>

        <button type="button" (click)="addSegment(i)" class="btn btn-primary">Add a segment</button>

Here is my .ts code
addPerson(index: number) {
    let personRows3 = <FormArray>this.mySummaryForm.get(`segmentRows3.${index}.personRows3`)
    if(personRows3){
        personRows3.push(this.fb.group({
            personR3: '',
            personI3: ''
        }));
     }
}

deletePerson(indexSeg: number, indexPers: number) {
    let personRows3 = <FormArray>this.mySummaryForm.get(`segmentRows3.${index}.personRows3`);
    if(personRows3){
        personRows3.removeAt(indexPers);
    }
}

addSegment(index: number) {
    let segmentRows3 = <FormArray>this.mySummaryForm.get('segmentRows3');
    if(segmentRows3){
        segmentRows3.push(
            this.fb.group({
                segmentTime3: '',
                segmentId3: '',
                topic: '',
                personRows3: this.fb.array([
                this.fb.group({
                   personR3: '',
                   personI3: ''
                  })
                ])
            })
        );
    }
}

A: I guess you can use customised data-index attributes to achieve. It is explained more clearly with an example in the answered mentioned in the link.
data-index example


text: Q: marking events on time series Suppose I have a time series (say, for the sake of argument, the stock time series of AAPL for the last thirty years or so), and I want to mark (with some sort of a highlight, or flag, or whatever) pivotal events (Steve Jobs comes back, iMac released, iPhone released, etc). Is there a reasonably civilized way of doing that? This is a pretty common thing to do on Bloomberg terminal and such.


text:
Q: easystroke broken - how to fix or which alternate software to use I use easystroke some years now. But today it's gone :(
In the CLI I got this message:

easystroke: error while loading shared libraries:
libboost_serialization.so.1.71.0: cannot open shared object file: No
such file or directory

It seems easystroke is not under maintenance for some years now (ohh shocking!!!).
So how can I fix this or anybody knows another nice Applikation on Linux for Mouse-Gestures?
uname -a :

Linux 5.4.85-1-MANJARO #1 SMP PREEMPT Mon Dec 21 21:38:53 UTC 2020 x86_64 GNU/Linux

A: I've found a way to install it.
Even if the easystroke-git from AUR not work, it work to do it manually like described at the Page: https://github.com/berkeleybross/easy-gesture/blob/master/docs/build-instructions.md#releases
wget http://openartisthq.org/easystroke/patched-easystroke-master.tar.bz2
tar xvjf patched-easystroke-master.tar.bz2
cd patched-easystroke-master/easystroke
make


text:
Q: Url rewriting a Regex help What Regex do I need for match this url:
Match:
1234
1234/
1234/article-name

Don't match:
1234absd
1234absd/article-name
1234/article.aspx
1234/any.dot.in.the.url

A: ^\d+(/?)|(/[a-zA-Z-]+)$

That may work. or not. Hope it helps

A: You can try:
^\d+(?:\/[\w-]*)?$

This matches a non-empty sequence of digits at the beginning of the string, followed by an optional suffix of a / and a (possibly empty) sequence of word characters (letters, digits, underscore) and a -.
This matches (see on rubular):
1234
1234/
1234/article-name
42/section_13

But not:
1234absd
1234absd/article-name
1234/article.aspx
1234/any.dot.in.the.url
007/james/bond

No parenthesis regex
You shouldn't need to do this, but if you can't use parenthesis at all, you can always expand to alternation:
^\d+$|^\d+\/$|^\d+\/[\w-]*$

A: Hope this ll help u ........
        string data = "1234/article-name";
        Regex Constant = new Regex("(?<NUMBERS>([0-9]+))?(//)?(?<DATA>([a-zA-Z-]*))?");
        MatchCollection mc;
        mc = Constant.Matches(data,0);
        if (mc.Count>0)
        {
            for (int l_nIndex = 0; l_nIndex < mc.Count; l_nIndex++)
            {
                string l_strNum = mc[l_nIndex].Groups["NUMBERS"].Value;
                string l_strData = mc[l_nIndex].Groups["DATA"].Value;
            }
        }


text:
Q: draw boundary of searched region on google map In my android app, i need to highlight searched region by drawing polygon.
How to draw polygon to highlight region/city/state just by keywords? how can I get all co-ordinates of boundaries to draw polygon?
i.e. same as housing android app. for any searched region, they are showing boundary on the google map, from where they are getting these data?.
Any sources to get these region boundary data as google api is available for this?

A: I don't  know about any service that gives you back the borders of a region, but you can build one yourself.
Have a look at this answer here: Google Maps how to Show city or an Area outline
(it is not an Android specific answer, but it explains where to get the coordinates and it gives guidelines on how to parse them).
Best of luck!


text:
Q: How to handle deleting databases in Couch across multiple clients? Within CouchDB it's sometimes the case that eventually you'll probably have more deleted documents within a database than active documents. After a while this becomes somewhat nonoptimal, as you're syncing more deleted document data than anything else.
The official documentation recommends periodically destroying the databases in order to get around this, but I've noticed that all that happens when doing this is that a client with a local copy of the database (e.g. if you have a database named "username" that's designed to replicate to a client device via Pouch), when it sees the blank database, refills it back up, deleted document records and all.
Short of changing the database name every time, is there any way to signal to other Couch instances that they shouldn't repopulate the new fresh and clean database, and instead take it as a new database entirely? Or, in fact, any other solution at all?

A: Yes, if you have bidirectional replication then the "other side" will replicate all the deleted docs back to the new DB.  The only two options I can think of are to have a new database (with a new name, which is what the docs you linked to probably meant), or to use filtered replication so the client doesn't push up deleted docs (or doesn't push up deleted docs older than a certain point).
The latter of these options is significantly more complex than the former.


text:
Q: How to insert Html data in lotus notes document (email,task,etc.) body using C++ api? I am using Lotus notes 8.5 c++ api to create a new notes document like email,calendars, tasks,etc. i am not able to put html data in any notes document body.When i insert html data, it shows as Html code. however i can put plain text easily using following api.
LnDocument Mydocument;
Lnstring strval= "xyz";
Lntext Txt;
Txt.Setvalue(strval);
Mydocument.Createitem("Body", Txt, LNITEMFLAGS_SUMMARY, LNITEMOPTION_DELETE_APPEND);

How can i Put html Data in Body field?

A: This tutorial has some good instructions on how to create a HTML email
It is aimed at Lotusscript but shouldn't be too hard to convert to the C++ api.  The gist is that you'll have to create a NotesMimeEntity and set its text to the HTML you've generated.


text:
Q: How to Output a List of Summaries From Different Grouping Variables When Using Dplyr::Group_by and Dplyr::Summarise library(tidyverse)

Using a simple example from the mtcars dataset, I can group by cyl and get basic counts with this...
mtcars%>%group_by(cyl)%>%summarise(Count=n())

And I can group by both cyl and am...
mtcars%>%group_by(cyl,am)%>%summarise(Count=n())

I can then create a function that will allow me to input multiple grouping variables.
Fun<-function(dat,...){
dat%>%
group_by_at(vars(...))%>%
summarise(Count=n())
}

However, rather than entering multiple grouping variables, I would like to output a list of two summaries, one for counts with cyl as the grouping variable, and one for cyl and am as the grouping variables.
I feel like something similar to the following should work, but I can't seem to figure it out. I'm hoping for an rlang or purrr solution. Help would be appreciated.
Groups<-list("cyl",c("cyl","am"))

mtcars%>%group_by(!!Groups)%>%summarise(Count=n())

A: Here's a working, tidyeval-compliant method.
library(tidyverse)
library(rlang)

Groups <- list("cyl" ,c("cyl","am"))

Groups %>%
  map(function(group) {
    syms <- syms(group)
    mtcars %>%
      group_by(!!!syms) %>%
      summarise(Count = n())
  })

#> [[1]]
#> # A tibble: 3 x 2
#>     cyl Count
#>   <dbl> <int>
#> 1     4    11
#> 2     6     7
#> 3     8    14
#>
#> [[2]]
#> # A tibble: 6 x 3
#> # Groups:   cyl [?]
#>     cyl    am Count
#>   <dbl> <dbl> <int>
#> 1     4     0     3
#> 2     4     1     8
#> 3     6     0     4
#> 4     6     1     3
#> 5     8     0    12
#> 6     8     1     2


text:
Q: I didn't get this joke from Dr. Octopus in Spider Man 2. Is there anything subtle in the language that I'm not picking up? Dr. Octopus:

Ladies and gentlemen. My wife Rosie and I would like to welcome you this afternoon. But first before we start, has anybody lost a large roll of 20 dollar bills in a rubber band? Because we found the rubber band.

Are there any linguistic subtleties going on?
I'd love to hear back from you people.

A: If they had found only the rubber band, how would they know it was once around a roll of money? Evidently, they found the money with the rubber band, but decided to keep the money.


text:
Q: Characterisation of local affine diffeomorphisms I've got a question about local affine diffeomorphisms between affine manifolds.
There ist a good characterisation about affine diffeomorphisms of connected affine Mannifolds:
Let $f,g\colon (M,\nabla^M) \rightarrow (N,\nabla^N)$ be affine diffeomorphisms between connected affine manifolds, $p\in M$ a Point with $f(p) = g(p)$ and $df_p = dg_p$. Then $f = g$.
Does this characterisation also hold for local affine diffeomorphisms?
The main Point in the proof is that given an affine diffeomorphism $f\colon M\rightarrow N$, $f\circ exp_p = exp_{f(p)}\circ df_p$ holds for every $p\in M$. I see no reasons why this shouldn't hold for local affine diffeomorphisms.
Any help would be appreciated as I don't see the point.

A: I don't believe one needs any "diffeomorphism" assumption to prove a result like this. In particular the following seems to be true:
Theorem. Let $M, N$ be affine manifolds with $M$ connected, and let $f$ and $g$ be (smooth) affine maps $M \to N$. Suppose there exists $p \in M$ with $f(p) = g(p)$ and $df_p = dg_p$. Then $f = g$.
For this we'll prove something like your formula:
Lemma. Let $f : M \to N$ be affine. Then given $p \in M$, there exists a neighborhood $U$ of $0 \in T_pM$ such that for $v \in U$
$$
   f(\exp_p(v)) = \exp_{f(p)}(df_p(v)).
$$
Proof of Lemma. Let $V$ be a neighborhood of $0 \in T_{f(p)}N$ such that $\exp_{f(p)}$ is a diffeomorphism on $V$ and so that $V$ is star-convex with respect to the origin. Let $U$ be a star-convex neighborhood of $0 \in T_pM$ contained in $df_p^{-1}(V)$.
Given $v \in U$, $f$ must map the the geodesic $t \mapsto \exp_p(tv)$ to a geodesic (since $f$ is affine) and thus this geodesic must be $\exp_{f(p)}(df_p(tv))$, q.e.d.
Proof of Theorem. Let $S \subseteq M$ be the set of $q$ with $f(q) = g(q)$ and $df_q = dg_q$. Obviously $S$ is closed since $f$ and $g$ are smooth. We claim $S$ is also open; since it is nonempty and $M$ is connected, this would complete the proof.
Fix $q \in S$ and a neighborhood $U$ of $0 \in T_qM$ as in the lemma that works for both $f$ and $g$. Then for $v \in U$,
$$
   f(\exp_q(v)) = \exp_{f(q)}(df_q(v)) = \exp_{g(q)}(dg_q(v)) = g(\exp_q(v)),
$$
the middle equality following since $q \in S$; so $f = g$ on $\exp_q(U)$, and hence $\exp_q(U) \subseteq S$, q.e.d.


text:
Q: Compute $\int_{\gamma} y dx$ where $\gamma$ is the curve shown. I'm at a loss on what to do with the following question from a previous differential topology exam:
Let $\gamma \rightarrow \mathbb{R}^{2}$ be the curve shown below with self-intersecting points $(0,0), (2,1)$ and $(4,2)$:

I'd imagine since this is in the context of differential topology, we are supposed to use Stoke's theorem, where we get:
$\int_{\gamma} ydx = \int_{R} dydx$
where $R$ is the region bounded by $\gamma$, but I am honestly having trouble doing the calculus on the right hand side.

A: Note that for a simply closed curve $\gamma=\partial R$ going around $R$ counterclockwise we have $$\int_\gamma y\>dx=-\int_R 1\> {\rm d}(x,y)=-{\rm area}(R)\ .$$ Split your $\gamma$ into a closed lower part $\gamma_1$ and a closed upper part $\gamma_2$ by choosing $(0,0)$ as dividing point. Then
$$\int_\gamma y\>dx=\int_{\gamma_1} y\>dx+\int_{\gamma_2} y\>dx$$
is the area of the topmost part (above the $\infty$) of your figure minus the area of the lowest part (below the $\infty$), which is $=0$ if the figure is symmetric with respect to the line $(0,0)\vee(4,2)$.


text:
Q: How to use Ajax to Validate email or username as unique in Laravel 5.2? This is my UserController where I check if the username exist in the database and return a json message accordingly. What i want is an ajax request to post to this controller and to return a message to a HTML form if the username exist or doesn't exist in the database.

 public function postSignUp(Request $request)
{

    $this->validate($request, [
        'first_name' => 'required|min:3|max:120',
        'last_name' => 'required|min:3|max:120',
        'username' => 'required|unique:users|min:6',
        'email' => 'required|email|unique:users',
        'password' => 'required|min:8',
        'gender' => 'required',
        'birthday' => 'required',
        'country' => 'required',
        'state' => 'required'
    ]);

    $username = $request->input('username', '');
    $user = User::where('username', $username)->first();

    // if the user was found, this will be true;
    // if the user wasn't found, $user will be null and this will be false
    if ($user) {
        return json_encode(false);
    } else {
        return json_encode(true);
    }

I was hoping to get a little help with this issue since I been searching the web for hours trying to figure this out.
I am currently building a logging web app with laravel 5.2 but I can't figure out how to use Ajax to do my front end validation. I found the following code online and did a little modifications to meet my needs but nothing seems to be working.
I am trying to verify the username field as a unique field. In other words, if the username exist in the database i want to let my users know before they submit the form. Can anyone help?

<script>
    $(function () {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        //register is the form id.
        $("#register").validate({
            rules: {
              /*username is the name of the field
              that I want to validate using ajax*/
                username: {
                    required: true,
                    rangelength: [6, 15],
                    remote: {
                        url: "{{ url('App/Http/Controllers/UserController/postSignUp') }}",
                        type: "post"
                    }
                }
            },
            errorClass: "has-danger",
            validClass: "has-success",
            //success: "valid",

            highlight: function (element, errorClass) {
                $(element).fadeOut(function () {
                    $(element).fadeIn();
                });
                $(element).closest(".form-group").addClass(errorClass);
            },
            unhighlight: function (element, errorClass) {
                $(element).closest(".form-group").removeClass(errorClass);
            },
            errorPlacement: function (error, element) {
                error.insertAfter(element);
            }
        });
    });
</script>


text:
Q: AWS Credentials File Multiple Roles Same Profile If I want to have in my .aws/credentials file access keys for one AWS profile / account ID but want individual credentials listed for each role-name associated with that account ID and profile combo (arn:aws:iam::account-id:role/role-name - i.e want to be able to refer to the credentials for profile X, account Y for roles A, B and C and have the AWS credentials SDK be able to read it properly or commands like terraform init use the credentials properly). Is that possible?
I did some digging and wasn't able to see much. One solution is that if I wanted to reference Profile X, account Y and role A then I'd update my credentials to that corresponding ARN and then edit the .aws/credentials file and only be able to have on type of role for profile X and account Y at a time. I wasn't able to find something where I could have multiple role credentials for one profile X/account Y combo. For example the below doesn't seem possible:
#.aws/credentials file
[X-A]
aws_access_key_id = keyid_roleA
aws_secret_access_key = key_roleA
aws_session_token = token_roleA

[X-B]
aws_access_key_id = keyid_roleB
aws_secret_access_key = key_roleB
aws_session_token = token_roleB

[X-C]
aws_access_key_id = keyid_roleC
aws_secret_access_key = key_roleC
aws_session_token = token_roleC


text:
Q: I have list with multiple strings and I want to search some patterns in substring of the string and print the next, previous line of pattern in python From the list first I have to check what all are the values contains start and end keyword. If the value contains start/end then it should print inbetween lines of these values.
Input:
list1 = ['started','1','asd', 'ending of the word/n','aaaa','startin','answer','fruit','123','ending']

Expected output:
['1',asd]
['answer','fruit','123']

    for x in list1:
        if start in x:
           substring1 = x
        if end in x:
           substring2 = x

After this I need to print the values between substring1 and substring2 variable. I don't know how to proceed further. I am also new to python. Can someone help me to solve this. Thanks in advance.

A: list1 = ['started', '1', 'asd', 'ending of the word/n', 'aaaa', 'startin', 'answer', 'fruit', '123', 'ending']
index_start = 0
for i in range(len(list1)):
    if 'start' in list1[i]:
        index_start = i
    if 'end' in list1[i]:
        print(list1[index_start+1:i])

Working with i in range() in your for loop is more appropriate so that you can get the indexes of where the patterns start/end. Then simply store the start_index when you find 'start' and print everything in between when you find the 'end' substring.
Of course you'd want to add some conditions to make sure there is a start before an end.
Output:
['1', 'asd']
['answer', 'fruit', '123']


text:
Q: Install Zeppelin in yarn cluster I am trying to install apache zeppelin in yarn cluster.
After installing and visiting http://localhost:8080, zeppelin is launching but it's asking me to log in. How I register or login?
It works well in my mac system, and it does not prompt a login. But in the cluster it prompts login.
Any help is appreciated.
Thanks in advance


text:
Q: Getting all URLs using anemone gem (very large site) The site I want to index is fairly big, 1.x million pages. I really just want a json file of all the URLs so I can run some operations on them (sorting, grouping, etc).
The basic anemome loop worked well:
require 'anemone'

Anemone.crawl("http://www.example.com/") do |anemone|
  anemone.on_every_page do |page|
      puts page.url
  end
end

But (because of the site size?) the terminal froze after a while. Therefore, I installed MongoDB and used the following
require 'rubygems'
require 'anemone'
require 'mongo'
require 'json'

$stdout = File.new('sitemap.json','w')

Anemone.crawl("http://www.mybigexamplesite.com/") do |anemone|
  anemone.storage = Anemone::Storage.MongoDB
  anemone.on_every_page do |page|
      puts page.url
  end
end

It's running now, but I'll be very surprised if there's output in the json file when I get back in the morning - I've never used MongoDB before and the part of the anemone docs about using storage weren't clear (to me at least). Can anyone who's done this before give me some tips?

A: If anyone out there needs <= 100,000 URLs, the Ruby Gem Spidr is a great way to go.

A: This is probably not the answer you wanted to see but I highly advice that you don't use Anemone and perhaps Ruby for that matter for crawling a million pages.
Anemone is not a maintained library and fails on many edge cases.
Ruby is not the fastest language and uses a global interpreter lock which means that you can't have true threading capabilities. I think your crawling will probably be too slow. For more information about threading, I suggest you can check out the following links.
http://ablogaboutcode.com/2012/02/06/the-ruby-global-interpreter-lock/
Does ruby have real multithreading?
You can try using anemone with Rubinius or JRuby which are much faster with but I'm not sure the extent of compatibility.
I had some mild success going from Anemone to Nutch but your mileage may vary.


text:
Q: Open file - security warning when running a .bat file in vba excel I am having an issue finding/understanding how to solve the following issue when running a .bat file in VBA in Excel. I am getting an Open File - Security Warning prompt when I try and execute it.
The issue is i don't have administrative privileges, so I can't set .bat files as being ignored from this prompt, and this .bat file is one that I created myself so I don't understand why my computer is flagging it as potentially harmful.
If anyone could explain a workaround, and why such an issue arises despite it being a custom generated .bat file, I would greatly appreciate it. By a workaround I mean modifying the code I currently have to deal with this problem, without having to go through Administrators.
Below is the snippet of code pertaining to the problem, thanks:
sub test()
'some stuff

    Open MY_FILENAME For Output As #FileNumber
    Print #FileNumber, FileContents
    Print #FileNumber, "exit"
    Close #FileNumber

    'run batch file
    Dim wsh As Object
    Set wsh = VBA.CreateObject("WScript.Shell")
    Dim waitOnReturn As Boolean: waitOnReturn = True
    Dim windowStyle As Integer: windowStyle = 1
    Dim rtn As Integer
    rtn = wsh.Run(Chr(34) & MY_FILENAME & Chr(34), windowStyle, waitOnReturn)
end sub

I should add that if run the shell like so I have no issues:
rtn = Shell(MY_FILENAME, vbNormalFocus)

Except that the code will continue running despite the shell not closing and completing its execution. I need the shell to halt until it has executed it's task.


text:
Q: Am I implementing the monkey test correctly? I have written the following code to perform a three-letter monkey test on the notorious Randu number generator.
from itertools import product
from scipy.stats import chisquare
from numpy.random import randint

multiple = 10
number_of_random_numbers = 17576*multiple #There are 17576 possible three letter words. Therefore it's easy use a sequence length of
                                        # 17576 times some natural number.

expectation = multiple     #Given that the null hypothesis is true
                           # (equivalent to saying: given that the random sequence is iid and uniform) we expect
                           # that each word occurs once every 17576 times. Therefore the expected occurrence of each
                           # combinations is equal to the multiple. If we have a random sequence of length 2*17576 we
                           # expect each word to occur twice.

def seedlcg(init_Val):
    global rand
    rand = init_Val

def lcg_randu():
    a = 65539
    c = 0
    m = 2**31
    global rand
    rand = (a*rand + c) % m
    return rand/m

seedlcg(30000)

random_sequence = []
for i in range(1,number_of_random_numbers):
    random_sequence.append(lcg_randu())
random_sequence = [math.ceil(26*number) for number in random_sequence]
#  def collect_words():
#       This function collects the observed words from the sequence of random numbers. It
#       returns a list that contains the observed words.

def collect_words(random_sequence):
    list_of_words = []
    for i in range(0,len(random_sequence)):
        list_of_words.append((random_sequence[i-2],random_sequence[i-1], random_sequence[i]))
    return list_of_words

# def initiate_list_of_possible_words():
#       This function initiates a list of all possible words and returns that list.

def initiate_list_of_possible_words():
    alphabet = [x for x in range(1,27)]
    list_of_possible_words = [letter for letter in product(alphabet, repeat=3)]
    return list_of_possible_words

# def count_words(observed_words):
#       This function checks how many times each possible word combination occurred. It returns
#       a list with the number of occurrences for each word.

def count_words(observed_words):
    list_of_possible_words = initiate_list_of_possible_words()
    word_count = []
    for word in list_of_possible_words:
        word_count.append(observed_words.count(word))
    return word_count

word_combinations = collect_words(random_sequence) #Collect the observed words from the sequence
word_count = count_words(word_combinations) #Collect how many times each possible word has occurred.

print(chisquare(word_count, multiple)) #Compute and print the Chisquare statistic and the corresponding p-value.

When I run this code I get the following result:
Power_divergenceResult(statistic=117915.47220000002, pvalue=0.0)

This code is supposed to count the occurrences of every possible three letter word in the generated random sequence and then perform a chi-square test. I understand that this code can probably be made to run ten times faster. However, I don't really believe that this chi-square test statistic has a p value of zero (this would mean that the monkey test would reject the the idd-ness of the Randu generator).
Question: Have I made a mistake in my code? Is there something I don't comprehend that results in this extreme p-value?


text:
Q: How do you handle timezone difference calculation in PHP? I'm being told that this below method of calculating the user's local time is sometimes not working.  What's the best way to do this in PHP?  What do you do?
public function getTimeOffset ($time) {
    $this->_cacheTimeOffset();
    if ($this->timeOffsetExecuted) {
        $d = date("O");
        $neg = 1;

        if (substr($d, 0, 1) == "-") {
            $neg = -1;
            $d = substr($d, 1);
        }

        $h = substr($d, 0, 2)*3600;
        $m = substr($d, 2)*60;

        return $time + ($neg * ($h + $m) * -1) + (($this->timeOffset + $this->getDstInUse()) * 3600);
    }
    return $time;
}

A: Use the DateTime extension, such as DateTime::getOffset,
or DateTimeZone::getOffset
Some countries might have perform several timezone update,
this method DateTimeZone::getTransitions reveal the transition history

A: Just answered a very similar question over here. I recommend you check that one out; I explained the two preferred ways of doing timezone offset calculation (using simple math, and then the datetimezone and datetime classes) pretty thoroughly.

The first way would be the easiest
  (and most logical) way, and that is to
  store their offset (if you already
  have it, that is) and multiply that by
  3600 (1 hour in seconds), and then add
  that value to the current unix timestamp to get their final time of
  running.
Another way to do it is to use the
  DateTime and DateTimeZone classes.
  How these two classes work, as shown
  here, is that you create two
  DateTimeZone objects, one with your
  timezone and one with theirs; create
  two DateTime objects with the first
  parameters being "now" and the
  second being the reference to the
  DateTimeZone objects above
  (respectively); and then call the
  getOffset method on your timezone
  object passing their timezone object
  as the first parameter, ultimately
  getting you the offset in seconds that
  can be added to the current unix
  timestamp to get the time that their
  job needs to run.

A: date('Z');

returns the UTC offset in seconds.

A: A quick solution:
<?php echo date('g:i a', strtotime("now + 10 hours 30 minutes")); ?>


text:
Q: WMS getfeatureinfo() giving incorrect result I am using openlayers and Geoserver. I have created a base layer using OSM and then added wms layer topp:states. I want to show a world map and on that show US states. I have added onclick functionality to get feature info. However, when I click at any states, it gives incorrect state name or no result. This further worsens when I zoom in/zoom out or change the scale.Here is my code:
CSS:
#map {

            position: relative;
            height:1000px;
            width:1400px;

            float:left;
            margin:0px ;
        }

Script:
 var bounds = new OpenLayers.Bounds(
           -180,-90,0,90
        );

        format = 'image/png';

        var options = {
             controls: [],
            maxExtent: bounds,
            maxResolution: 0.22563114453125,
            projection: "EPSG:4326",
            units: 'degrees',
            displayProjection: new OpenLayers.Projection("EPSG:4326")

        };
        map = new OpenLayers.Map('map', options);
        layer = new OpenLayers.Layer.OSM("Base OpenStreet Map");
     states = new OpenLayers.Layer.WMS(
            "NA states", "http://localhost:8080/geoserver/wms",
            {
                layers: 'topp:states', styles: '', transparent: true,  format: 'image/png'
            },
            { isBaseLayer: false, singleTile: false,displayOutsideMaxExtent: true, ratio: 1,yx : {'EPSG:4326' : true} }
        );
       map.addLayers([layer,states]);

Code with call to getfeatureInfo:
       map.events.register('click', map, function (e) {
                            document.getElementById('nodelist').innerHTML =   "Loading... please wait...";
                            OpenLayers.Request.GET({url:"http://localhost:8080/geoserver/wms",params:{
                                REQUEST: "GetFeatureInfo",
                                EXCEPTIONS: "application/vnd.ogc.se_xml",
                                BBOX: bounds.toBBOX(),
                                 SERVICE: "WMS",
                                INFO_FORMAT: 'text/html',
                                QUERY_LAYERS: [ map.layers[1].params.LAYERS],
                                FEATURE_COUNT: 50,
                                Layers: [map.layers[1].params.LAYERS],
                                 WIDTH: map.size.w,
                                HEIGHT: map.size.h,
                                x: Math.floor(e.xy.x),
                                 y: Math.floor(e.xy.y),

                               }, success:setHTML});
                            OpenLayers.Event.stop(e);
                       });

It may have to do with bounds or extents,but that's just my guess.


text:
Q: Seeking advice on how to structure the SQL Server 2008 DB table with large amount of data? I am planning a web application (programmed using ASP.NET) that manages the database of logged events. The database will be managed in an SQL Server 2008. Each event may come from a set of, let's call them, "units." A user will be able to add and remove these "units" via the ASP.NET interface.
Each of the "units" can potentially log up to a million entries, or maybe even more. (The cut off will be administered via a date. For instance:
DELETE FROM [tbl] WHERE [date] < '01-01-2011'

The question I have is what is the best way to structure such database:

*

*By placing all entries for all "units" in a single table like this:
CREATE TABLE tblLogCommon (id INT PRIMARY INDEX,
                           idUnit INT,
                           dtIn DATETIME2, dtOut DATETIME2, etc INT)

*Or, by separating tables for each "unit":
CREATE TABLE tblLogUnit_1 (id INT PRIMARY INDEX, dtIn DATETIME2, dtOut DATETIME2, etc INT)
CREATE TABLE tblLogUnit_2 (id INT PRIMARY INDEX, dtIn DATETIME2, dtOut DATETIME2, etc INT)
CREATE TABLE tblLogUnit_3 (id INT PRIMARY INDEX, dtIn DATETIME2, dtOut DATETIME2, etc INT)
--and so on
CREATE TABLE tblLogUnit_N (id INT PRIMARY INDEX, dtIn DATETIME2, dtOut DATETIME2, etc INT)

Approach #1 seems simpler from a standpoint of referencing entries because with approach #2 I'll have to deal with variable N number of tables (as I said users will be allowed to add and remove "units.)
But approach #1 may render access to those log entries later very inefficient. I will have to generate reports from those logs via the ASP.NET interface.
So I'd like to hear your take on this before I begin coding?
EDIT: I didn't realize that the number of columns in a table makes a difference. My bad! The actual number of columns in a table is 16.

A: I would go with approach 1, as the table does not seem very large(width wise) and yuo could apply indexes to improve searching/selecting.
Further to this, you could also look at partitioned tables and indexes.
Creating Partitioned Tables and Indexes

A: Splitting in separate tables is going to yield better insert and search speed.
With one table the difference is an index on idUnit.  With that index search speed is going to be nearly as fast as separate tables (and you can search across idUnits is a single query).   Where one table is going to take a hit is insert but that is a small hit.

A: A lot depends on how you intend to use this data. If you split the data into multiple tables, will you be querying over multiple tables, or will all your queries be within the defined date range. How often will data be inserted and updated.
In other words, there's no correct answer!
Also, can you afford a license for SQL enterprise in order to use partitioned tables?

A: I did some tests on the actual data with SQL Server 2008 Express, using local computer connection, no network latency. The computer this was tested on: Desktop, Windows 7 Ultimate, 64-bit, CPU: i7, @2.8GHZ, 4 cores; RAM: 8GB; HDD (OS): 1TB, 260GB free.
First all records were located in a "SINGLE" table (approach #1). All records were generated with random data. A complex SELECT statement processing each particular "unitID" was tried two times (one immediately after another), with CPU load: 12% to 16%, RAM load: 53% - 62%. Here's the outcome:
UnitID   NumRecords   Complex_SELECT_Timing
1        486,810      1m:26s / 1m:13s
3        1,538,800    1m:13s / 0m:51s
4        497,860      0m:30s / 0m:24s
5        497,860      1m:20s / 0m:50s

Then the same records were separated into four tables with identical structure (approach #2). I then ran the same SELECT statement two times as before, on the same PC, with identical CPU and RAM loads. Next are the results:
Table   NumRecords   Complex_SELECT_Timing
t1       486,810      0m:19s / 0m:12s
t3       1,538,800    0m:42s / 0m:38s
t4       497,860      0m:03s / 0m:01s
t5       497,860      0m:15s / 0m:12s

I thought to share this with whoever is interested. This pretty much gives your the answer...
Thanks everyone who contributed!


text:
Q: Running Python requests consecutively returns old website data I'm trying to determine when a website updates. I've done this by creating two variables and requesting the same site data in each. Then comparing them in a while loop, updating one variable in each iteration of the loop (see code below). The website HTML actually changes every minute, as the time changes on the site. So you would expect the loop to end every minute.
Unfortunately, the site seems to send the same original data for each additional request and therefore the while loop does not exit. In order to reproduce the problem, run the code below a couple of times and then inspect the time in the HTML (origsite[4050:4114]) to see if it's the current time or the time from when you first ran the block of code.
import time
import random
import sys
import requests

site = requests.get("http://www.supremenewyork.com/shop/all/").text
origsite = requests.get("http://www.supremenewyork.com/shop/all/").text

n = 1

while (origsite == site):
    x = round(random.uniform(0.8,1.2),3)
    time.sleep(x)
    origsite = requests.get("http://www.supremenewyork.com/shop/all/").text
    print(n)
    n = n + 1
print("site changed")

Is this a known issue with requests? Or is the website sending old information on purpose? I have tried using a VPN to change my IP and it still returns old data. Is there another way to test if a site has changed? Below is an example of it using old data. origsite is storing data from 5min before site data is run.
origsite[4050:4114]
Out[94]: b'ime data-timezone-offset="3600">04/06/2018 03:11am <span '

site[4050:4114]
Out[95]: b'04/06/2018 03:16am LDN</'

A: Unfortunately there didn't seem to be a Selenium/requests solution. I solved the problem by using Browser from splinter. The adjusted code is below:
from splinter import Browser
browser = Browser('firefox')
browser.visit(mainUrl + cat)
origsite = browser.html
site = browser.html

n = 1

while (origsite == site):
    x = round(random.uniform(0.8,1.2),3)
    time.sleep(x)
    origsite = browser.html
    print(n)
    n = n + 1
print("site changed")


text:
Q: Join two tables in Oracle concatenating results by id I want to join two tables in Oracle and list the results concatenated if they have the same parent id in this way:
Table All
|id    | other fields|service_id|
|------|-------------|----------|
| 827  |xxxxxxxx     |null      |
| 828  |xxxxxxxx     |327       |
| 829  |xxxxxxxx     |328       |
| 860  |xxxxxxxx     |null      |
| 861  |xxxxxxxx     |326       |

Table Services
| id    | parent_id |
| ----  | -------|
|  326  | 860    |
|  327  | 827    |
|  328  | 827    |

I want a query that returns this
|id    | sub_id  |
|------|---------|
| 827  | 828,829 |
| 828  | null    |
| 829  | null    |
| 860  | 861     |
| 861  | null    |

Thanks a lot!

A: By joining the all table to service and then back to all in an alias you can get the ID and sub id's in a list that then just need to be combined from multiple rows into 1 column per ID.
This should get you the "Raw data" that then needs to be aggregrated...
TESTED: Rextester working example
NOTE: Since you have different "LEVELS" of depth for your sub_ID i'm not really sure what you want so 860 and 123 isn't included because it's a completely different field than the source of 827
SELECT A.ID as ID, A2.ID as Sub_ID
FROM ALL A
LEFT JOIN SERVICES S
 on S.Pareint_ID = A.ID
LEFT JOIN All A2
 on A2.Service_ID = S.ID

Now... if we assume that you have a version of oracle which supports ListAgg
SELECT A.ID as ID, ListAgg(A2.ID,',') within group (Order by A2.ID)  as Sub_ID
FROM ALL A
LEFT JOIN SERVICES S
 on S.Parent_ID = A.ID
LEFT JOIN All A2
 on A2.Service_ID = S.ID
GROUP BY A.ID

Giving Us:
+----+-----+---------+
|    | ID  | SUB_ID  |
+----+-----+---------+
|  1 | 827 | 828,829 |  -- These are all.id's...
|  2 | 828 | NULL    |
|  3 | 829 | NULL    |
|  4 | 860 | NULL    |  --> Now why is 123 present as it's a service.id
|  5 | 861 | NULL    |
+----+-----+---------+

**Note all is a reserved word and either needs to be escaped or if your table name really isn't all; adjust accordingly.
LISTAGG Docs


text:
Q: Xcode 13 archive failed: ipatool failed with an exception: #When using latest React-native version, an error occurs when attempting to archive and export a release build through xcodebuild.
ipatool failed with an exception: #<CmdSpec::NonZeroExitException: $ Xcode.app/Contents/Developer/usr/bin/python3 /Xcode.app/Contents/Developer/usr/bin/bitcode-build-tool -v -t /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin --sdk /Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS15.2.sdk -o /var/folders/v1/wd4zzzf10pzbbgtwf94wnb4h0000gn/T/ipatool20221003-10540-akdneb/thinned-out/arm64/Payload/BookingKoala\ For\ Providers.app/Frameworks/hermes.framework/hermes --generate-dsym /var/folders/v1/wd4zzzf10pzbbgtwf94wnb4h0000gn/T/ipatool20221003-10540-akdneb/thinned-out/arm64/Payload/BookingKoala\ For\ Providers.app/Frameworks/hermes.framework/hermes.dSYM --strip-swift-symbols /var/folders/v1/wd4zzzf10pzbbgtwf94wnb4h0000gn/T/ipatool20221003-10540-akdneb/thinned-in/arm64/Payload/BookingKoala\ For\ Providers.app/Frameworks/hermes.framework/hermes Status: pid 10975 exit 1 Stdout: SDK path: /Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS15.2.sdk
React-native :: 0.70.1
npx react-native info
System:
OS: macOS 11.3
CPU: (4) x64 Intel(R) Core(TM) i5-4278U CPU @ 2.60GHz
Memory: 384.45 MB / 8.00 GB
Shell: 5.8 - /bin/zsh
Binaries:
Node: 16.14.2 - /usr/local/bin/node
Yarn: 1.22.19 - /usr/local/bin/yarn
npm: 8.19.1 - /usr/local/bin/npm
Watchman: Not Found
Managers:
CocoaPods: 1.11.3 - /usr/local/bin/pod
SDKs:
iOS SDK:
Platforms: DriverKit 21.2, iOS 15.2, macOS 12.1, tvOS 15.2, watchOS 8.3
Android SDK: Not Found
IDEs:
Android Studio: 4.0 AI-193.6911.18.40.6626763
Xcode: 13.2.1/13C100 - /usr/bin/xcodebuild
Languages:
Java: Not Found
npmPackages:
@react-native-community/cli: Not Found
react: ^18.2.0 => 18.2.0
react-native: ^0.70.1 => 0.70.1
react-native-macos: Not Found
npmGlobalPackages:
react-native: Not Found
Updated react-native version
Ensure you have XCode <= 13.2.1
Attempt to archive and export a release build using xcodebuild


text:
Q: Cancel a user edit from property set in the ViewModel? quite a newbie question, i'm sure, but i wasn't able to find an answer...
I have a control (in this case- a combo box) which is bound to a ViewModel property:
<ComboBox
      x:Name="methodTypeCmb"
      Grid.Row="0" Grid.Column="2"
      ItemsSource="{Binding Path=AllNames, Mode=OneTime}"
      SelectedItem="{Binding Path=Name, ValidatesOnDataErrors=True, Mode=TwoWay}"
      Validation.ErrorTemplate="{x:Null}"
      />

In my ViewModel, when this property changes, I want to ask the user to confirm the change.
If the user clicks 'no', I want to cancel the change.
However, I must be doing something wrong, because my view doesn't revert back to the previous value when the change is cancelled.
The ViewModel's property:
public string Name
{
    get { return m_model.Name; }
    set
    {
        if (MessageBox.Show("Are you absolutely sure?","Change ",MessageBoxButton.YesNo) == MessageBoxResult.Yes)
        {
            // change name
        }
        base.OnPropertyChanged("Name");
    }
}

A: Because you are cancelling within the scope of the text changing event, wpf ignores the property changed event.  You must call it from the dispatcher
        Dispatcher.CurrentDispatcher.BeginInvoke((ThreadStart)delegate
        {
            OnPropertyChanged("Name");
        });

You should leave your existing "OnPropertyChanged("Name");" at the bottom of the function just add the above line to the block where you are cancelling
EDIT:  The following code works I have tested it
        public string Newtext
        {
            get
            {
                return this._newtext;
            }
            set
            {
                if (MessageBox.Show("Apply?", "", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    this._newtext = value;
                    this.OnPropertyChanged("Newtext"); //Ignored
                }
                else
                {
                    Dispatcher.CurrentDispatcher.Invoke((ThreadStart)delegate
                    {
                        OnPropertyChanged("Newtext");
                    });
                }
            }
        }


text:
Q: how to select a name column while creating a dimension under dimension list in SSAS? I am trying to create a Fact-Dimension based on the example given in the AdventureWorks-SSAS documentation (the web-link for the document was given below). As I followed through the steps given below, I couldn't find the name-column list in step 7; it can be understood from the screenshot that I attached to this question.

*

*In Solution Explorer, right-click Dimensions, and then click New Dimension.

*On the Welcome to the Dimension Wizard page, click Next.

*On the Select Creation Method page, verify that the Use an existing table option is selected, and then click Next.

*On the Specify Source Information page, verify that the Adventure Works DW 2012 data source view is selected.

*In the Main table list, select InternetSales.

*In the Key columns list, verify that SalesOrderNumber and SalesOrderLineNumber are listed.

*In the Name column list, select SalesOrderLineNumber.

*Click Next.
Would anyone please help me understand why I couldn't go further from step 7.
Thank you for considering to support my attempts.
https://learn.microsoft.com/en-us/analysis-services/multidimensional-tutorial/lesson-5-2-defining-a-fact-relationship?view=asallproducts-allversions

A: There are currently some issues in visual studio :
You need to click on 'Add key column' and then all values would be posted down.
And you can then select the column values


text:
Q: I am creating a food orderin app. When I switch to dark mode, the app is crashing I have posted the entire code in MainFragment.kt.Please look into it.

         lateinit var recl_view:RecyclerView
    lateinit var progress_bar:RelativeLayout
     var list =ArrayList<DataList>()
    lateinit var no_net:ImageView
    lateinit var refresh:SwipeRefreshLayout
    lateinit var search_bar:EditText
    lateinit var appbar:AppBarLayout
    lateinit var nav_view:NavigationView
    var asc = true
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_main, container, false)
        setHasOptionsMenu(true)
        search_bar = view.findViewById(R.id.main_search_bar)
        refresh = view.findViewById(R.id.main_frg_swipe_refresh)
        search_bar.setHint("Search Restaurants")
        no_net = view.findViewById(R.id.main_frg_no_net)
        appbar = view.findViewById(R.id.main_frg_appbar)
        progress_bar = view.findViewById(R.id.frg_main_prgs)
        nav_view = requireActivity().findViewById(R.id.main_navigation_view) as NavigationView
        nav_view.setCheckedItem(R.id.home_select)
        if(Connection().checkConnectivity(activity as Context)) {
            no_net.visibility = View.GONE
            appbar.visibility = View.VISIBLE
            val q = Volley.newRequestQueue(activity as Context)
            val url = "http://13.235.250.119/v2/restaurants/fetch_result/"
            try{
                progress_bar.visibility = View.VISIBLE
                val jsonreq = object : JsonObjectRequest(
                    Request.Method.GET,url,null,
                    Response.Listener {
                        if(it.getJSONObject("data").getBoolean("success")){
                            list = arrayListOf<DataList>()
                            val data = it.getJSONObject("data").getJSONArray("data")
                            for(i in 0 until data.length()){
                                list.add(
                                    DataList(
                                        data.getJSONObject(i).getString("id"),
                                        data.getJSONObject(i).getString("name"),
                                        data.getJSONObject(i).getString("rating"),
                                        data.getJSONObject(i).getString("cost_for_one"),
                                        data.getJSONObject(i).getString("image_url")
                                    )
                                )
                            }
                            recl_view = view.findViewById(R.id.frg_main_rec_view)
                            recl_view.layoutManager = LinearLayoutManager(activity)
                            recl_view.adapter = MainAdapter(activity as Context,list)
                            progress_bar.visibility = View.GONE
                        }
                    },
                    Response.ErrorListener {
                        appbar.visibility = View.GONE
                        progress_bar.visibility = View.GONE
                        Toast.makeText(activity as Context,"Please Try Again Later.", Toast.LENGTH_SHORT).show()
                    }){
                    override fun getHeaders(): MutableMap<String, String> {
                        val headers = HashMap<String, String>()
                        headers["Content-type"] = "application/json"
                        headers["token"] = "c3acf1e14c21f9"
                        return headers
                    }
                }
                q.add(jsonreq)
            }catch (e: Exception){
                appbar.visibility = View.GONE
                progress_bar.visibility = View.GONE
                Toast.makeText(activity as Context,"Please Try Again Later.", Toast.LENGTH_SHORT).show()
            }
        }
        else{
            appbar.visibility = View.GONE
            Toast.makeText(activity as Context,"Please Check your Internet Connection", Toast.LENGTH_SHORT).show()
            no_net.visibility = View.VISIBLE
        }
        search_bar.addTextChangedListener(object :TextWatcher{
            override fun afterTextChanged(p0: Editable?) {
            }
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                val listData = arrayListOf<DataList>()
                for (i in 0 until list.size) {
                    if (list[i].name.toLowerCase()
                            .contains(search_bar.text.toString().toLowerCase()) ||
                        list[i].cost_for_one.contains(search_bar.text.toString()) ||
                        list[i].rating.contains(search_bar.text.toString())
                    ) {
                        listData.add(list[i])
                    }
                }
                recl_view.adapter = MainAdapter(activity as Context, listData)
                (recl_view.adapter as MainAdapter).notifyDataSetChanged()
            }

        }
        )
        refresh.setOnRefreshListener {
            getFragmentManager()?.beginTransaction()?.detach(this)?.attach(this)?.commit()

        }
        return view

    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        if(Connection().checkConnectivity(activity as Context)) {
            MenuInflater(activity as Context).inflate(R.menu.app_bar_menu, menu)
            return super.onCreateOptionsMenu(menu, inflater)
        }

The error is shown here

Process: com.example.foodly, PID: 9860
kotlin.UninitializedPropertyAccessException: lateinit property recl_view has not been initialized
at com.example.foodly.fragments.MainFragment.getRecl_view(MainFragment.kt:32)
at com.example.foodly.fragments.MainFragment$onCreateView$1.onTextChanged(MainFragment.kt:126)
at android.widget.TextView.sendOnTextChanged(TextView.java:11785)
at android.widget.TextView.setText(TextView.java:6965)
at android.widget.TextView.setText(TextView.java:6761)
at android.widget.EditText.setText(EditText.java:145)
at android.widget.TextView.setText(TextView.java:6713)
at android.widget.TextView.onRestoreInstanceState(TextView.java:6580)
at android.view.View.dispatchRestoreInstanceState(View.java:22288)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:4805)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:4805)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:4805)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:4805)
at android.view.View.restoreHierarchyState(View.java:22266)
at androidx.fragment.app.Fragment.restoreViewState(Fragment.java:639)
at androidx.fragment.app.Fragment.restoreViewState(Fragment.java:3010)
at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:3001)

This error is shown only when we switch from dark mode to light mode or vice versa.

A: You need to move the assignment of the recl_view variable outside your network request callback and into the main body of onCreateView, e.g.:
...
nav_view = requireActivity().findViewById(R.id.main_navigation_view) as NavigationView
nav_view.setCheckedItem(R.id.home_select)

recl_view = view.findViewById(R.id.frg_main_rec_view)

if(Connection().checkConnectivity(activity as Context)) {
    no_net.visibility = View.GONE
    ...

This is because when the view is recreated (e.g. when rotated, or switch dark/light mode) the onTextChanged method of the TextWatcher attached to search_bar is called and this method accesses recl_view, but this will only have been initialised once your network request has finished.


text:
Q: Charged current vs. neutral current neutrino interactions I am doing research related to the detection potential of neutrino detectors and, in looking up the various neutrino interaction channels that exist in each detector, I have found the interactions being classified as "charged-current" and "neutral-current" interactions.  I have come across this terminology before and know it has to do with the nature of the interactions at the particle level.  I also remember the adage "there are no flavor-changing neutral currents," if that applies here.
I've found that differentiating charged-current and neutral-current interactions is most relevant in the context of so-called "scintillator" detectors, which use hydrocarbons (with approximate chemical formula C$_n$H$_{2n}$) as the primary interaction medium.  I would like some to explain to me, in the context of neutrino-matter interactions, what qualifies as a charged-current interaction and what qualifies as a neutral-current interaction.  You can use the scintillator-relevant interactions in Table 1 of this paper for specific examples.
Feel free to use Feynman diagrams in your explanation if it helps, I am familiar with them.

A: At the tree level (i.e. the simplest Feynman diagram) the both types of weak interaction result from the exchange of a weak boson. The weak bosons are the $Z^0$ (neutral) and the $W^\pm$ (charged).
Guess how we assign the terms "neutral" and "charged" to weak interactions. Right, by the exchange boson. (We don't distinguish between interaction involving the two $W$ bosons for technical reasons.)
In hadronic neutrino interaction (ones involving a nucleon) you can tell the two classes apart by noting if the neutrino continues on it's way (neutral) or if a charged lepton ($e$, $\mu$ or $\tau$) appears in it's place (charged).
This doesn't work for leptonic interaction where the neutrino has the same flavor as the other lepton because of the possible presence of the exchange diagram.

(Image from http://inspirehep.net/record/1236362/files/TwoDiagrams.png) Notice that both diagrams have the same input state and the same output state.


text:
Q: Stop and restart CountDownTimer I have a Timer which it starts from 00:00 nice, but when I want to stop it I call cdTimer.cancel() but then I'm not able to restart the Timer with the old values and it starts again. I have this method :
private void StartTimer(){
    final long EndTime   = 3600;
    cdtTimer = new CountDownTimer(EndTime*1000, 1000) {
        public void onTick(long millisUntilFinished) {
            long secondUntilFinished = (long) (millisUntilFinished/1000);
            long secondsPassed = (EndTime - secondUntilFinished);
            long minutesPassed = (long) (secondsPassed/60);
            secondsPassed = secondsPassed%60;
            tvCounterTimer.setText(String.format("%02d", minutesPassed) + ":" + String.format("%02d", secondsPassed));
        }
        public void onFinish() {
            tvCounterTimer.setText("done!");
        }
    }.start();
}

I thought I could save the values minutesPassed and secondsPassed but then I should pass them by parameter, right?

A: To cancle a timer do this
timer.cancel();
timer.purge();

To restart a timer you will have to re instantiate the object and then schedule it. i will start again.


text:
Q: Identifying REST Operation from its URL patterns? I was just wondering if we can find out the REST Operation from its URL? Like like identification that can be used to determine whether it is GET/POST/PUT/DELETE etc?

A: First of all, let me highlight that REST is architectural style and it is protocol-independent. But I haven't come across any applications doing REST over a protocol that is not HTTP(S). So, when you say REST operation, I understand it as HTTP request.

URL stands from Universal Reource Locator and it is meant for, well, locating resources in the server. Just that. URLs locate resources and are not meant to express any operation (unless you are doing RPC, but I guess that's not what you want).
On the other hand, the request method is the primary source of request semantics, as it indicates the purpose for which the client has made this request and what is expected by the client as a successful result.

Having said that, let me go back to your questions:

I was just wondering if we can find out the REST Operation from its URL?

No. The URL will (or at least should) tell you about the resource which is the target of the operation expressed by the HTTP method.

Like identification that can be used to determine whether it is GET/POST/PUT/DELETE etc?

If I understand your question correctly, as I answered above, no.
But, if you want to identify the request methods supported by a given resource, then you can use the OPTIONS method. Consider the following request as example:
OPTIONS /foo HTTP/1.1
Host: example.org

The server will respond with something similar to:
HTTP/1.1 200 OK
Allow: OPTIONS, GET, HEAD, POST

Where the Allow header contains a list of the methods supported by the target resource.


text:
Q: How to remove rows from data frame based on subset function? I would like to remove some rows from my data frame. I think that using subset it will be the easiest way to do that.
I used code below to remove some of the rows before:
data_selected <- subset(tbl_data, Name.x != "XXX" & Name.y != "YYY")

The question is how to remove the rows from my table which have the same string in two cells (same row).
I think that mtcars can be used as an example:
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2

gear and carb columns can be used. As you can see two first rows should be removed from this data because both have the same value 4 in those two columns. Please take to the account that in my data I don't have numeric values but character string.

A: Based on the information in the post, I think a comparison (!=) between the 'gear' and 'carb' columns will be enough to subset the dataset
df1 <- mtcars[1:5,]
subset(df1, gear!=carb)
#                     mpg cyl disp  hp drat    wt  qsec vs am gear carb
#Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2

This should also work for 'non-numeric' columns, but not for partial matches.
If we need to make an exception about keeping the rows that have both 'Unknown', we can use the | operator after adding another logical condition  (`(gear=='Unknown' & carb=='Unknown')) to the original condition.
Making some changes in the dataset to show the output (just as an example, I know I am changing a numeric column to character by doing this)
 df1$gear[4] <- 'Unknown'
 df1$carb[4] <- 'Unknown'
 df1$gear[5] <- 'Unknown'

subset(df1, (gear=='Unknown' & carb=='Unknown') | gear!=carb)
#                   mpg cyl disp  hp drat    wt  qsec vs am    gear    carb
#Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1       4       1
#Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0 Unknown Unknown
#Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0 Unknown       2