Q: How to set a position that changes when the window size changes I'm creating a web page for my grandpa, and I'm going to have this lil biker dude, that runs across the screen and when hovered over, stops and says"wear a helmet". I got him to move back and forth and it is fixed to the navbar, but the problem is that when the screen size changes, say it's on a smaller phone or computer, then the biker dude turns around at a different spot and it runs infront of the navbar stuff.
here is the html:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <title>CountrySideBycicling</title>
    <link rel="stylesheet" href="main.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-social/5.1.1/bootstrap-social.min.css">

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

          </button>

            Home
                  (current)

            About

            Gallery

            Services

            Contact

            Brands

CountrySideBycicling

  Lorem ipsum dolor sit amet consectetur adipisicing elit.
      Quisquam officiis aperiam temporibus exercitationem hic provident nesciunt,
       quod officia neque quam sint dicta, mollitia commodi illo necessitatibus inventore blanditiis eveniet maiores.

    <button class="btn btn-primary">Read More</button>

Business Name or Tagline

This is a template that is great for small businesses. It doesn't have too much fancy flare to it, but it makes a great use of the standard Bootstrap core components. Feel free to use this template for any project you want!

        Call to Action!

This call to action card is a great place to showcase some important information or display a clever tagline!

Section Heading

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid, suscipit, rerum quos facilis repellat architecto commodi officia atque nemo facere eum non illo voluptatem quae delectus odit vel itaque amet.

Section Heading

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid, suscipit, rerum quos facilis repellat architecto commodi officia atque nemo facere eum non illo voluptatem quae delectus odit vel itaque amet.

              Previous

              Next

Card One

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem magni quas ex numquam, maxime minus quam molestias corporis quod, ea minima accusamus.

        More Info

Card Two

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quod tenetur ex natus at dolorem enim! Nesciunt pariatur voluptatem sunt quam eaque, vel, non in id dolore voluptates quos eligendi labore.

        More Info

Card Three

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem magni quas ex numquam, maxime minus quam molestias corporis quod, ea minima accusamus.

        More Info

CountrySideBycicling

Here you can use rows and columns to organize your footer content. Lorem ipsum dolor sit amet,
          consectetur
          adipisicing elit.

Brand Sites

          Bikesite

          Bikesite

          Bikesite

Useful links

          Gallary

          Brands

          About

Contact

           windsor, oh, cox road

           grandpa@gmail.com

           + 01 234 567 88

© 2020 Copyright:

            countrysidebicycling.com

here is the css
    margin: 0;
    padding: 0;
}

div{
    width: 100%;
    height: 100%;
}
.navbar-default {
    background: none;
}
.navbar{
  position: fixed;
  z-index: 10;
    padding: 10px 0 10px 10px;
    top: 0;
    width: 100%;
  }

  footer{
      background-color:#e6e6e6;
  }

  .jumbotron{
      background-image: url('download.jpeg');
      color: white;
      background-attachment: fixed;
      background-repeat: no-repeat;
      background-size: cover;
      min-height: 400px;
      margin-top: 0px;
      margin-bottom: 8px;
  }
  a{
      color:#2e5984;
  }

 .navbar-brand{
     height: 60px;
     width: 100px;
 }

 #aboutusimg{
     background-size: 100%;
        background-image: url(download.jpeg);

        background-repeat:no-repeat;

        height: 400px;
        }

/* slider */

.carousel .carousel-item {
    width: 100%;
    height: 100vh;
    background-size: cover;
    background-position: center;
}

.carousel .carousel-item:first-of-type {
    background-image: url('download.jpeg');
}

.carousel .carousel-item:nth-of-type(2) {
    background-image: url("download.jpeg");
}

.carousel .carousel-item:last-of-type {
    background-image: url("download.jpeg");
}

.carousel-control-prev-icon, .carousel-control-next-icon {
    width: 50px;
    height: 50px;
}

/* partners slider, about page */

/* carousel */

h2{
    text-align:center;
    padding: 20px;
  }
  /* Slider */

  .slick-slide {
      margin: 0px 20px;
  }

  .slick-slide img {
      width: 100%;
  }

  .slick-slider
  {
      position: relative;
      display: block;
      box-sizing: border-box;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
              user-select: none;
      -webkit-touch-callout: none;
      -khtml-user-select: none;
      -ms-touch-action: pan-y;
          touch-action: pan-y;
      -webkit-tap-highlight-color: transparent;
  }

  .slick-list
  {
      position: relative;
      display: block;
      overflow: hidden;
      margin: 0;
      padding: 0;
  }
  .slick-list:focus
  {
      outline: none;
  }
  .slick-list.dragging
  {
      cursor: pointer;
      cursor: hand;
  }

  .slick-slider .slick-track,
  .slick-slider .slick-list
  {
      -webkit-transform: translate3d(0, 0, 0);
         -moz-transform: translate3d(0, 0, 0);
          -ms-transform: translate3d(0, 0, 0);
           -o-transform: translate3d(0, 0, 0);
              transform: translate3d(0, 0, 0);
  }

  .slick-track
  {
      position: relative;
      top: 0;
      left: 0;
      display: block;
  }
  .slick-track:before,
  .slick-track:after
  {
      display: table;
      content: '';
  }
  .slick-track:after
  {
      clear: both;
  }
  .slick-loading .slick-track
  {
      visibility: hidden;
  }

  .slick-slide
  {
      display: none;
      float: left;
      height: 100%;
      min-height: 1px;
  }
  [dir='rtl'] .slick-slide
  {
      float: right;
  }
  .slick-slide img
  {
      display: block;
  }
  .slick-slide.slick-loading img
  {
      display: none;
  }
  .slick-slide.dragging img
  {
      pointer-events: none;
  }
  .slick-initialized .slick-slide
  {
      display: block;
  }
  .slick-loading .slick-slide
  {
      visibility: hidden;
  }
  .slick-vertical .slick-slide
  {
      display: block;
      height: auto;
      border: 1px solid transparent;
  }
  .slick-arrow.slick-hidden {
      display: none;
  }

  /* lil dude */

  #riding{
    width: 50px;
    height: 40px;
    z-index: 30;
    position: fixed;
    top: 25px;
    left: 0px;
    transform: rotateY(0deg);
}
#message{
    color: white;
    position: fixed;
    top: 0;
    left: 0;
}

keep in mind that there are other files, this is just the index.html, so the css has other stuff in it, but the little dude is at the bottom of the css, and before the navbar in the html.

A: The hardcoded values of 200 and 550 will not work when the navbar dimensions are adjusted for diffeerent size screens.  I've changed it to retrieve the offsetWidth and offsetLeft of the (.navbar-toggle button or .nav-item[0]) and .navbar-brand image to bounce back.

body {

    margin: 0;
    padding: 0;
}

div{
    width: 100%;
    height: 100%;
}
.navbar-default {
    background: none;
}
.navbar{
  position: fixed;
  z-index: 10;
    padding: 10px 0 10px 10px;
    top: 0;
    width: 100%;
  }

  footer{
      background-color:#e6e6e6;
  }

  .jumbotron{
      background-image: url('download.jpeg');
      color: white;
      background-attachment: fixed;
      background-repeat: no-repeat;
      background-size: cover;
      min-height: 400px;
      margin-top: 0px;
      margin-bottom: 8px;
  }
  a{
      color:#2e5984;
  }

 .navbar-brand{
     height: 60px;
     width: 100px;
 }

 #aboutusimg{
     background-size: 100%;
        background-image: url(download.jpeg);

        background-repeat:no-repeat;

        height: 400px;
        }

/* slider */

.carousel .carousel-item {
    width: 100%;
    height: 100vh;
    background-size: cover;
    background-position: center;
}

.carousel .carousel-item:first-of-type {
    background-image: url('download.jpeg');
}

.carousel .carousel-item:nth-of-type(2) {
    background-image: url("download.jpeg");
}

.carousel .carousel-item:last-of-type {
    background-image: url("download.jpeg");
}

.carousel-control-prev-icon, .carousel-control-next-icon {
    width: 50px;
    height: 50px;
}

/* partners slider, about page */

/* carousel */

h2{
    text-align:center;
    padding: 20px;
  }
  /* Slider */

  .slick-slide {
      margin: 0px 20px;
  }

  .slick-slide img {
      width: 100%;
  }

  .slick-slider
  {
      position: relative;
      display: block;
      box-sizing: border-box;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
              user-select: none;
      -webkit-touch-callout: none;
      -khtml-user-select: none;
      -ms-touch-action: pan-y;
          touch-action: pan-y;
      -webkit-tap-highlight-color: transparent;
  }

  .slick-list
  {
      position: relative;
      display: block;
      overflow: hidden;
      margin: 0;
      padding: 0;
  }
  .slick-list:focus
  {
      outline: none;
  }
  .slick-list.dragging
  {
      cursor: pointer;
      cursor: hand;
  }

  .slick-slider .slick-track,
  .slick-slider .slick-list
  {
      -webkit-transform: translate3d(0, 0, 0);
         -moz-transform: translate3d(0, 0, 0);
          -ms-transform: translate3d(0, 0, 0);
           -o-transform: translate3d(0, 0, 0);
              transform: translate3d(0, 0, 0);
  }

  .slick-track
  {
      position: relative;
      top: 0;
      left: 0;
      display: block;
  }
  .slick-track:before,
  .slick-track:after
  {
      display: table;
      content: '';
  }
  .slick-track:after
  {
      clear: both;
  }
  .slick-loading .slick-track
  {
      visibility: hidden;
  }

  .slick-slide
  {
      display: none;
      float: left;
      height: 100%;
      min-height: 1px;
  }
  [dir='rtl'] .slick-slide
  {
      float: right;
  }
  .slick-slide img
  {
      display: block;
  }
  .slick-slide.slick-loading img
  {
      display: none;
  }
  .slick-slide.dragging img
  {
      pointer-events: none;
  }
  .slick-initialized .slick-slide
  {
      display: block;
  }
  .slick-loading .slick-slide
  {
      visibility: hidden;
  }
  .slick-vertical .slick-slide
  {
      display: block;
      height: auto;
      border: 1px solid transparent;
  }
  .slick-arrow.slick-hidden {
      display: none;
  }

  /* lil dude */

  #riding{
    width: 50px;
    height: 40px;
    z-index: 30;
    position: fixed;
    top: 25px;
    left: 0px;
    transform: rotateY(0deg);
}
#message{
    color: white;
    position: fixed;
    top: 0;
    left: 0;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <title>CountrySideBycicling</title>
    <link rel="stylesheet" href="main.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-social/5.1.1/bootstrap-social.min.css">

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

          </button>

            Home
                  (current)

            About

            Gallery

            Services

            Contact

            Brands

CountrySideBycicling

  Lorem ipsum dolor sit amet consectetur adipisicing elit.
      Quisquam officiis aperiam temporibus exercitationem hic provident nesciunt,
       quod officia neque quam sint dicta, mollitia commodi illo necessitatibus inventore blanditiis eveniet maiores.

    <button class="btn btn-primary">Read More</button>

Business Name or Tagline

This is a template that is great for small businesses. It doesn't have too much fancy flare to it, but it makes a great use of the standard Bootstrap core components. Feel free to use this template for any project you want!

        Call to Action!

This call to action card is a great place to showcase some important information or display a clever tagline!

Section Heading

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid, suscipit, rerum quos facilis repellat architecto commodi officia atque nemo facere eum non illo voluptatem quae delectus odit vel itaque amet.

Section Heading

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid, suscipit, rerum quos facilis repellat architecto commodi officia atque nemo facere eum non illo voluptatem quae delectus odit vel itaque amet.

              Previous

              Next

Card One

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem magni quas ex numquam, maxime minus quam molestias corporis quod, ea minima accusamus.

        More Info

Card Two

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quod tenetur ex natus at dolorem enim! Nesciunt pariatur voluptatem sunt quam eaque, vel, non in id dolore voluptates quos eligendi labore.

        More Info

Card Three

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem magni quas ex numquam, maxime minus quam molestias corporis quod, ea minima accusamus.

        More Info

CountrySideBycicling

Here you can use rows and columns to organize your footer content. Lorem ipsum dolor sit amet,
          consectetur
          adipisicing elit.

Brand Sites

          Bikesite

          Bikesite

          Bikesite

Useful links

          Gallary

          Brands

          About

Contact

           windsor, oh, cox road

           grandpa@gmail.com

           + 01 234 567 88

© 2020 Copyright:

            countrysidebicycling.com

here is the css


Q: Curl Not Sending I have this curls on my localhost and these just works fine doing its task.
These curls are: [1] - GCM ; [2] - my own api.
However, when uploaded these files to my online server, curl [2] is not working but curl [1] is just doing fine.
// curl [1] - my own api
public function send($recipient, $message)
{
    // $client = new GuzzleHttp\Client();
//       $r = $client->post('http://link.to.api', [
// 'body' => [
// 'recipient' => $recipient,
//  'message' => $message['message']
// ] ]);
    // $response = $client->send($r);

    // $postData = 'recipient='.$recipient.
                // '&message='.$message['message'];

// shell_exec('curl -i -X POST "http://link.to.api" -d "'. $postData.'"');

    $url = 'http://link.to.api';

    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch,CURLOPT_HEADER, false);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    // curl_setopt($ch, CURLOPT_POST, count($postData));

    // Disabling SSL Certificate support temporarly
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    curl_setopt($ch, CURLOPT_POSTFIELDS, array('recipient'=>'123123', 'message'=>'assss'));

    $output=curl_exec($ch);

    curl_close($ch);
    return $output;

}

// curl [2] - GCM
public function send($reg_ids, $message)
{
    // Set POST variables
    $url = 'https://android.googleapis.com/gcm/send';
    $GOOGLE_API_KEY = '11111111111111111111111111111111';

    $fields = array(
        'registration_ids' => $reg_ids,
        'data' => $message,
    );

    $headers = array(
        'Authorization: key=' . $GOOGLE_API_KEY,
        'Content-Type: application/json'
    );
    // Open connection
    $ch = curl_init();

    // Set the url, number of POST vars, POST data
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Disabling SSL Certificate support temporarly
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

    // Execute post
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }

    // Close connection
    curl_close($ch);
    return $result;
}

As you can see, I have tried different options for send my curl[2].
Any tips and help?
My website that do these things and my [link.to.api] are stored in the same server.

A: curl_setopt($ch, CURLOPT_POSTFIELDS, array('recipient'=>'123123', 'message'=>'assss'));

I just change the above code to this:
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

where $postData is:
$postData = 'recipient='.$recipient.'&message='.$message['message']

Alas!


Q: How to tell Mathematica to replace 0 to power 0 by 1? Experts;
Given
f = (#1^#2) &

Is there a way to define 'f' above such that if #1 and #2 are both zero, then the value of the pure function 'f' should be 1 ?
so that when I write
f[0,0]

it will return 1 and not Indeterminate?
btw, I know I can write
f = (If[#1 == 0 && #2 == 0, 1, #1^#2]) &

But I wanted a general rule or pattern, so I do not have to write these checks, as the pure function can be more complicated (many # in it ) and I do not want to do many of these 'if then else' checks for each possible 0^0 that might show up.
thanks
Update:
May be I should clarify more why I am doing this.
I have a user selects a function from a menu. The function is
a x^n0 + b y^n1 + c x^n2 y^n3

Where in the above, the parameters 'n0', 'n1', 'n2' and 'n3' also can be selected from sliders, and these can be zero.
Now, 'x' and 'y' are coordinates, and these can be zero also.
Therefore, it is possible that 0^0 can be encountered when evaluating the above function.
There are many cases to check for, when doing it myself. For example 'y^n3' can be 0^0 and not the other, y^n1 can be 0^0 and not the other, x^n2 y^n3 can be both 0^0 and not the others, etc.., and so I have to define many different cases. (16 possible cases I think).
And I am trying to avoid this. If I can tell Mathematica to replace 0^0 by 1 at a lower level, then life will be simpler.
Update 12/7/11
Thanks for everyone's answers and comments, all are very useful and solve my problem and I learned from them.
I selected Leonid answer as it allowed me to solve my problem with least amount of additional coding.
Here is an small example
Manipulate[Row[{format[x, n], "=", eval[x, n]}],
 {{x, 0.0, "x="}, 0, 1, .1, Appearance -> "Labeled"},
 {{n, 0.0, "n="}, 0, 1, .1, Appearance -> "Labeled"},
 Initialization :>
  (
   format[x_, n_] := HoldForm["(" x ")"^n];
   eval = Unevaluated[#1^#2] /. HoldPattern[0.0^0.0] :> 0.0 &
   )
 ]

I use real numbers everywhere in my code (it is a numerical pde solver), so that is why I used 0.0 in the above and not 0^0 to fit with what I am doing.

A: You may try writing it like f = Quiet[Check[#1^#2,1]] &.
Quiet will suppress the "Power::indet: "Indeterminate expression 0^0 encountered." message and Check will replace the result with 1 if it is indeterminate.
It is probably better to use some function like s = Quiet[Check[#1, 1]] and wrap your expressions in it.

A: I'm slightly surprised the trivial (albeit slightly dangerous) fix did not get mentioned earlier. If you really don't expect the expression 0^0 to come up in any context where you'd (a) be worried that it did, or (b) would like it to evaluate it to something other than 1, you can simply try
Unprotect[Power];
Power[0, 0] = 1;
Protect[Power];
0^0

I needed this fix in a situation where a complicated function had a number of calls to expressions of the form x^n where x is real and n is an integer, in which case 0^0 should be seen as the limit of x^0=1 as x goes to 0.
It's important to note, though, that doing this will 'contaminate' Power for the current kernel session, and may therefore break other notebooks which run concurrently and for which conditions (a) and (b) may not hold. Since Power is located in the System՝ context instead of Global՝, it may be difficult to separate the contexts of different notebooks to avoid clashes produced by this fix.

A: Of course there are many ways to do things in Mathematica, but a design idiom I often use is to write the "function" (actually, a pattern) with decreasing specificity.  Mathematica has the property that it will apply more specific patterns before less specific.
So, for your case I'd just write:
Clear[f];
f[0, 0] = 1;
f[a_, b_] := a^b;

I assume you expect to work with integer values since that's the usual context for this type of situation, e.g. when evaluating Bernstein basis functions.

A: I agree with the answer of @Deep Yellow, but if you insist on a pure function, here is one way:
f = Unevaluated[#1^#2] /. HoldPattern[0^0] :> 1 &

EDIT
Staying within the realm of pure functions, the situation you described in your edit can be addressed in the same way as my solution to your specific original example. You can automate this with a tiny bit of metaprogramming, defining the following function transformer:
z2zProtect[Function[body_]] :=
   Function[Unevaluated[body] /. HoldPattern[0^0] :> 1]

Then, my previous code can be rewritten as:
 f = z2zProtect[#1^#2 &]

But you can is this more generally, for example:
ff = z2zProtect[#1^#2 + 2 #2^#3 + 3 #3^#4 &]

In[26]:= ff[0,0,0,0]
Out[26]= 6


Q: handling "No results" with Jquery Autocomplete Hey I'm trying to return a message when there are no results for the users current query! I have looked all over the net and there are similar scenarios, but I can't seem to get it working with my code below!
Can anyone help me figure this out please, as I am pulling my hair out trying to fix it!
I need to maintain the ability to use the keyboard to scroll down through the results.
Thanks in advance.
HTML

   <div id="search_box">
     <form id="search_form" autocomplete="off" action="" onSubmit="return false;">
        <input type="text" id="suggestSearchBox" value="Search by City or Hotel Name" onClick="this.value='';" />
     </form>
   </div>

Javascript
NOTE: The remote data source is called "dataLocCodes", which is a javascript array

// JavaScript Document
$(function() {
   $("#suggestSearchBox").focus().autocomplete(dataLocCodes, {
      max: 15,
      selectFirst: true,
      matchContains: true,
      formatItem: function(row, i, max){
      if (row.hotelId) {
         return row.accomName + ' - ' + row.city + ' - ' + row.country;
      } else {
         return row.city + ' - ' +    row.country;
      }
   }
}).result(
   function(event, row, formatted) {
      $("input#suggestSearchBox").val(row.city + ' - ' + row.country);
      var param = row.locparam;
      var encoded_url = param.replace(/ /gi,"+");
      encoded_url = encoded_url.replace(/&/gi,"amp");
      window.location.href = "hotels.html?location=" + encoded_url;
   });
});

A: There are a couple of ways to handle this.  You can either create a source method so that if the results from the filter are empty, you add "no results" as a value, or you handle the response event to display a message that no results where returned in your ui.  If using the source method, then add a select handler to prevent No Result from being a value.
var availableTags = ['Abc', 'Def', 'ghi'];
$('#noresults').autocomplete({
    source: function (request, response) {
        var responses = $.ui.autocomplete.filter(availableTags, request.term);
        if (responses.length == 0) responses.push('No Result');
        response(responses);

    },
    response: function (event, ui)
    {
        if (ui.content.length == 0) {
            console.log('No results');
        }
    },
    select: function (event, ui) {
        // don't let no result get selected
        return (ui.item.value != 'No Result');
    }
});


Q: How to keep a round imageView round using auto layout? How do I turn a rectangular image view into a circular image view that can hold shape in auto layout without setting width and height restraints? Thereby allowing the imageView to define it’s size, and size bigger and smaller relative to objects around it with leading, trailing, top, and bottom constraints.
I asked a similar question the other day, but I think this might be posed in a more concise way. Thanks so much!
EDIT
Ok, I started over to make this as simple as possible. I have a view named "Cell" and a UIImageView named "dog" within the cell, and that's it. I don't have "unable to simultaneously satisfy constraints" in the console anymore, just two simple views using auto layout. I'm still trying to use this code to round the UIImageView:
profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2
profileImageView.clipsToBounds = true

Here is the cell constraint setup:

Here is the profile pic constraint setup:

Here is the result without the code, no rounding, but nice and square:

Here is the result with the code to round:

This makes no sense to me, because without the rounding code the image is square, and with the code it's diamond shaped. If it's square shouldn't it be a circle with no issues?
EDIT 2
Here's what happens when I remove the bottom constraint and add a multiplier of .637 for equal height to superview.

A: Unfortunately you cannot do this using cornerRadius and autolayout — the CGLayer is not affected by autolayout, so any change in the size of the view will not change the radius which has been set once causing, as you have noticed, the circle to lose its shape.
You can create a custom subclass of UIImageView and override layoutSubviews in order to set the cornerRadius each time the bounds of the imageview change.
EDIT
An example might look something like this:
class Foo: UIImageView {
    override func layoutSubviews() {
        super.layoutSubviews()

        let radius: CGFloat = self.bounds.size.width / 2.0

        self.layer.cornerRadius = radius
    }
}

And obviously you would have to constrain the Foobar instance's width to be the same as the height (to maintain a circle). You would probably also want to set the Foobar instance's contentMode to UIViewContentMode.ScaleAspectFill so that it knows how to draw the image (this means that the image is likely to be cropped).

A: First of all, I should mention that u can get a circle shape for your UIView/UIImageView only if the width and height will be equal. It's important to understand. In all other cases (when width != height), you won't get a circle shape because the initial shape of your UI instance was a rectangle.
OK, with this so UIKit SDK provides for developers a mechanism to manipulate the UIview's layer instance to change somehow any of layer's parameters, including setting up a mask to replace the initial shape of UIView element with the custom one. Those instruments are IBDesignable/IBInspectable. The goal is to preview our custom views directly through Interface Builder.
So using those keywords we can write our custom class, which will deal only with the single condition whether we need to round corners for our UI element or not.
For example, let's create the class extended from the UIImageView.
@IBDesignable
class UIRoundedImageView: UIImageView {

    @IBInspectable var isRoundedCorners: Bool = false {
        didSet { setNeedsLayout() }
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        if isRoundedCorners {
            let shapeLayer = CAShapeLayer()
            shapeLayer.path = UIBezierPath(ovalIn:
                CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width, height: bounds.height
            )).cgPath
            layer.mask = shapeLayer
        }
        else {
            layer.mask = nil
        }

    }

}

After setting the class name for your UIImageView element (where the dog picture is), in your storyboard, you will get a new option, appeared in the Attributes Inspector menu (details at the screenshot).

The final result should be like this one.

A: Setting radius in viewWillLayoutSubviews will solve the problem
override func viewWillLayoutSubviews() {
  super.viewWillLayoutSubviews()
  profileImageView.layer.cornerRadius = profileImageView.frame.height / 2.0
}

A: It seems when you add one view as a subview of another that netted view will not necessarily have the same height as its superview. That's what the problem seems like. The solution is to not add your imageView as a subview, but have it on top of your backgroundView. In the image below I'm using a UILabel as my backgroundView.

Also in your case, when you're setting the cornerRadius use this: let radius: CGFloat = self.bounds.size.height / 2.0.

A: create new interface in your .h file like
@interface CornerClip : UIImageView

@end

and implementation in .m file like
@implementation cornerClip

-(void)layoutSubviews
{
    [super layoutSubviews];

    CGFloat radius = self.bounds.size.width / 2.0;

    self.layer.cornerRadius = radius;

}

@end

now just give class as "CornerClip" to your imageview.
100% working... Enjoy

A: With my hacky solution you'll get smooth corner radius animation alongside frame size change.
Let's say you have ViewSubclass : UIView. It should contain the following code:
class ViewSubclass: UIView {
    var animationDuration : TimeInterval?
    let imageView = UIImageView()
    //some imageView setup code

    override func layoutSubviews() {
        super.layoutSubviews()

        if let duration = animationDuration {
            let anim = CABasicAnimation(keyPath: "cornerRadius")
            anim.fromValue = self.imageView.cornerRadius
            let radius = self.imageView.frame.size.width / 2
            anim.toValue = radius
            anim.duration = duration
            self.imageView.layer.cornerRadius = radius
            self.imageView.layer.add(anim, forKey: "cornerRadius")
        } else {
            imageView.cornerRadius = imageView.frame.size.width / 2
        }

        animationDuration = nil
    }
}

An then you'll have to do this:
let duration = 0.4 //For example
instanceOfViewSubclass.animationDuration = duration
UIView.animate(withDuration: duration, animations: {
    //Your animation
    instanceOfViewSubclass.layoutIfNeeded()
})

It's not beautiful, and might not work for complex multi-animations, but does answer the question.

A: Swift 4+ clean solution based on omaralbeik's answer
import UIKit

extension UIImageView {

    func setRounded(borderWidth: CGFloat = 0.0, borderColor: UIColor = UIColor.clear) {
        layer.cornerRadius = frame.width / 2
        layer.masksToBounds = true
        layer.borderWidth = borderWidth
        layer.borderColor = borderColor.cgColor
    }
}

Sample usage in UIViewController
1.Simply rounded UIImageView
override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        imageView.setRounded()
    }

2.Rounded UIImageView with border width and color
override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        imageView.setRounded(borderWidth: 1.0, borderColor: UIColor.red)
    }

A: write this code
override viewDidLayoutSubViews() {
profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2
profileImageView.clipsToBounds = true

}

in this case it will called after calculating the autolayout calculations in the first code you called the cornerradius code before calculating the actual size of the view cuz it's dynamically calculated using aspect ratio , the actual corner radius is calculated before equaling the width and the height of the view

A: I have same problem, and Now I get what happened here, hope some ideas can help you:
there are something different between the tows:

*

*your profileImageView in storyboard

*your profileImageView in viewDidLoad
the size of bound and frame is different when viewDidLoad and in storyboard,just because view is resize for different device size.
You can try it print(profileImageView.bounds.size) in viewDidLoad and viewDidAppear you will find the size in viewDidLoad you set cornerRadius  is not the real "running" size.
a tips for you:
you can use a  subClass of ImageView to avoid it, or do not use it in storyboard,

A: If you have subclassed the UIImageView. Then just add this piece of magical code in it.
Written in : Swift 3
override func layoutSubviews() {
    super.layoutSubviews()
    if self.isCircular! {
        self.layer.cornerRadius = self.bounds.size.width * 0.50
    }
}

A: I am quite new to iOS native development, but I had the same problem and found a solution.

So the green background has this constraints:
backgroundView.translatesAutoresizingMaskIntoConstraints = false
backgroundView.topAnchor.constraint(equalTo: superview!.safeAreaLayoutGuide.topAnchor).isActive = true
backgroundView.leftAnchor.constraint(equalTo: superview!.leftAnchor).isActive = true
backgroundView.widthAnchor.constraint(equalTo: superview!.widthAnchor).isActive = true
backgroundView.heightAnchor.constraint(equalTo: superview!.heightAnchor, multiplier: 0.2).isActive = true

The image constraints:
avatar.translatesAutoresizingMaskIntoConstraints = false
avatar.heightAnchor.constraint(equalTo: backgroundView.heightAnchor, multiplier: 0.8).isActive = true
avatar.widthAnchor.constraint(equalTo: backgroundView.heightAnchor, multiplier: 0.8).isActive = true
avatar.centerYAnchor.constraint(equalTo: backgroundView.centerYAnchor, constant: 0).isActive = true
avatar.leadingAnchor.constraint(equalTo: backgroundView.leadingAnchor, constant: 20).isActive = true

on viewWillLayoutSubviews() method I set the corner radius
to
avatar.layer.cornerRadius = (self.frame.height * 0.2 * 0.8) / 2

Basically, I am simply calculating the height of the image and then divide it by 2. 0.2 is the backgroungView height constraint multiplier and 0.8 the image width/height constraint multiplier.

A: Solution: Crop the image
[imageView setImage:[[imageView image] imageWithRoundedCorners:imageView.image.size.width/2]];
imageView.contentMode = UIViewContentModeScaleAspectFill;

I was looking for the same solution for profile pictures. After some hit and try and going through available functions, I came across something which works and is a nice way to ensure its safe. You can use the following function to crop out a round image from the original image and then you need not worry about the corner radius.
Post this even if your view size changes the image remains round and looks good.

A: Can be easily done by creating an IBOutlet for the constraint which needs to be changed at runtime. Below is the code:

*

*Create a IBOutlet for the constraint that needs to be changed at run time.
@IBOutlet var widthConstraint: NSLayoutConstraint!

*Add below code in viewDidLoad():
self.widthConstraint.constant = imageWidthConstraintConstant()

Below function determines for device types change the width constraint accordingly.
func imageWidthConstraintConstant() -> CGFloat {

    switch(self.screenWidth()) {

    case 375:
        return 100

    case 414:
        return 120

    case 320:
        return 77

    default:
        return 77
    }
}

A: Add a 1:1 aspect ratio constraint to the imageView for it to remain circular, despite any height or width changes.

A: I added custom IBInspectable cornerRadiusPercent, so you can do it without any code.
class RoundButton: UIButton {

    override var bounds: CGRect {
        didSet {
            updateCornerRadius()
        }
    }

    //private var cornerRadiusWatcher : CornerRadiusPercent?
    @IBInspectable var cornerRadiusPercent: CGFloat = 0 {

        didSet {
            updateCornerRadius()
        }
    }

    func updateCornerRadius()
    {
        layer.cornerRadius = bounds.height * cornerRadiusPercent
    }

}


Q: Using Array(Tuple(LowCardinality(String), Int32)) in ClickHouse I have a table
CREATE TABLE table (
    id Int32,
    values Array(Tuple(LowCardinality(String), Int32)),
    date Date
) ENGINE MergeTree()
PARTITION BY toYYYYMM(date)
ORDER BY (id, date)

but when executing the request
SELECT count(*)
FROM table
WHERE (arrayExists(x -> ((x.1) = toLowCardinality('pattern')), values) = 1)

I get an error
Code: 49. DB::Exception: Received from clickhouse:9000. DB::Exception: Cannot capture column 3 because it has incompatible type: got String, but LowCardinality(String) is expected..

If I replace the column 'values'
values Array(Tuple(String, Int32))
then the request is executed without errors.
What could be the problem when using Array(Tuple(LowCardinality(String), Int32))?

A: Until it will be fixed (see bug 7815), can be used this workaround:
SELECT uniqExact((id, date)) AS count
FROM table
ARRAY JOIN values
WHERE values.1 = 'pattern'

For the case when there are more than one Array-columns can be used this way:
SELECT uniqExact((id, date)) AS count
FROM
(
    SELECT
        id,
        date,
        arrayJoin(values) AS v,
        arrayJoin(values2) AS v2
    FROM table
    WHERE v.1 = 'pattern' AND v2.1 = 'pattern2'
)

A:
values Array(Tuple(LowCardinality(String), Int32)),

Do not use Tuple. It brings only cons.
It's still *2 files on the disk.
It gives twice slowdown then you extract only one tuple element
https://gist.github.com/den-crane/f20a2dce94a2926a1e7cfec7cdd12f6d
valuesS Array(LowCardinality(String)),
valuesI Array(Int32)


Q: I want the view to remain static but the content to re-orient within the view I am making a view with several subviews for iPad. I want all the positioning and sizing of the subviews to stay the same when rotating the iPad, but the content inside the subviews to re-orient. Does anyone know how to do this?

A: It sounds like you still need to layout the views depending on the orientation. However, you're portrait and landscape frames would have different proportions on the screen.
An Example of how you might layout a view:
int h = 300;
int w = 100;
int space = 50;

CGRect frame;
if( interfaceOrientation == UIInterfaceOrientationPortrait ) {

   frame = CGRectMake( space, space, w, h );
}
else if( interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown ) {
    frame = CGRectMake( self.view.bounds.size.width - w - space, self.view.bounds.size.height- h - space, w, h );
}
else if( interfaceOrientation == UIInterfaceOrientationLandscapeRight ) {
    frame = CGRectMake( space, self.view.bounds.size.height- w - space, h , w );
}
else if( interfaceOrientation == UIInterfaceOrientationLandscapeLeft ) {
    frame = CGRectMake( self.view.bounds.size.width - h - space, space, h, w );
}

self.label.frame = frame;


Q: Performance Issues in Celery I already read other posts about that but none of them solve my problem. I have function to scan all ports for a given ip. It takes 5-10 seconds to complete without celery but if I use the celery to run this function, it takes approximately 15 minutes. I observed that function without celery, consuming approximately %90 cpu power but with celery this value is %2-%3 so task takes 15 minutes to finish. This causes a serious performance problem for me. How to increase a cpu power for a specific task or any idea to solve this problem?
@app.task
def port_scan(ip): ##requires nmap 7.70
    if (regex(ip)==True): ##If ip is valid
        try:
            nm = nmap.PortScanner()
            result_1 = nm.scan(ip,arguments="-p 1-65535 -T5") #Just for test

            output = ({"Name":result_1["scan"][ip]["tcp"]})
            # print(output)
            return output #It will return with the output that needed

        except KeyError:
            return None


Q: Input validation using PHP and Jquery Ajax I want to validate an user input with ajax. It is the first time I use Ajax and I got stuck. If the input is correct I still get an error message and I don't know why.
I get as an error 'Subtax error in the jquery file'. What do I do wrong?
Thank you in advance.
HTML:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">

                    Your name
                    <input type="text" name="inputName" class="form-control" id="inputName"   placeholder="Name">

                    Your e-mail
                    <input type="text" name="inputEmail" class="form-control" id="inputEmail"    placeholder="E-mail">

                    Your message for us
                    <textarea name="inputMess" class="form-control" id="inputMess"></textarea>

                <button type="submit" name="send" class="btn btn-default">Send</button>
              </form>

PHP:
 <?php

  sleep(1);

  $mail_reg = '/^(?i)(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9] {1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/';

$return = array();
$mesaj = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (empty($_POST['inputName']) || is_numeric($_POST['inputName'])) {

      $mesaj = "Please enter your name!";
      $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

    } elseif (empty($_POST['inputEmail']) || !preg_match($mail_reg, $_POST['inputEmail'])) {

      $mesaj = "Please enter your e-mail!";
      $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

    } elseif (empty($_POST['inputMess'])) {

      $mesaj = "Please tell us something";
      $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

    } else {

      $return['error'] = false;
      $return['msg'] = 'Thank you for getting in touch. We will contact you!';
      echo json_encode($return);
       exit();

    }
  }

 ?>

JavaScript:
$(document).ready(function() {
 var email_reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;

$('form').submit(function(event) {

  event.preventDefault();

  if ($('#inputName').val() == '' || $('#inputName').val().length < 2 || !isNaN($('#inputName').val())) {

    alert('Please enter your name');

  } else if (!email_reg.test($('#inputEmail').val())) {

    alert('Please enter a valid e-mail adress');

  } else if ($('#inputMess').val() == '' || !isNaN($('#inputMess').val())) {

    alert('Please tell us something');

  } else {

    var formData = $('form').serialize();
    submitForm(formData);

  }

})

function submitForm(formData) {

    $.ajax({

        type: 'POST',
        url: $('form').action,
        data: formData,
        dataType: 'json',
        cache: false,
        timeout: 7000,
        success: function(data) {

                $('#mess').text(data.msg);

        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {

                $('#mess').text('A communication error occured');

        },
        complete: function(XMLHttpRequest, status) {

            //$('form')[0].reset();

        }

    })
}

  })

A: There might be some problem with your jquery file inclusion. Your code is working absolutely fine with me. I tried your code by saving it in a new php file as follows.
<?php

  sleep(1);

  $mail_reg = '/^(?i)(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9] {1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/';

$return = array();
$mesaj = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (empty($_POST['inputName']) || is_numeric($_POST['inputName'])) {

      $mesaj = "Please enter your name!";
      $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

    } elseif (empty($_POST['inputEmail']) || !preg_match($mail_reg, $_POST['inputEmail'])) {

      $mesaj = "Please enter your e-mail!";
      $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

    } elseif (empty($_POST['inputMess'])) {

      $mesaj = "Please tell us something";
      $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

    } else {

      $return['error'] = false;
      $return['msg'] = 'Thank you for getting in touch. We will contact you!';
      echo json_encode($return);
       exit();

    }
  }

 ?>

<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">

                    Your name
                    <input type="text" name="inputName" class="form-control" id="inputName"   placeholder="Name">

                    Your e-mail
                    <input type="text" name="inputEmail" class="form-control" id="inputEmail"    placeholder="E-mail">

                    Your message for us
                    <textarea name="inputMess" class="form-control" id="inputMess"></textarea>

                <button type="submit" name="send" class="btn btn-default">Send</button>
              </form>

Output:

A: Try add header('Content-Type: application/x-javascript'); in php before outputing the json string.


Q: ORA-22992 / ORA-06502+ORA-06512 errors I'm using this part of code in large one :
SELECT DISTINCT
    P.SKU, SUBSTR(X.ATTRIBUTENAME, 14, 3) ATTRIBUTECODE, X.ATTRIBUTEVALUE
FROM
    PRODUCT@ISPSTAG2 P,
    XMLTABLE('/attrs/attr'
    PASSING XMLTYPE(REGEXP_REPLACE(P.ATTRIBUTES_DE_AT, '<attr name="longDescription">.*?<\/attr>'))
    COLUMNS ATTRIBUTENAME VARCHAR2(50) PATH '@name',
            ATTRIBUTEVALUE VARCHAR2(4000) PATH '/string'
) X
WHERE X.ATTRIBUTENAME LIKE 'Z_CA%'
AND DN(DOMAINID) = 'AT'
AND SKU NOT LIKE 'OFF_%' AND SKU NOT LIKE 'PDT%'
AND ATTRIBUTES_DE_AT IS NOT NULL;

And it throws an ORA-22992 error.
I've made some research and a tip can to use the dual
SELECT DISTINCT P.SKU, SUBSTR(X.ATTRIBUTENAME, 14, 3) ATTRIBUTECODE, X.ATTRIBUTEVALUE
FROM PRODUCT@ISPSTAG2 P,
XMLTABLE('/attrs/attr'
    PASSING XMLTYPE(REGEXP_REPLACE(P.ATTRIBUTES_DE_AT, '<attr name="longDescription">.*?<\/attr>'))
    COLUMNS ATTRIBUTENAME VARCHAR2(50) PATH '@name',
            ATTRIBUTEVALUE VARCHAR2(4000) PATH '/string'
) X
WHERE X.ATTRIBUTENAME LIKE 'Z_CA%'
AND DN(DOMAINID) = 'AT'
AND SKU NOT LIKE 'OFF_%' AND SKU NOT LIKE 'PDT%'
AND (SELECT ATTRIBUTES_DE_AT FROM DUAL) IS NOT NULL;

But now I get ORA-06502/ORA-06512 errors :

ORA-06502: PL/SQL : erreur numérique ou erreur sur une valeur
  ORA-06512: à "SYS.XMLTYPE", ligne 272
  ORA-06512: à ligne 1
  06502. 00000 -  "PL/SQL: numeric or value error%s"
  *Cause:    An arithmetic, numeric, string, conversion, or constraint error occurred. For example, this error occurs if an attempt is made to assign the value NULL to a variable declared NOT NULL, or if an attempt is made to assign an integer larger than 99 to a variable declared NUMBER(2).
  *Action:   Change the data, how it is manipulated, or how it is declared so that values do not violate constraints.

But, I executed the first one on ISPSTAG2 and it works, but the second one on ISPSTAG2 returns me the same ORA-06502/ORA-06512 errors so the issue is with the dual subquery.
I also tried to create a view on ISPSTAG2 using DBMS_LOB.SUBSTR with 4000 characters but same error.
Any ideas ? Thank you.

A: If forgot to use the (SELECT ATTRIBUTES_DE_AT FROM DUAL) subquery inside the XMLTYPE...
SELECT DISTINCT P.SKU, SUBSTR(X.ATTRIBUTENAME, 14, 3) ATTRIBUTECODE, X.ATTRIBUTEVALUE
FROM PRODUCT@ISPSTAG2 P,
XMLTABLE('/attrs/attr'
    PASSING XMLTYPE(REGEXP_REPLACE(**(SELECT ATTRIBUTES_DE_AT FROM DUAL)**, '<attr name="longDescription">.*?<\/attr>'))
    COLUMNS ATTRIBUTENAME VARCHAR2(50) PATH '@name',
            ATTRIBUTEVALUE VARCHAR2(4000) PATH '/string'
) X
WHERE X.ATTRIBUTENAME LIKE 'Z_CA%'
AND DN(DOMAINID) = 'AT'
AND SKU NOT LIKE 'OFF_%' AND SKU NOT LIKE 'PDT%'
AND (SELECT ATTRIBUTES_DE_AT FROM DUAL) IS NOT NULL;

The thing I don't understand is that when don't use the subquery in the IS NOT NULL filter I have the the ORA-22992 error (using distant LOB), so why I have a different error not using the dual subquery, which is the same distant LOB ?
Anyway for you for your time/help :)


Q: Why Azure app service restarts when swapping slots? After having this issue in production for a long time, and having read anything i can find about (such as this or this or that), i made a simple test.

*

*Create an empty asp.net website

*in Application_Start, send an email or message (i've used PushBullet) to you so you know when the app starts

*Create a new app service plan and resource group

*Create the website on Azure and publish it

*Create a staging deployment slot

*Swap staging/production

*Publish the website again so both slots have the same version of the website

So i have an empty website, no connectionstring, no slot setting :

When i click swap, I will get notifications that slots restart (at least once each).
Why is this happening ?
UPDATE:
After studying Mohit's answer, i need some more clarifications.

*

*We send the notification in the Application_Start method, which is triggered by the AppInit event if i understand correctly.

*I do not understand the behavior you explain. The order seems very important to ensure no downtime, yet you say it's not necessarily in that order. Why is it required to restart the app domain for the production slot ? Why would users get annoyed that the site is down (it should not) ?

*What is the "new swap" feature ? What's the difference with the "old swap" ? For my tests, i just swapped using the portal.

*You mention the "new swap" pauses before swap. I suppose it just means it waits for the applicationInitialization to complete (eg HTTP 200 on /) ?

*I've done some more testing since yesterday. In the Application_Start method, i've added some Thread.Sleep to make app startups longer. However, when i swap i see no downtime on either staging or production. Shouldn't i experience downtimes on staging, at least for the duration of my app startup ? Does this mean the slot that is warmed up then swapped with production is in fact another temporary slot that is neither staging nor prod ?

A: I have very similar problem, app is restarted after swapping to production slot and that causes unwanted downtime. After a lot of searching I found the following:
In some cases after the swap the web app in the production slot may restart later without any action taken by the app owner. This usually happens when the underlying storage infrastructure of Azure App Service undergoes some changes. When that happens the application will restart on all VMs at the same time which may result in a cold start and a high latency of the HTTP requests. While you cannot control the underlying storage events you can minimize the effect they have on your app in the production slot. Set this app setting on every slot of the app:
WEBSITE_ADD_SITENAME_BINDINGS_IN_APPHOST_CONFIG: setting this to “1” will prevent web app’s worker process and app domain from recycling when the App Service’s storage infrastructure gets reconfigured.
You can find the whole Ruslany post, that I found very helpful here


Q: inquirer package, present questions based on previous answers I'm using NPM 'inquirer' package in order to present the user various questions. One of them is a 'choices' selection.
Is there a way to present follow up questions based on the 'choices' selection?
Here's my code:
    const { prompt } = require('inquirer');
require('colors');

const questions = [
    {
        type: 'input',
        name: 'appName',
        message: 'Enter application name:'
    },
    {
        type: 'input',
        name: 'appDescription',
        message: 'Enter app description:'
    },
    {
        type: 'input',
        name: 'appAuthor',
        message: 'Enter app author:'
    },
    {
        type: 'checkbox',
        name: 'plugins',
        message: 'Select plugins to install:',
        choices: [
            {
                name: 'Cassandra'
            }
        ]
    }
];

module.exports.performQuestions = async () => {
    console.log('\nWelcome to Chef!\n'.underline.italic.cyan);

const answers = await prompt(questions);
if (!answers.appName) {
    console.error('\nPlease provide app name!\n'.red);
    process.exit(1);
}

    answers.appType = 'service';

    return answers;
};

Here I want to present a few more questions if the user selects 'Cassandra' is that possible?
Thanks.

A: You can use "when" and like in the example bellow, the second question will popup only if "Cassandra" is selected:
const QUESTIONS = [
  {
    name: 'your-name',
    type: 'list',
    message: 'Your name:',
    choices: ['Batman', 'Superman', 'Ultron', 'Cassandra'],
  },
  {
    name: 'hello-cassandra',
    type: 'confirm',
    message: 'Oh, hello Cassandra!',
    when: (answers) => answers['your-name'] === 'Cassandra',
  },
];

inquirer.prompt(QUESTIONS)
  .then(answers =>
  {
    console.log(answers);
  });


Q: How to access an application using different host and port with JBoss 5 I have deployed my application in Jboss and I want to give users access to my application with different host and ports per user. To explain clearly:
http://192.168.11.21/MBeanProject/servcount

for user1 and
http://192.168.11.22/MBeanProject/servcount

for user2 so on...
How could I do this?  I am using JBoss5 as my AS.  Based on the user request I need to count the number of times that user1 accessed the first url and the number of times the user2 accessed the second one ...and so on...  Can you guide me how could I procced? Currently I am working with the Snmp traps using JBoss5

A: You will need a separate IP address for every user, right?  Which doesn't sound like a very scalable solution, but if you do decide to do this you will then need as many IP addresses as you have users, and tell JBoss to listen to all interfaces using a startup argument like bin/run.sh -b 0.0.0.0.  Then, your Servlets will be able to tell the full IP address by checking (eg) HttpServletRequest#getRequestUrl().  Or, you could have a separate instance of JBoss running for each user, binding each one to a different IP.
However, this is a very unusual design.  It offers poor scalability, difficult maintenance, difficult network config and sysadmin tasks, and confusion for any new devs on the project.  Appservers are designed to be able to serve multiple users on the same instance.  I can't really see any positives to a design like this.  Unless you have very good reasons for doing so (in which case please share!) you should probably use different URLs for different users, like:
http://192.168.11.21/MBeanProject/user1/servcount
http://192.168.11.21/MBeanProject/user2/servcount

or
http://192.168.11.21/MBeanProject/servcount?user=user1
http://192.168.11.21/MBeanProject/servcount?user=user2


Q: Python 2.7 : UnicodeDecodeError when I use character point with import socket connect I work with python under windows. I have this error "UnicodeDecodeError: 'utf8' codec can't decode byte 0x92" when I excecute this simple code :
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((controlAddr, 9051))

controlAddr is "127.0.0.1" and I know that it is the character '.' which cause the problem so I tried different conversion but each time, I have the same error. I tried these different ways:

*

*controlAddr = u'127.0.0.1'

*controlAddr = unicode('127.0.0.1')

*controlAddr.encode('utf-8')

*controlAddr = u'127'+unichr(ord('\x2e'))+u'0'+unichr(ord('\x2e'))+'0'+unichr(ord('\x2e'))+u'1'
I added # -*- coding: utf-8 -*- at the begining of the main file and socket.py file.
... I still have the same error

A: The error message says you have a byte 0x92 in your file somewhere, which is not valid in utf-8, but in other encodings it may be, for example:
>>> b'\x92'.decode('windows-1252')
'`'

That means that your file encoding is not utf-8, but probably windows-1252, and problematic character is the backtick, not the dot, even if that character is found only in a comment.
So either change your file encoding to utf-8 in your editor, or the encoding line to
# -*- coding: windows-1252 -*-

The error message doesn't mention the file the interpreter choked on, but it may be your "main" file, not socket.py.
Also, don't name your file socket.py, that will shadow the builtin socket module and lead to further errors.
Setting an encoding line only affects that one file, you need to do this for every file, only setting it in your "main" file would not be enough.

A: Your error says 'utf8' codec can't decode byte 0x92". In the Windows codepage 1252, this character maps to U+2019 the right quotation mark ’.
It is likely that the editor you use for your Python script is configured to replace the single quote ('\x27' or ') by the right quotation mark. It may be nicer for text, but is terrible in source code. You must fix it in your editor, or use another editor.

A: Thank you ! Indeed, this character doesn't exist in utf-8.
However, I didn't send the character "`", corresponding to 0x92 with windows-1252 and to nothing in utf-8. Futhermore this error appears when a character "." is in controlAddr and it is the same hexadecimal code for both encoding, i.e, 0x2e.
The complete error message is given above :

Traceback (most recent call last):
  File "C:\Python27\Lib\site-packages\spyderlib\widgets\externalshell\pythonshell.py", line 566, in write_error
    self.shell.write_error(self.get_stderr())
  File "C:\Python27\Lib\site-packages\spyderlib\widgets\externalshell\baseshell.py", line 272, in get_stderr
    return self.transcode(qba)
  File "C:\Python27\Lib\site-packages\spyderlib\widgets\externalshell\baseshell.py", line 258, in transcode
    return to_text_string(qba.data(), 'utf8')
  File "C:\Python27\Lib\site-packages\spyderlib\py3compat.py", line 134, in to_text_string
    return unicode(obj, encoding)
  File "C:\Python27\Lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 736: invalid start byte

For this code :

controlPort = 9051
controlAddr = unicode("127.0.0.1")
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((controlAddr, controlPort))


Q: Set the selected value of two dropdownlists simultaneously using jQuery How to set the selected value of a dropdownlist to the selected value of another?
The below code shows how to accomplish this correctly.
ASPX
<asp:DropDownList ID="ddl1" RunAt="Server" DataValueField="ID" DataTextField="ID" AppendDataBoundItems="true"/>
<asp:DropDownList ID="ddl2" RunAt="Server" DataValueField="ID" DataTextField="TEXT" AppendDataBoundItems="true"/>

JQUERY
$("#<%= ddl1.ClientID %>").change(function() {
    var Code = $(this).val();
    $("#<%= ddl2.ClientID %>").val(Code);
});

When using jQuery Mobile, however the DataTextField is rendered as a span tag which the above code does not update.
QUESTION
How to amend the above code to accommodate for this?
http://jsfiddle.net/E28WW/

A: Store the value from first selectmenu, then look for it in the second one. Select it using
.prop('selected', true); and then call .selectmenu('refresh').

Demo

$(document).on('pageinit', function () {
  $(document).on('change', '#ddl1', function () {
    var selected = $(this).val();
    $('#ddl2 option[value="' + selected + '"]').prop('selected', true);
    $('#ddl2').selectmenu('refresh');
  });
});

I used pageinit which is equivalent to .ready(). It is a special event for jQM.

A: Have you checked that the change function is actually being called. Is the script you provide the entire contents of the script tag?
The function will not be bound to the event until it is loaded, using the $(document).ready(); will bind the event to the control.
$(document).ready(function() {
    $("#<%= ddl1.ClientID %>").change(function() {
        var Code = $(this).val();
        $("#<%= ddl2.ClientID %>").val(Code);
    });
});


Q: Postman Response download is NOT pretty in Atom and other editors While using Postman and Sending and Downloading a Request, I have saved the JSON locally and when opening in Atom, Notepad++ and other editors, the Postman JSON is not parsed.  I've tried changing LF in Atom and it doesn't seem to do anything.  See below which shows (on the right pane) a pretty pane that parses nicely from a different project.
I don't see any settings in Postman to change nor is there an option to change when downloading.  Any ideas?


Q: Display a delivery day range based on shipping country in Woocommerce In Woocommerce, I'm trying to add an estimated delivery day range on cart and checkout pages.
I have set 2 shipping Zones: Germany and other European countries (outside Germany) called "DHL Europe". I need to display a different delivery day range for Germany shipping country than other European shipping countries:

*

*Germany shipping country will display "Lieferzeit 3-5 Werktage" (and when there is no shipping costs).

*Other European shipping countries will display "Lieferzeit 5-7 Werktage"

My code attempt:
function sv_shipping_method_estimate_label( $label, $method ) {
    $label .= '
';
    switch ( $method->method_id ) {
        case 'flat_rate':
            $label .= 'Lieferzeit 3-5 Werktage';
            break;
        case 'free_shipping':
            $label .= 'Lieferzeit 3-5 Werktage';
            break;
        case 'international_delivery':
            $label .= 'Lieferzeit 5-7 Werktage';
    }

    $label .= '';
    return $label;
}
add_filter( 'woocommerce_cart_shipping_method_full_label', 'sv_shipping_method_estimate_label', 10, 2 );

It works with the free_shipping and flat_rate shipping methods, but not for European deliveries (outside Germany).
What am I doing wrong?
How to display the correct date range for European countries (outside Germany)?

A: You don't really need to target your shipping methods, but instead customer shipping country:
add_filter( 'woocommerce_cart_shipping_method_full_label', 'cart_shipping_method_full_label_filter', 10, 2 );
function cart_shipping_method_full_label_filter( $label, $method ) {
    // The targeted country code
    $targeted_country_code = 'DE';

    if( WC()->customer->get_shipping_country() !== $targeted_country_code ){
        $days_range = '5-7'; // International
    } else {
        $days_range = '3-5'; // Germany
    }
    return $label . '
' . sprintf( __("Lieferzeit %s Werktage"), $days_range ) . '';
}

Code goes on function.php file of your active child theme (or active theme). Tested and works.


Q: Display notifications on a particular time I would like to display notification on a particular time and daily routine (i.e at 8'o clock morning). I am using broadcast receiver, alarmmanager to display notifications.
But the problem is, I am not getting the notifications displayed on mobile.
I've added wake lock permissions in manifest file also. Help me please
Thank you
MainActivity.java
public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 8);
    calendar.set(Calendar.MINUTE, 00);
    calendar.set(Calendar.SECOND, 0);

    Intent notificationmassage = new Intent(getApplicationContext(),NotificationClass.class);

  //This is alarm manager
  PendingIntent pi = PendingIntent.getService(this, 0 , notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT);
  AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
  am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
          AlarmManager.INTERVAL_DAY, pi);

  Toast.makeText(this, "Start Alarm", Toast.LENGTH_LONG).show();

}

NotificationClass.java
public class NotificationClass extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
                new Intent(context, MainActivity.class), 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                                                .setSmallIcon(R.drawable.ic_launcher)
                                                .setContentTitle("Text1")
                                                .setContentText("Text2 ");
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setDefaults(Notification.DEFAULT_SOUND);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager ;
        mNotificationManager= (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1,mBuilder.build());

    }
}

manifest:
<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="21" />

<uses-permission android:name="android.permission.WAKE_LOCK"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name=".NotificationClass">
        </receiver>
</application>

UPDATE: - now the issues was when ever I open the Application notification arises. For Ex: Alarm Set to 8.AM, whenever I open the app after 8 AM,the notification arises..even though the current time is > 8 AM. How to solve that?

A: In your activity Replace following
    PendingIntent pi = PendingIntent.getService(this, 0, notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT);

with
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT);

A:      public void getNotification(Context context,String Message){
          int icon = R.drawable.appicon;
            int when =(int) System.currentTimeMillis();
            NotificationManager notificationManager = (NotificationManager)
                    context.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notification = new Notification(icon, Message, when);

            String title = context.getString(R.string.app_name);

            Intent notificationIntent = new Intent(context, MainActivity.class);

            // set intent so it does not start a new activity
             notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent intent =PendingIntent.getActivity(context, 0, notificationIntent, 0);
            notification.setLatestEventInfo(context, title,Message, intent);
            notification.flags |= Notification.FLAG_AUTO_CANCEL;

            // Play default notification sound
            notification.defaults |= Notification.DEFAULT_SOUND;

            // Vibrate if vibrate is enabled
            notification.defaults |= Notification.DEFAULT_VIBRATE;
            notificationManager.notify(0, notification);

    }


Q: Show records of a particular year in one page <?php
$hostname = "localhost";
$user     = "root";
$password = "";
$dbname = "abcd";

$conn = new mysqli($hostname, $user, $password, $dbname);
$sql="SELECT YEAR(date) as year from events GROUP BY year";
        $row2 = mysqli_fetch_array(mysqli_query($conn,$sql));
        $result2 = $conn->query($sql);
$eyear=$row2['year'];

$year="2017";

for ($counter = 1; $counter <=5; $counter++){
    echo'
'.$year.'
';
    $year--;
}

?>

I want to retrieve records of separate years and display results for a particular year in one page


Q: Failing data insert in php mysql I need to add records into the table 'writings'. As you can see in the code below, the failure leds to the message data insert failed.
I've already tried to change everything that  online forums adviced but it didnt help. All the program outputs is data insert failed and thats all. When I tried to add mysql_errno, it gave error code 0, which,as I remember, means that operation was successful.
The main code:
<?php
include 'dbcon.php';
$Title=$_GET['Title'];
$TaskID=$_GET['TaskID'];
$uid=$_GET['uid'];
$Text=$_GET['Text'];
$Date=$_GET['Date'];
$result=mysqli_query($MySQLiconn,"insert into 'writings'(uid,TaskID,Date,Text,Title, comment) values('$uid','$TaskID','$Date','$Text','$Title','')");
if ($result) {
    echo "Successfully added.
";
} else {
    echo "Data insert failed

";
}

The file DBcon
<?php
     $DB_host = "localhost";
     $DB_user = "root";
     $DB_pass = "";
     $DB_name = "web";

     $MySQLiconn = new MySQLi($DB_host,$DB_user,$DB_pass,$DB_name);

     if($MySQLiconn->connect_errno)
     {
         die("ERROR : -> ".$MySQLiconn->connect_error);
     }

A: Try this:
$sql = "INSERT INTO writings (uid, TaskID, Date, Text, Title, comment)
VALUES ('$uid','$TaskID','$Date','$Text','$Title','')";

$result = mysql_query( $sql, $MySQLiconn );
if(! $result )
{
  die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";


Q: Tracker.autorun not working inside componentDidMount of react Tracker.autorun not working inside componentDidMount of react when I specify the projection (fields) for output. But the same works when I dont have any projection on mongo query.
This works:
Meteor.subscribe('quotes');
        this.quotesTracker = Tracker.autorun(() => {
            const quotes = Quotes.find(
                {instrument_token: 12374274},
                {
                    sort: {timestamp: 1},
                    limit: 5000
                }
            ).fetch();

This doesnt work
Meteor.subscribe('quotes');
    this.quotesTracker =Tracker.autorun(() => {
            const quotes = Quotes.find(
                {instrument_token: 12374274},
                {
                    fields: {
                        last_price: 1,
                        timestamp: 1,
                                           },
                    sort: {timestamp: 1},
                    limit: 5000
                }
            ).fetch();

What am I missing here?

A: I don't think Meteor's tracker works well with ReactJS, as their mechanism of re-render is different.
You might want to use this package.
https://github.com/meteor/react-packages/tree/devel/packages/react-meteor-data
You can use it like so.
import { Meteor } from 'meteor/meteor';
import { mount } from 'react-mounter';
import { withTracker } from 'meteor/react-meteor-data';
import { IndexPage } from "./index-page";

FlowRouter.route('/', {
    action: () => {
        mount(IndexPageContainer, {});
    }
});

export const IndexPageContainer = withTracker(() => {
    Meteor.subscribe('whatever');
    return {
        Meteor: {
            collection: {
                whatever: Whatever.find().fetch()
            },
            user: Meteor.user(),
            userId: Meteor.userId(),
            status: Meteor.status(),
            loggingIn: Meteor.loggingIn()
        }
    };
})(IndexPage);

Where IndexPage is your actual component.
You can then access the db by this.props.Meteor.collection.whatever.find()


Q: Running PHP - when using a node instance and port I'm running an application using nodejs and it's listening on port 8000, so my web url bar is ip:8000. I have an ajax call to a php file:
    $.ajax({
    url: './chat/store.php',
    type: 'post',
    data: {message: message},
    error: function () {
        console.log('Store not working...');
    }

but the php won't run because were running inside the node instance, so is there anything I can do to so that php runs while accessing the ip:8000 url?

A: Simple way: You could call the CMD version of php from inside node and return the value via node.
Hard way


Q: Accessing MJPEG Stream .net core I am trying to access a mjpeg stream through my .net core app. It seems AForge.Video is not compatible with .net core.
Is there any lib / coding example available how to access a video stream and get single images out of it? Is there any possibility to get Aforge running with .NET core?
private MJPEGStream stream = null;

        public void initRecorder(RecorderUnit unit)
        {
            stream = new MJPEGStream(unit.getAdress());
            stream.NewFrame += stream_newFrame;
            stream.VideoSourceError += stream_error;
        }
        private void stream_newFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();
        }
        private void stream_error(object sender, VideoSourceErrorEventArgs eventArgs)
        {
        }

A: I've had good success using FFmpeg wrappers in C# in times gone by. Here is one that I've used: https://github.com/Ruslan-B/FFmpeg.AutoGen . It takes some work to master the FFmpeg compilation process, which is typically done via cross-compile from Linux, and is typically a necessary part of this. It also takes some work to understand the FFmpeg API. There are a lot of options and steps to extracting frames, and some difficulties in making it performant, especially the display of the extract frames. This project won't be as easy as you were hoping; however, you will have the full FFmpeg power at your fingertips when done.


Q: Using python loop to change part of variable name within function (e.g. inserting different number at end) Updated question in Edit II
I am running a regression model. For that model, I want to test a large set of values in one specific part of the function and then run the model and all following functions.
E.g.
alpha = ['1', '2', '3']

for a in alpha:
    oddsvar = 'odds_all' + a
    result = 'result_all' + a
    norm_odds = 'norm_odds' + a
    pos_norm_odds = 'pos_norm_odds' + a

    oddsvar = mba263.odds_ratios(result)['Odds ratios']
    norm_odds = numpy.power(oddsvar, std_all)
    pos_norm_odds = norm_odds
    pos_norm_odds[pos_norm_odds<1]=1/pos_norm_odds[pos_norm_odds<1]
    pos_norm_odds.sort_values(ascending=False)
    print(pos_norm_odds)

When I first define oddsvar (and the other variables) they just contain a string. I want that string to be used in the rest of the function to either be a variable name or pull data from a different part of my code.
For alpha = 1 the handwritten code would look like this:
odds_all1 = mba263.odds_ratios(result_all1)['Odds ratios']
norm_odds_all1 = numpy.power(odds_all1, std_all)
pos_norm_odds_all1=norm_odds_all1
pos_norm_odds_all1[pos_norm_odds_all1<1]=1/pos_norm_odds_all1[pos_norm_odds_all1<1]
pos_norm_odds_all1.sort_values(ascending=False)

I have been trying (and searching) but so far couldn't find a solution that works for me.
Edit:
Rewording my question: I am trying to define a name in the first half by making
oddsvar = 'odds_all' + a -->> result should be e.g. odds_all1

Then I want to use the new name "odds_all1" and have it be the result of the equation on the right. What I can't figure out in the code is, how to have
oddsvar = mba263.odds_ratios(result)['Odds ratios']
... translated to ...
odds_all1 = mba263.odds_ratios(result_all1)['Odds ratios']

So that after the function has run, I can call the variable "odds_all1" and it gives me the whole list of odds for my logistic regression with alpha = 1.
I see that I can solve the first half with a dictionary (thanks @Teh), however, that approach doesn't seem to work for the argument within the function.
Edit II:
alpha= ['1', '2', '3']
for a in alpha:
    d = {} #odds_all dict
    e = {a: 'result_all' + a} #result_all dict
    f = {} #norm_odds dict
    g = {} #pos_norm_odds dict

    d['odds_all' + a] = mba263.odds_ratios(e[a])['Odds ratios']
    f['norm_odds' + a] = numpy.power(d['odds_all' + a], std_all)
    g['pos_norm_odds' + a] = e['norm_odds' + a]
    g['pos_norm_odds' + a][g['pos_norm_odds' + a]<1]=1/g['pos_norm_odds' + a][g['pos_norm_odds' + a]<1]
    g['pos_norm_odds' + a].sort_values(ascending=False)
    print(g)

Thank you for the help so far. With the dict approach I was able to solve the left side of the equation.
However, the "mba263.odds_ratios(e[a])" still yields an error (AttributeError: 'str' object has no attribute 'params').
I have "result_all1" defined as a variable name elsewhere, but combining result_all and the alpha can only be done as a string.
Can I switch it back from being a string to being a name within the dict?

A: This is just a guess on my part, but I found the exec() to run a command, and you might look that up.  You could probably build a string with "global {}" or set it to a throw away value and fill in your built name, and then run the string with exec([stringname]).
Here's just a test I ran from the command prompt in python.
myval = "test1"
mystr = "global " + myval
exec(mystr)
print(mystr)
global test1
print(type("test1"))
<class 'str'>

Hope this helps you.  Good luck with your program!
Did you try something like this after your first setting lines?
temp_str = "global " + oddsvar
exec(temp_str)

Again, I'm just guessing.  I hope you can get this to work like you need.  For the other set of values, you might try building a string, and then using the exec on that.  Something like this
temp_str = oddsvar + "mba263.odds_ratios(result)['Odds ratios']"
exec(temp_str)


Q: OpenCV Assertion Failed with SolvePnP I'm trying to use solvePnP in a C++ program that detects a chessboard in a video stream. Every time the calibration finishes, I try to run solvePnP, but I keep getting errors that I think are related to the translation and rotation vectors.
This is the error:
The error
This is my code:
    #include <cstdio>
    #include <cstdlib>
    #include <string>
    #include <iostream>
    #include <fstream>

    #include <opencv2/core/core.hpp>
    #include <opencv2/imgproc/imgproc.hpp>
    #include <opencv2/calib3d/calib3d.hpp>
    #include <opencv2/highgui/highgui.hpp>

    using namespace cv;
    using namespace std;

    //Global variables
    vector<vector<Point2f> > corner_list;
    vector<vector<Point3f> > point_list;
    vector<Mat> rotation_vecs, translation_vecs;
    int i = 0;
    bool calibMode = true, drawMode = false, drawMode2 = false, camMatrixInit = false, calibrated = false;
    Mat originalCameraMatrix, cameraMatrix, distCoefficients, frame, gray, rvec, tvec;

    //Function declarations
    vector<Point3f> genWorldPoints(int cols, int rows);
    void printCameraMatrix();
    void printDistCoeff();
    void printRotVecs();

    /*Generates the world points (0, 0, 0), (1, 0, 0), etc. for the camera calibration.*/
    vector<Point3f> genWorldPoints(int cols, int rows){
        vector<Point3f> ret;

        for (int i=0; i<rows; i++) {
            for (int j=0; j<cols; j++) {
                int tempi = i*(-1);
                ret.push_back(Point3f((float)j, (float)tempi, 0.0));
            }
        }

        return ret;
    }

    /*Print the camera matrix*/
    void printCameraMatrix(){
        cout << "Original Camera Matrix" << endl << originalCameraMatrix << endl;
        cout << "Current Camera Matrix" << endl << cameraMatrix << endl;
    }

    /*Prints the distortion coefficients*/
    void printDistCoeff(){
        cout << "Distortion Coefficients:"<< endl << distCoefficients << endl;
    }

    int main(int argc, char *argv[]){
        VideoCapture *capdev;

cameraMatrix = Mat::eye(3, 3, CV_64F);
distCoefficients = Mat::zeros(8, 1, CV_64F);

// open the video device
capdev = new VideoCapture(0);
if (!capdev->isOpened()) {
    printf("Unable to open video device\n");
    return(-1);
}

namedWindow("Video", 1);

bool found;

*capdev >> frame;

rvec = Mat::zeros(3, 1, CV_64F);
tvec = Mat::zeros(3, 1, CV_64F);

//Initialize camera matrix
cameraMatrix.at<double>(0,2) = (frame.size().width)/2;
cameraMatrix.at<double>(1,2) = (frame.size().height)/2;

cameraMatrix.copyTo(originalCameraMatrix);

printCameraMatrix();

for(;;){
    *capdev >> frame;

    if (!found) {
        imshow("Video", frame);
    }

    Size patternsize(9,6);

    vector<Point2f> corner_set;
    vector<Point3f> point_set;

    int code = waitKey(10);

    cvtColor(frame, gray, CV_BGR2GRAY);

    found = findChessboardCorners(gray, patternsize, corner_set, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS);

    //Code to add a calibration frame
    if (found && calibMode) {
        cornerSubPix(gray, corner_set, Size(11, 11), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1));
        drawChessboardCorners(frame, patternsize, Mat(corner_set), found);

        //s key press
        if (code == 115){
            printf("Adding calibration frame\n");
            printf("Number of corners found: %lu\n", corner_set.size());
            printf("Point 0 x: %f\ty: %f\n", corner_set[0].x, corner_set[1].y);

            //Add the corner set
            corner_list.push_back(corner_set);

            //Generate point set
            vector<Point3f> point_set = genWorldPoints(9,6);

            //Add point set to point set list
            point_list.push_back(point_set);

            //Save the image
            string filename = "../data/images/p4_calib_image_"+to_string(i)+".jpeg";
            imwrite(filename, frame);

            //if there are more than 5 saved calibration images, run calibration procedure
            if (i>4) {

                //Calculate the reprojection error by running calibrateCamera
                double rpe = calibrateCamera(point_list, corner_list, frame.size(), cameraMatrix,
                                             distCoefficients, rotation_vecs, translation_vecs,
                                             CV_CALIB_FIX_ASPECT_RATIO | CV_CALIB_FIX_K4);

                //Print the camera matrix
                printCameraMatrix();
                printDistCoeff();

                //Print the reprojection error
                cout << "Reprojection error: " << rpe << endl;

                calibrated = true;
            }

            //Increment i
            i++;
        }

        imshow("Video", frame);
    }

    else if (found && drawMode){
        cout << "Draw mode" << endl;
        bool solved = solvePnP(point_list, corner_list, cameraMatrix, distCoefficients,
                               rvec, tvec);
                               //rotation_vecs.front(), translation_vecs.front());
    }

    else if (found && drawMode2){
        cout << "Draw mode 2" << endl;
        bool solved = solvePnP(point_list, corner_list, cameraMatrix, distCoefficients,
                               rvec, tvec);
                               //rotation_vecs.front(), translation_vecs.front());
    }

    //Switching between drawing modes
    if (calibrated && code == 49) {
        calibMode = false;
        drawMode2 = false;
        drawMode = true;
    }
    else if (calibrated && code == 50){
        calibMode = false;
        drawMode = false;
        drawMode2 = true;
    }
    //Switch back to calibration mode
    else if (calibrated && code == 51){
        drawMode = false;
        drawMode2 = false;
        calibMode = true;
    }

    if (code == 27) {
        printf("Terminating\n");
        delete capdev;
        return(0);
    }
}

capdev = new VideoCapture(0);

printf("Terminating\n");
delete capdev;

return(0);
    }

Please excuse the indentation...

A: The problem is that sovlePnP requires vector<Point2/3f> as input, instead of vector<vector<Point2/3f> >. In your code, "point_list" is vector<vector<Point3f> >, and "corner_list" is vector<vector<Point2f> >.
The documentation of solvePnP can be found here: http://docs.opencv.org/3.0-beta/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html


Q: Convert React Components into web Components Want to convert existing react components into isolated web components in which we share data using props and custom events and also theme(styling) was set according to the props we share . Like if we share theme=light , web Component theme should be default and same is done for dark theme.
I tried many way but not find the correct one.


Q: Looking for any way to transfer file from PPC to PC i looking for any way to transfer file from PPC to PC - and from PC to PPC ,
i dont want to use WebService, and if i use RAPI i need that in the PC will be any program - and i dont want
(i dont want that in the PC will be any of my program)
how i can do it ?
thank's in advance

A: You're going to need to be more specific -- the way the question is now it's basically impossible to determine what you're after.
Do you need to transfer a file from a Windows Mobile handheld to a Windows PC?  Over what type of connection (are they on the same 802.11 network) ?
You need more details or no one will be able to even attempt to help you.

A: So, if what I gather is correct, you want to plug a device with your app on it into a PC and then be able to push files to the PC from the device without having to install anything over on the PC.  Is that correct?  If so, the next question is are you insane?
It's not possible, and for very good reason.  You don't see any potential security problems with being able to just plug a device into a PC and push files up to the PC without the user having to explicitly have installed something to receive that data?  I could write a simple attack app that would fill up the PC's hard drive in about 5 minutes.

A: A vanilla version of this is to just use the Active Sync synchronization folders. If you on the device save a file to the device synch folder, then Active Sync will move it over to the PC synch folder automatically.


Q: Pass local variable to create.js.erb for an iteration in an iteration I have a Post and a Comment model, while a post can have multiple comments and a comment belongs to a post (and a user).
I am iterating through all Posts by doing @posts.each do |d|, which is not a big deal. Also i am iterating through all the comments of a Post by d.comments.each do |comment|. No big deal too.
Ive setted up a create.js.erb to make my app a bit more dynamic and to instantly display the comment you created under a post. While my form is working fine, i have troubles setting up the create.js.erb which is giving me a NameError - undefined local variable or method 'comment' for #<Class:> Did you mean?  @comment: when submitting the forms content. After reloading the page the comment is added up, but i would like to have an instant update like a single page app would behave. i have never worked with ajax before.
I would be able to solve the whole situation if i would just display the comments on a separate posts#show view but since i am iterating through every post on the index page and want to display every comment of every post and also update the comments async i just cant figure out how to do that.
How do I create the desired behavior?
Sorry if my question is asked kinda wonky.
comments_controller.rb
  def create
    @user = current_user
    @comment = Comment.new(comment_params)
    @comment.user_id = @user.id

    respond_to do |format|
      if @comment.save
        format.js {}
        format.html { redirect_to root_path, notice: 'Comment added' }
        format.json { render :show, status: :created, location: @comment }
      else
        format.html { redirect_to root_path }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

posts/index.html.erb
<% @posts.each do |d| %>
  <%= d.content %>

  <div class="comment-list">
    <%= render partial: "comments/comment", collection: d.comments %>
  </div>
<% end %>

comments/_comment.html.erb
<%# d.comments.reverse.each do |comment| %>
  <%= comment.content %>
<%# end %>

create.js.erb
$(".comment-list").append("<%= j render partial: "comments/comment" %>");

A: $(".comment-list").append("<%= j render partial: "comments/comment" %>");

Replace above code with
$(".comment-list").append("<%= j render partial: "comments/comment", locals: {comment: @comment} %>");


Q: how to calculate recall fast and correct with duplicate document id's python 2.7 I have two tsv data files (gold and results) with four columns and I would like to calculate the recall score. Here is the format of the gold file:
(doc1)  173 174 mike
(doc2)  189 194 sara
(doc2)  189 194 mike
(doc2)  200 207 car

format of the resluts file:
(doc1)  173 174 mike
(doc2)  189 194 mike
(doc2)  200 207 car

and here is my code:
from __future__ import division
def eval():
        tp=0 #true positives
        fn=0 #false negatives
        gold=[]
        results=[]

        with open('/path/to/gold.tsv', 'rb') as goldFile, open('/path/to/results.tsv', 'rb') as f:
            for l in goldFile:
                parts = l.decode('utf-8').split('\t')
                try:
                   gold.append((parts[0], parts[3]))
                except:pass

            for line in f:
                cols = line.decode('utf-8').split('\t')
                try:
                   results.append((cols[0], cols[3]))
                except:pass

        for i,j in gold:
            doc = []
            for docid in results:
               if results[0] == i:
                  doc.append(docid)

            for k, v in doc:
                if j == v:
                    tp += 1
                    gold.remove((i,j))
                    results.remove((i,j))
                    continue
            gold.remove((i,j))
            fn += 1

        return float(tp)/(tp+fn)

    print(eval())

The output is:
0.0

Recall should be 0.75 in the above case, what am I doing wrong? And how to calculate more efficiently? I tried with dictionaries but since I have duplicate documents id's that is not possible. I'd really appreciate any guidance.
Thanks in advance.


Q: excel show/hide group based on combobox selection I need some help to figure out how to unhide/hide a group based on an activeX combo box selection.
I currently have two groups (group_1 and group_2) and a combobox (activeX) with two selections (2021-2022 and 2022-2023).
When 2021-2022 is selected from the drop down, I want group_1 to be unhidden (it is hidden by default).
When 2022-2023 is selected from the drop down, I want group_1 to be hidden and group_2 unhidden (it is hidden by default).
I am very new to VBA and have tried to put some code together for the first group and drop down selection option, but I have had no luck.
Private Sub ComboBox1_Change_2()
    Select Case ComboBox1.Text
        Case "2021-2022"
            With ActiveSheet.Shapes("group_1")
                If .Visible = False Then .Visible = True Else .Visible = False
End With
End If
End Sub

Is this something that can be done?

A: Try this:
Private Sub ComboBox1_Change()
    Dim txt
    txt = ComboBox1.Text
    With Me 'assuming this is in the worksheet code module
        .Shapes("group_1").Visible = txt = "2021-2022"
        .Shapes("group_2").Visible = txt = "2022-2023"
        .Shapes("group_3").Visible = Len(txt) > 0 'any option selected
    End With
End Sub


Q: Getting TypeError trying to open() a file in write mode with Python I have a Python script that in my mind should:

*

*Open a file

*Save its content in a variable

*For each line in the variable:

*

*Edit it with a regular expression

*Append it to another variable

*Write the second variable to the original file

Here is a MWE version of the script:
# [omitting some setup]

with open(setFile, 'r') as setFile:
    olddata = setFile.readlines()

newdata = ''

for line in olddata:
    newdata += re.sub(regex, newset, line)

with open(setFile, 'w') as setFile:
    setFile.write(newdata)

When I run the script I get the following error:
Traceback (most recent call last):
    File C:\myFolder\myScript.py, line 11, in <module>
        with open(setFile, 'w') as setFile:
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper

As far as I can understand, Python is complaining about receiving the setFile variable as an argument of open() because it isn't of the expected type, but then why did it accept it before (when I only read the file)?
I suppose that my mistake is quite evident but, as I am a neophyte in Python, I can't find out where  it is. Could anyone give me a help?

A: just curious why you are using the same variable name for your file and then as your filehandler and then again in your next with function.
_io.TextIOWrapper is the object from your previous open, which has been asssigned to the setFile variable.
try:
with open(setFile, 'r') as readFile:
    olddata = readFile.readlines()
newdata = ''
for line in olddata:
    newdata += re.sub(regex, newset, line)
with open(setFile, 'w') as writeFile:
    writeFile.write(newdata)


Q: Breaking on a deadlock between multiple startup projects in Visual Studio I have multiple startup projects in my client/server solution. The server is a Console app and the client is a WinForms app. The server/console is launched first in case that matters.
Now there is a deadlock caused by some synchronization client-side code that blocks the server. Thread synchronization is done using simple lock statements.
When the deadlock occurs, both apps freeze of course and hitting pause/break in VS only breaks the server app, not the client. There are two questions here:

*

*How could I choose which project to break out of multiple start up projects?

*If a lock statement is stuck in a deadlock, is there a way to find out which line of code has a current lock on that object?

A: I think your best solution would be to debug your client and server in separate instances of visual studio and setting startup projects accordingly.
As for the second question, I normally set a guid and output on create and release of a lock. to see if this is happening.  If it is, I set breakpoints and debug and look at the stack to see where on the calls are coming from. You may be able to output System.Environment.StackTrace to a log to get this information, but I've ever attempted it.

A: You can use 2 Visual studios. One starting the console, one starting the server
I Would check if you really need a lock statement.
What do you want to lock ?
Do you always need a exclusive lock ?
Or are there some operations which can happen in parallel and only some which are exclusive ?
In this case you could use the ReaderWriterLockSlim
This can reduce the risk of deadlocks.


Q: HTML5  tag as container bad for SEO? I'm trying to use the  tag in HTML5 more as a container as this tag can now have block elements as children, example:
before (valid XHTML 1.1)

      article title

      text

      read more

after (valid HTML5)

      article title

      text

      read more

Does this new way of markup have any effects for SEO?

A: OK, removing pure semantics from your question (which, in my mind, does have a material impact on deciding on implementing your chosen method) and concentrating on pure "SEO" value and impact:
The first example needs to be qualified more, as if we take your example as literal, then you are linking to the same page.html 3 times. Google (specifically) only takes the link anchor value from the 1st link to any page that it comes across, so - the value for the first example is only extracted from that first link. The 2nd link (using an IMG tag with an ALT attribute as the anchor value), and the 3rd link using read more as the anchor value are effectively "ignored". It's important that other signals are used to supplement the first link's true intended value, such as surrounding text, images etc.
The 2nd example (HTML5), wraps all of that semantic/surrounding content up to make the effective 'anchor' value from which search engines will derive the link's intended meaning, and then as a consequence, the meaning of the destination page of the link.
Using an anchor tag as a containing wrapper for content that contains additional emphasis (the H tag), an image and an additional div only increases the difficulty that a search engine has to decipher the intended meaning of the link so it can associate it with the destination page.
Search engines (and Google predominantly) are constantly improving their crawling ability to enable better algorithmic parsing and processing of the HTML. Apart from emphasis signals (which are very low), Google mostly ignores the mark-up. The exception is of course links - so making an effort to simplify the parsing/processing by providing clear signals as to a link's anchor text is the safest way forward. Expecting them to understand all of the differences of HTML3, vs HTML4, vs HTML5 and all of the transitional, strict and other variations of each, is probably expecting too much.
TL;DR
Possibly, but only in terms of true link value.

A: As far as i know in the second way is not bad in anyway in term of seo But first may be slightly better as the titles,images are more closely linked to link.

Q. But better by how much?
A. May be not too much


Q: how to pass pointer to a method as another method argument All!
I have some class hierarchy
class A {public: virtual void foo(int, T*) = 0; virtual void foo1(int, T*) = 0;};
class B : public A {public: void foo(int, T*) override; void foo1(int, T*) override;};
class C : public B {public: void foo(int, T*) override; void foo1(int, T*) override;};

In client code
class D{void client_foo(A* pA, bool, T*);};
void D::client_foo(A* pA, bool b, T* pT)
{
    if (b) pA->foo(1050, pT);
    else pA->foo1(5010, pT);
}

I want to introduce new function void D::client_helper(???) which will achieve pA, int value, pT and pointer to method of class A to be called.
So, D::client_foo(...) could be rewritten as:
void D::client_foo(A* pA, bool b, T* pT)
{
    if (b) client_helper(pA, 1050, pT, std::mem_fn(&A::foo));
    else client_helper(pA, 5010, pT, std::mem_fn(&A::foo1));
}

the question is: what signature should D::client_helper() have?

A: Since both A::foo and A::foo1 have the same signature, there's no need for std::mem_fn, or another abstraction, just have client_helper take a plain pointer to member function of A.
void client_helper(A* pA, int i, T* pT, void(A::*memfn)(int, T*))
{
    (pA->*memfn)(i, pT);
}

And call it as
void client_foo(A* pA, bool b, T* pT)
{
    if (b) client_helper(pA, 1050, pT, &A::foo);
    else client_helper(pA, 5010, pT, &A::foo1);
}

Live demo

A: For passing functions as arguments, you have std::function.

A: I've used std::function<ret_type(arg_1)> and std::bind instead of std::mem_fn
e.g.
client function:
void client_helper(std::function<void (T*)> fnFoo, T* pT)
{
     nfFoo(pT);
}

call of the function:
usign namespace std::placeholders;
A* pA;
T* pT;
client_helper(std::bind(&A::foo, pA, 1050, _1), pT);