text:
Q: PHP not showing one variable on WordPress page I am trying to add text in an image overlay. The page shows all other variables for the correct posts. But the status variable only shows the first text on all images e.g. NEW ARRIVAL
Variable
$status = 'NEW'; $status2='SOLD'; $status3='HOT DEAL';

Display Code

<?php $status = get_field('status'); if ($status='NEW') echo 'NEW ARRIVAL'; else { the_field('status');} ?>

I have tried other code like,
echo ('$status')

etc
<?php
unset($bed); unset($type); unset($salerent); unset($pricemin); unset($pricemax); unset($status);
$salerent = 'sale';
$salerent2 = 'rent';
$type = 'villa'; $type2='condo'; $type3='house'; $type4='land';
$status = 'NEW'; $status2='SOLD'; $status3='HOT DEAL';
$bed = 'all';
$minprice='0';
$maxprice='999999999';
if ($bed=='all') {$bed1=1;$bed2=2;$bed3=3;$bed4=4;$bed5=5;$bed6=6;$bed7=7;$bed8=8;$bed9=9;$bed10=10;}
if ($salerent=='rent'){
$p0text="Price (per month)";
$p1text="0 - 10,000";
$p2text="10,000 - 25,000";
$p3text="25,000 - 40,000";
$p4text="40,000 - 80,000";
$p5text="80,000+";
}
else{
$p0text="Price";
$p1text="0 - 3 mill";
$p2text="3 - 6 mill";
$p3text="6 - 10 mill";
$p4text="10 - 20 mill";
$p5text="20+ mill";
}
?>
<?php wp_head(); ?>

<?php include( get_template_directory() . '/menu.php'); ?>

/star property
 Villas, Condos & Houses for Sale & Rent in Hua Hin

    <form id="searchurl" method="POST" action="http:// .com/search-result/?">
    Search:
    <select class="custom-select mysearch" id="salerent" name="salerent">
    <option value="sale" <?php if($salerent=='sale'){echo "selected";}?>>Sale</option>
    <option value="rent" <?php if($salerent=='rent'){echo "selected";}?>>Rent</option>
    </select>

    <select class="custom-select mysearch" id="type" name="type">
    <option value="villa" <?php if ($type=='villa'){echo "selected";}?>>Villa</option>
    <option value="condo" <?php if ($type=='condo'){echo "selected";}?>>Condo</option>
    <option value="house"<?php if ($type=='house'){echo "selected";}?>>House</option>
    <option value="house"<?php if ($type=='land'){echo "selected";}?>>Land</option>
    <option value="house"<?php if ($type=='commercial'){echo "selected";}?>>Commercial</option>
    </select>

    <select class="custom-select mysearch" id="bed" name="bed">
    <option value="all">Bedrooms</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    </select>

    <select class="custom-select mysearch" id="pricerange" name="pricerange">
    <option id="p0" value="all"><?php echo $p0text;?></option>
    <option id="p1" value="1"><?php echo $p1text;?></option>
    <option id="p2" value="2"><?php echo $p2text;?></option>
    <option id="p3" value="3"><?php echo $p3text;?></option>
    <option id="p4" value="4"><?php echo $p4text;?></option>
    <option id="p5" value="5"><?php echo $p5text;?></option>
    </select>
<input class="col-lg-1 col-md-1 mysearch" type="text" id="searchid" name="searchid" placeholder="#ID/Project" />
<button type="submit" onclick="document.getElementById('searchurl').submit();" id="submitbutton" class="btn btn-primary btn-md">SEARCH</button>
    </form>

New Listings:
 Properties for Sale & Rent in Hua Hin

<?php
$args = array(
    'posts_per_page'    => 6,
    'post__in' => array(22094, 16782, 20898, 19838, 22150, 1442, 1794),
    'post_type'     => 'post',
    'no_paging' => true,
    'order' => DESC,
    'cat'           => 2,
);
// query
$the_query = new Wp_Query( $args ); ?>

<?php if( $the_query->have_posts() ): ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

<a class="listingslink" href="<?php the_permalink(); ?>"><?php the_title(); ?>

<a href="<?php the_permalink(); ?>"><img src="<?php the_field('image_1'); ?>" class="w-100" alt="<?php the_field('image_1_alt'); ?>" title="<?php the_field('area_project'); ?> <?php $type = get_field('type'); if ($type=='Villa') echo 'House'; else { the_field('type');} ?> for <?php the_field('sale_or_rent'); ?> in Hua Hin">**
<?php $status = get_field('status'); if ($status='NEW') echo 'NEW ARRIVAL'; else { the_field('status');} ?>
**

ID #<?php the_field('property_id'); ?>
    <?php $price = get_field('Price'); echo number_format($price, 0, '', ','); ?> baht<?php $saleorrent = get_field('sale_or_rent'); if($saleorrent=='Rent'){echo ' ';} ?>
<?php the_field('living_space'); ?> SQM
<?php the_field('bedrooms'); ?> Beds
    <?php the_field('bathrooms'); ?> Baths

<?php $excerpt = wp_trim_words( get_field('property_description' ), $num_words = 10, $more = '... more' ); echo $excerpt; ?>

<?php endwhile; ?>
<?php endif; ?>

A: Part of your code is...
 if ($status='NEW') echo 'NEW ARRIVAL';

Now you say that it is always showing "NEW ARRIVAL" which would mean that your IF is always TRUE.
What you are doing is assigning $status = "NEW" which will always be true.
Single = is assignment
Double == is checking for equivalence.
So your statement should be...
 if ($status =='NEW') echo 'NEW ARRIVAL';


text:
Q: Conceptually speaking, why does synchrotron radiation arise? First, a bit of background. I'm a chemist who works with synchrotron-based techniques, but I'm focussed on materials analysis rather than synchrotron physics.
I'm struggling to work out where synchrotron radiation (SR) actually comes from. Why does subjecting an electron to radial acceleration cause it to emit photons? I understand, with Bremsstrahlung radiation that the energy from the decelerating particle has to go somewhere. My first thought was that SR may arise from a similar effect, as my understanding is that you do work when you radially accelerate a particle. I reasoned that, since the magnitude of its velocity remains constant, and the magnitude of the kinetic energy (KE) remains constant, SR must result from conservation of energy (i.e. the work done in the radial acceleration is converted into SR). However, I've since read that emission of SR causes the electrons in the storage ring to lose energy. And, this energy must be resupplied by the inclusion of RF cavities in the ring. This would suggest that SR comes from the KE of the electron, not from the work of the magnet on the electron. (On reflection, I can't see how a permanent magnet could "do work".)
So why is SR emitted?
(Please bear in mind, that as a chemist, I have next to no knowledge of relativity, electrodynamics, Maxwell's equations, etc. I'm really just looking for a conceptual understanding. I don't mind a mathematical answer if you can give one without assuming knowledge of such physics. But, I imagine that's unlikely.)
Edit: Any good textbook recommendations would be helpful too. All the books I've read either gloss over the issue or use physics that goes over my head.

A: Conceptually the idea is based on a simple principle: conservation of linear momentum.
Every time a charged particle has to be accelerated, a photon has to be involved. If you want to linearly accelerate a charged particle, you have to shoot photons at its back. If you want to stop a charged particle (decelerate), it has to emit photons in the forward direction: at every emission the charged particle recoils back and slows down.
The circular motion is not much different. The acceleration in this case points towards the center of the circle (centripetal), so the charged particle has to emit a photon outwards, tangentially to the circle, every time it needs to curve. You can imagine it's trajectory not as a perfect circle but as a almost regular polygon with many sides. This means that in circular accelerators the charged particles have to be constantly resupplied with energy.
Now, about the energy transfer from the accelerator to the charged particle, you are perfectly right when you say that a fixed magnetic field doesn't transfer energy, but fortunately any other kind of EM field does. In particular I'd like to quote this page on wikipedia:

While a classical cyclotron uses both a constant guiding magnetic field and a constant-frequency electromagnetic field [...], its successor, the isochronous cyclotron, works by local variations of the guiding magnetic field, adapting the increasing relativistic mass of particles during acceleration.

As you can see, the magnetic field is variable and this means that there is also an electric field that can accelerate the charged particles.

A:
This would suggest that synchrotron radiation comes from the kinetic energy of the electron, not from the work of the magnet on the electron.

This is absolutely correctly described, now it remains to explain the inner mechanism of the phenomenon.
A magnetic field deflects a moving electron sideways (Lorentz force).  To answer your question, it would be helpful to explain how this deflection occurs in detail. But the fact is that there is no attempt to explain this phenomenon, which has been known for 130 years. Meanwhile, the inner mechanism of this deflection must have something to do with both the movement of the electron and the external magnetic field.
It is often overlooked that the electron not only has a charge, but is also a magnetic dipole. If a moving electron now enters the sphere of influence of the magnetic field, the magnetic dipole of the electron is aligned by the magnetic field. I postulate here that EM radiation (the synchrotron radiation) is emitted at exactly this moment.
Since the EM radiation has a momentum, firstly the

*

*firstly, the alignment of the magnetic dipole is disturbed and

*secondly, the electron is deflected sideways, thereby reducing its kinetic energy.

On reflection, I can't see how a permanent magnet could "do work".

The change in direction is accomplished by converting the kinetic energy of the electrons into radiation. The external magnetic field acts like a spring and constantly realigns the magnetic dipole of the electron.

redpajama_set_name: RedPajamaStackExchange


text:
Q: manage serverside validaton when I use jquery post From razor view I'm sending js object using jquery to the mvc controller. Reason why I do it using jquery post method and not razors form is that I need to manage dynamic input of certain fields. On the view certain fields (inputtextbox) are dynamically added to the view (from 0 - 10) and I manage that solution using js on the page.
 var myJsObj = ...
 $.ajax({
           type: 'POST',
           traditional: true,
           contentType: 'application/json',
           url: '/MyController/SomeAction',
           data: JSON.stringify({ model: myJsObj}),
           success: function () {

           }
 });

On the server side, mvc receives that model and in case of some error I want to return this object back to the view.
[HttpPost]
public ActionResult SomeAction(MyModel model)
{
   if(!ModelState.IsValid)
   {
      ModelState.AddModelError("", "Error occured!");
      return View(model);
   }
   return RedirectToAction("Index");
}

I have inside razor view
Html.ValidationSummary

but since I'm using jquery post I dont know how to receive back to the view and display error like I would use regular razor form. Or if you know better approach to manage dynamically added input boxes on the razor view please post. Any help please.

A: This is what I have done to display errors for dynamic inputs. First off, take a look at this post to give you a better understanding. I have modified my code to better suit my needs, but you can check if it works for your application.
use-asp-net-mvc-validation-with-jquery-ajax.
I would then consume the return result in the ajax post error callback. It returns a code 400 'Bad Request' on validation errors. The validator variable is the form validator object.
error: function (xhr, textStatus, errorThrown) {
     var statusCode = parseInt(xhr.status);
     if (statusCode == 400) {
         var data = $.parseJSON(xhr.responseText);
         var message = "";
         $.each(data, function (i, item) {
             var propertyName = "" + item.key + "";
             if ($("input[name='" + item.key + "']").length > 0) {
                 var errorObj = {};
                 errorObj[item.key] = item.error;
                 validator.showErrors(errorObj);
            }
            else {
                message += "<div>" + item.key + ": " + item.error + "</div>";
            }
        });

        if (message != "") {
            //display message
         }
    }
}

I hope this helps. Good luck.

A: I think you've got a couple of options here:

*

*If you prefer to continue to use an Ajax POST as you've shown above, then you need to take the response from the POST and inject it back into your current HTML document.  For example,

$.ajax({
       type: 'POST',
       traditional: true,
       contentType: 'application/json',
       url: '/MyController/SomeAction',
       data: JSON.stringify({ model: myJsObj}),
       success: function (data) {
           // This is the case where the MVC action found model validation
           // errors, and so it is responding with an HTML document that
           // shows the errors.
           var returnedBodyHtml = $(data).find('body').html();
           $('body').html(returnedBodyHtml);
       }
     });

(That's untested code up there, so you may have to debug a little bit.)  But this code doesn't handle the case where the server responded with a redirect (in the case of successful validation).  So, check out this post for some options there.

*Your other option is to use the standard Form submit.  I know you said you had some dynamically generated input controls on your page, but that doesn't mean that you can't do a Form submit.  You just need to make sure that these dynamically generated  elements have the correct "name" attribute on them, so that their values get mapped appropriately to the Model on the server side action that is accepting the POST.  For example, if your Javascript is dynamically generating an HTML element like this, and inserting it into the form:

<input type="text" name="myDynamicallyGeneratedInput[0]" />
<input type="text" name="myDynamicallyGeneratedInput[1]" />
<input type="text" name="myDynamicallyGeneratedInput[2]" />
<input type="text" name="myDynamicallyGeneratedInput[3]" />

then your Form submit will still work, as long as on the server side, your MyModel class has that corresponding property:
class MyModel
{
    public List<string> MyDynamicallyGeneratedInput {get; set;}
}


text:
Q: Отображение html страницы в юнити игре Нужно отобразить html страницу с сайта в UIView в игре.
Нашол на офф сайте такой вариант:
public class ExampleClass : MonoBehaviour
{
    public string url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
    IEnumerator Start()
    {
        WWW www = new WWW(url);
        yield return www;
        Renderer renderer = GetComponent<Renderer>();
        renderer.material.mainTexture = www.texture;
    }
}

Но это картинка а мне нужно страница с текстом... подскажите как решить проблему.

A: Решил пойти простым путём, так как страницу с текстом в формате html не получилось отобразить, нашол решение для файла .txt
    using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Net;

public Text textView;

    public void Start(){

            string fileContent = new WebClient().DownloadString("http://www.yoursite.com/namefile.txt");

            GUIStyle style = new GUIStyle ();
            style.richText = true;
            textView.text = fileContent;
    }
}

В Unity3D есть Rich Text о существований которого я не знал, на случай если кому ещё понадобится вот док. с офф. сайта Unity Rich Text


text:
Q: javax.ws.rs.ProcessingException: could not find writer for content-type application/x-www-form-urlencoded type I'm sending POST request using "resteasy-client" library in MediaType.APPLICATION_FORM_URLENCODED_TYPE.
Sample Code :
String serviceUrl = "URL";

    ConnectRequest connectRequest = new ConnectRequest();
    connectRequest.setUsername("");
    connectRequest.setPassword("");
    connectRequest.setScope("bearer");
    connectRequest.setGrant_type("");

    Entity<ConnectRequest> entity = Entity.entity(connectRequest,
                MediaType.APPLICATION_FORM_URLENCODED_TYPE);

    ResteasyClient client = new ResteasyClientBuilder().build();
    ResteasyWebTarget target = client.target(serviceUrl);

    Response response = target.request().post(entity);

    System.out.println("RESP : "+response.toString());

Maven Dependencies
    <properties>
    <java.version>1.7</java.version>
    <resteasy.version>3.0.4.Final</resteasy.version>
</properties>
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-client</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jackson-provider</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-servlet-initializer</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>jaxrs-api</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxb-provider</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-multipart-provider</artifactId>
            <version>${resteasy.version}</version>
        </dependency>
</dependencies>

Connection is working fine and sending correct response while
  requesting using POSTMAN

But after requesting using the program it creates error as
Response :

javax.ws.rs.ProcessingException: could not find writer for
  content-type application/x-www-form-urlencoded type

Please help...

A: You can't use a POJO to send application/x-www-form-urlencoded. You need to use the javax.ws.rs.core.Form class.
Form connectRequest = new Form()
    .param("username", "...")
    .param("password", "...")
    .param("client_id")
    ...;

You can also use Entity.form(connectionRequest), which is shorthand so you don't have to use the MediaType.APPLICATION_FORM_URLENCODED_TYPE.

As an aside, see this also for parsing the response. You won't need the dependency. You already have the one for RESTEasy.

A: I created a set of reader/writers you can import that handle automatic binding of form encoding to java objects: https://github.com/exabrial/form-binding it's a little easier than creating an instance of a Form.


text:
Q: row_number partition result wrong I am using ROW_NUMBER to rank countries by sales desc. Query looks like below
SELECT country, SUM(sales) AS sales,
       ROW_NUMBER() OVER (PARTITION BY country ORDER BY SUM(sales) DESC) AS 'rank'
FROM table
GROUP BY country
ORDER BY sales DESC

For some reason the rank is one for all the countries.

A: If you partition by COUNTRY, the row_number reset to 1
SELECT country,
       SUM(sales) AS sales,
       ROW_NUMBER() OVER (ORDER BY SUM(sales) DESC) AS 'rank'
FROM table
GROUP BY country
ORDER BY sales DESC


text:
Q: How to return the value of body inside a promise I'm trying to get the value (which is a binary data of an image) inside the body of a promise that looks like this. And is there a way to turn the binary data into a base64 encode?
"Promise"{
"IncomingMessage"{
    "_readableState":"ReadableState"{...
    },
    "readable":false,
    "_events":[...
    ]{...
    },
    "_eventsCount":4,
    "_maxListeners":"undefined",
    "socket":"TLSSocket"{...
    },
    "connection":"TLSSocket"{...
    },
    "httpVersionMajor":1,
    "httpVersionMinor":1,
    "httpVersion":"1.1",
    "complete":true,
    "headers":{...
    },
    "rawHeaders":[...
    ],
    "trailers":{...
    },
    "rawTrailers":[...
    ],
    "aborted":false,
    "upgrade":false,
    "url":"",
    "method":null,
    "statusCode":200,
    "statusMessage":"OK",
    "client":"TLSSocket"{...
    },
    "_consuming":true,
    "_dumped":false,
    "req":"ClientRequest"{...
    },
    "request":"Request"{...
    },
    "toJSON":[...
    ],
    "caseless":"Caseless"{...
    },
    "body": //binary values here

Now, the code to access them is by console.log(getto) inside an async function
async function getMedia(imgMsgUrl, auth) {
const getImage = {
    url: imgMsgUrl,
    oauth: auth,
};
var getto = get(getImage);
await getto;
console.log(getto);
};

How do I easily access the body by modifying the code inside the async function? And how do I turn it into a base64 encode?

A: I got it to work. Here's the code.
async function getMedia(imgMsgUrl, auth) {
const getImage = {
    url: imgMsgUrl,
    oauth: auth,
};
var getto = get(getImage).then(function(response) {
    let buffer = Buffer.from(response.body);
    let base64 = buffer.toString('base64');
    console.log(base64);
});
await getto;
};

A: Since it the result of get(getImage) is a promise, you can't access the value like you will access a variable.
You can only get the result in an async function using await (like you did above) or perform whatever action you want with it in a callback function passed to Promise.then()
function getMedia(imgMsgUrl, auth) {
  const getImage = {
    url: imgMsgUrl,
    oauth: auth,
  };
  var getto = get(getImage);
  getto.then(result => {
    doSomething(result)
  });
};


text:
Q: How to filter a Stream[Future[A]]-like class by sub-type B<:A? I have this class that manage reception of a stream of asynchronous messages. It has type argument, say A, and I like to implement a function that filter those messages by type, say B<:A
But my first implementation is not working due to type erasure (see example below). Is there a good way to so?
Here is a simplified example of my problem:
package test.filterByType

import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.Future

trait MessageStream[A]{ self =>

  def next(): Future[A]

  def filter[B<:A]: MessageStream[B] = new MessageStream[B]{
    def next(): Future[B] = self.next.flatMap{
      case b: B => Future.successful(b)
      case _    => next()
      }
  }
}

case class MessageStreamImpl[A](msg: IndexedSeq[A]) extends MessageStream[A]{
  private var index = 0
  def next() = {
    index += 1
    Future.successful(msg(index-1))
  }
}

object Main{
  trait A
  case class B(i: Int) extends A
  case class C(i: Int) extends A

  def main(args: Array[String]){
    val msg: IndexedSeq[A] = (1 to 10).map{ i => if(i%2==0) B(i) else C(i) }
    val streamOfA = MessageStreamImpl(msg)
    val streamOfB = streamOfA.filter[B]

    val b: B = Await.result(streamOfB.next(), 1 second)
  }
}

At compilation, I get warning: abstract type pattern B is unchecked since it is eliminated by erasure, and indeed the code does not work. If I execute Main, I get the error:
lang.ClassCastException: test.filterByType.Main$C cannot be cast to test.filterByType.Main$B
Which happens because it does not filter out the first list item C(1)

A: This small adjustment does the trick
import scala.reflect.ClassTag
def filter[B<:A](implicit C: ClassTag[B]): MessageStream[B] = new MessageStream[B]{
    def next(): Future[B] = self.next.flatMap{
        case b: B => Future.successful(b)
        case _    => next()
    }
}

A: I've found an alternative that works:
def collect[B<:A](f: PartialFunction[A,B]) = new MessageStream[B] {
  override def next(): Future[B] = self.next().flatMap { m =>
    if (f.isDefinedAt(m)) Future.successful(f(m))
    else next()
  }
}


text:
Q: Adding an object with dynamically allocated attribute to a vector in C++ I have the following code:
struct Matrix {
    int * data;

    Matrix(int sz) {
        std::cout << this << " constructed" << std::endl;
        data = new int[sz];
        for (int i = 0; i < sz; i++) {
            data[i] = sz;
        }
    }
    ~Matrix() {
        std::cout << this << " destructed" << std::endl;
        delete[] data;
    }
};

int main()
{
    std::vector<Matrix> my_matrices;
    for (int i = 1; i < 3; i++) {
        std::cout << my_matrices.capacity() << std::endl;
        my_matrices.emplace_back(i);
    }
}

This compiles, but gives the following error when I try to run it:
0
0x5642c4882eb0 constructed
1
0x5642c4883308 constructed
0x5642c4882eb0 destructed
2
0x5642c4883350 constructed
0x5642c4883300 destructed
free(): double free detected in tcache 2
Aborted (core dumped)

If I understand it correctly the destructor is called to destruct a memory adress that does not contain a Matrix-object. How is this possible/what am I doing wrong?
I have noticed that it does work when I try to do it like this:
int main()
{
    std::vector<Matrix*> my_matrices;
    for (int i = 1; i < 3; i++) {
        std::cout << my_matrices.capacity() << std::endl;
        my_matrices.emplace_back(new Matrix(i));
    }
    for (int i = 1; i < 3; i++) {
        delete my_matrices[i];
    }
}

But this seems complicated and does not make me understand why the first example did not work. I am not entirely sure whether this causes a memory leak or not.


text:
Q: how to make a conditional in where. SEQUELIZE mysql should fetch all teachers where the value 'search' is found in the coursesOffered array.
table teacher
name   lastName    dob              coursesOffered
juan     perez   2022/10/02     [ 'math', 'science' ]
marcos   smith   2022/10/02     [ 'history', 'literature' ]
Query sequelize
const search = 'math';

const teachers = await Teacher.findAll({
    where: should fetch all teachers where the value 'search' is found in the coursesOffered array.
})

A: You can try JSON_CONTAINS function.
// When you are doing string search, make sure to wrap the search term with "".
const teachers = await Teacher.findAll({
    where: Sequelize.fn('JSON_CONTAINS', Sequelize.col('coursesOffered'), `"${search}"`)
})


text:
Q: If a family of sets $C$ is a subset of a $σ$-algebra $F$, then are the subsets of $C$ in the $σ$-algebra as well? Recently I asked this question
If a set is in a σ-algebra, then are the subsets in the σ-algebra as well?
involving a set in F rather than a family of sets.
Now the question is
Let $A \subseteq F$ where $F$ is a σ-algebra. If $B \subseteq A$, is it true that $B \subseteq F$ ?
My answer would be that if $E \in B$ then $E \in A$ and therefore$E \in F$ $\forall E$. This means $B \subseteq F$.
So am I correct to assume that the claim is correct?

A: Yes, you are correct. You don't need $F$ to be a $\sigma$-algebra. It is always true that if $A \subseteq  F$ and $B \subseteq A$ then $B \subseteq F$. The proof is as you state it (and you have not used that $F$ is a $\sigma$-algebra).


text:
Q: How does one perform multiple non-linear regression? I performed an experiment where I took the heights of plants and measured a number of environmental conditions (air temp, soil temp, lux, air humidity, soil pH, wind) for each of those plants. I want to then determine the effect that these conditions had on plant height. I have used multiple linear regression many times before in R using the form of:
LinearModelTemp<-lm(Height~ AirTemp+SoilTemp+lux+..., data=data)

but I would not expect the response of plants to all these conditions to be linear. How do you perform multiple non-linear regression?
So far the options I have found are non-linear least squares and segmented linear regression. For non-linear least squares I would have to set the parameters of the curve and I have no prior ideas for what these are. Furthermore, I am not aware of being able to perform multiple regression using this format. The other option is segmented linear regression, but again I would have to choose where my breakpoints are. I have some idea for where I would expect these to be but surely choosing these breakpoints will have a significant impact on form of the final regression model.
Is there a standard protocol I can follow when performing this or are there other options that I have not considered?

A: There are a few methods that do what you want, which is to allow functional forms to be flexible.  Probably the best one for your case here however is the additive model (or generalized additive model if your response isn't continuous).
The AM has the form
$$
y = \alpha + X'\beta + \displaystyle\sum_m f_m(Z_m) + \epsilon
$$
where $X$ are variables that you represent linearly as in a parametric model, and the $Z$ are terms that you allow to be flexible.
AMs don't remove all functional form assumptions.  You still have that your terms have an additive effect on the response, which might not be true (interactions can help with some violations of this).  And when they are fit the usual way, they assume that the functions $f_m$ are smooth (so, like, no sharp thresholds).
They are usually fit with a method similar to what you call "segmented linear regression", but modified.  One uses way, way more breakpoints than one thinks one needs, and then lets the data tell them how to "penalize" the coefficients on those breakpoints, so that the function doesn't get too wiggly (or too straight).
Specifically, if the response is continuous, the parameters ($\theta$ $\equiv$ $\beta$ along with the splines that make up each of the $f_z$) can be estimated by
$$
\theta = \left(W'W+\lambda D\right)^{-1}W'y
$$
where $W$ is $X$ along with the data gotten from the basis expansion (the segmenting) of $Z$.  $D$ is a square matrix of dimension $p$ (the number of variables including the spline terms).  In a really simple AM, it is zero on al the off-diagonals, and zero for the $X$'s and $Z$'s, but one for all the spline terms.  $\lambda$ is a vector with different values in the entries associated with the sets of splined terms for each $Z$.  When the entries of $\lambda$ get bigger, the splined terms shrink, and the function $f(Z)$ reduces to the main effect $Z$ (because in this simple example there is no penalty on $Z$ by the way $D$ is constructed).
Choosing $\lambda$ from data is a little more involved, as is much else about AMs and GAMs.  Good books include those by Ruppert, Wand and Carrol ("Semiparametric Regression" -- dated, but easy to read), Wood (introduction to GAMs with R), and the chapter in Hastie & Tibshirani's Intro to Statistical Learning.
While I think there are a few R packages that do GAMs, I've had good luck with gam in mgcv.
Try the following as an example of the kind of output you'd get:
library(mgcv)
m = gam(Sepal.Width~s(Sepal.Length)+s(Petal.Length)+s(Petal.Width)+Species,data=iris)
summary(m)
plot(m,pages=1)

All the above said: GAMs can be kind of a rabbit hole.  If you don't have the time and inclination to learn all this stuff, see if your needs aren't served by including a few polynomial terms.

A: The answer from @generic_user should be very helpful. I just want to suggest ways to minimize the number of variables for which you include truly non-linear terms, and to discuss a bit when to use a nonlinear model function versus polynomial regression.
The relations between the dependent variable and each of the independent variables don't have to be exactly linear for linear regression to work. Changes in the dependent variable with changes in each of the independent variables just have to be well enough represented by linear relations over the range of interest. This is like doing a Taylor expansion of a function and only keeping terms up to first order: sometimes a linear approximation is good enough.
You can do linear regression with non-linearly transformed variables. For example, you already list $pH$ as an independent variable, which can be used directly in linear regression even though it is related logarithmically to the underlying hydrogen-ion activity. Such a non-linear transformation doesn't rule out a linear regression, as the "linear" part of the name only refers to the relation (in this case) between changes in Height and changes in $pH$, regardless of whether you consider $pH$ to have been obtained by a non-linear transformation. That's why regression against polynomials, as suggested by some here, is also linear regression. So for variables which you expect to have a monotonic relation to Height (over the range of your data), an appropriate transformation of an independent variable will typically allow linear regression.
Variables with a peak or a trough in the relation to Height (as you suggest may be the case for temperature) require additional attention, if such a peak or trough occurs within the range of your data. Including polynomial terms in your linear regression can capture such relations (analogous to higher-order terms in a Taylor expansion), but they will be hard to interpret in terms of biological processes. I suspect that in your field there are some general formulas for relations of plant height to temperature, which include as parameters the temperature for peak height and how quickly height drops off with temperature on either side of the peak. If you find such formulas, your analysis can be set up in a way that identifies the peak and drop-off parameter values that best match your data. That may be easier to interpret biologically than a generic polynomial regression.


text:
Q: How can I access the selector field of a By object? I'm using Java, Selenium Webdriver in Eclipse.
I wrote a helper method to wait for an element present, scroll to it, wait for the element to be visible and click it.  Here's what I have:
protected void waitScrollWaitClick(By by, String scroll)
{
    wait.until(ExpectedConditions.presenceOfElementLocated(by));
    getJse().executeScript("$('.mCustomScrollbar#" + scroll + "').mCustomScrollbar('scrollTo',document.querySelector(\"" + by.selector + "\"), {scrollInertia:0})");
    wait.until(ExpectedConditions.visibilityOfElementLocated(by));
    getDriver().findElement(by).click();

Now the issue I'm having is in that second line in the method. I am passing a By object.  This works for the conventional Webdriver methods on lines 1,3,4.  But since we are using a custom scrollbar for our web app, I need to use that JavascriptExecutor class (the getJse()) to scroll on the proper div #id (thus passing in the 'scroll' argument).  To use that JSE I just need the CSS selector, not the whole By object.  If I add a breakpoint and look, the By object contains a 'selector' field that has what I want (in Eclipse there's a red square icon with an 'F' on it), but I can't seem to access it.  I tried with the "by.selector" in the code above, but that is a compile error.
How can use that selector field?  I'm not Java expert, so maybe I'm missing something obvious.  I guess I don't understand why I can stop on a breakpoint, see the By object I created in the Variables tab, expand the By object and see the 'selector' field I want, but just can't access it.

A: The easy answer is that you cannot get the CSS selector from a By type, or even WebElement type. This is because the WebElements themselves are found by the By class. In case the By specified was a xpath there would be no way to populate the CSS selector.
The long answer specifically for your issue, to get the CSS Selector would be to create it using Javascript. An example would be Florent B.'s answer here. However, I didn't tried myself and I have no idea if it works for all cases.
Now, to address the general issue, instead of using document.querySelector use document.getElementById in case your element has an id.
Or by using document.evaluate to get your element by xpath. You can find an example in the answer posted here.


text:
Q: Unable to set pricebook Id in orderitems I am writing trigger "On Insert Of Order(Sales order) copy opportunityLineitems to order line items" I have done everything fine upto my knowledge but when I am inserting order it is showing pricebook not set error.
Thanks In Advance
Trigger Code:-
trigger orderLineCreationSherry on order(after insert)
{
    set<string> strSet = new set<string>();
    list<order> orList = new list<order>();
    list<OrderItem> oliPist=new list<OrderItem>();
    list<opportunity> oppList=new list<opportunity>();

    for(order o:trigger.new){
        strSet.add(o.OpportunityId);
    }
    system.debug('strSet========'+strSet);

    map<string,opportunity> mapOpp = new map<string,opportunity>([SELECT id,Name, (SELECT id,name,Product2Id,Quantity FROM OpportunityLineItems) FROM Opportunity WHERE id in:strSet]);
    system.debug('oppList========='+oppList);

    for(order o:trigger.new)
    {
        List<Order> oderLst = new List<Order>();
        Opportunity opp = mapOpp.get(o.OpportunityId);
        if(opp.OpportunityLineItems.size()!=0){
            for(OpportunityLineItem oli : opp.OpportunityLineItems)
            {
                PriceBook2 pb2Standard =[select Id from Pricebook2 where isStandard=true];
                Id standardPriceBookId = pb2Standard.Id;
                system.debug('standardPriceBookId===========>>>>>>>>>>>>'+standardPriceBookId);
                Id currentProductId=oli.Product2Id;
                system.debug('currentProductId===========>>>>>>'+currentProductId);
                PricebookEntry pbe = [SELECT Id,Product2Id,Pricebook2Id,UnitPrice FROM PricebookEntry WHERE Pricebook2Id =:standardPriceBookId AND Product2Id =:currentProductId AND isActive = true LIMIT 1];
                system.debug('Here Is Pricebook2 ID'+pbe.id);
                system.debug('INsideloop');
                OrderItem od = new OrderItem();
                od.OrderId=o.Id;
                od.Quantity=oli.Quantity;
                od.PricebookEntryId=pbe.Id;
                od.Product2Id=oli.Product2Id;
                oliPist.add(od);
            }
        system.debug('Here Is Field Data=========>>>>>>'+oliPist);
      }
        system.debug('Its Reaching Here');
    }
    if(oliPist.size()!=0){
        system.debug('It Will Be Debuged Now INsert Zone');
        insert oliPist;
    }
}

A: you need two triggers one before insert and one after insert on order.
trigger OrderTriggerBefore on Order (before insert) {

set<Id> OpportunityId = new set<Id>();
for(Order ord :trigger.new) {
    if(ord.OpportunityId != null) {
        OpportunityId.add(ord.OpportunityId);
    }
}
Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>([select Id,pricebook2Id from Opportunity where Id In :OpportunityId]);
for(Order ord :trigger.new) {
    ord.Pricebook2Id = oppMap.get(ord.OpportunityId).pricebook2Id;
}}`

after this do create this
trigger OrderTrigger on Order (After insert) {
set<Id> oppId = new Set<Id>();
set<Id> pcrId = new set<Id>();
List<OrderItem> oliPist = new  List<OrderItem>();
for(Order ord : trigger.new) {
    if(ord.opportunityId != null) {
        oppId.add(ord.opportunityId);
    }
}

Map<Id,List<OpportunityLineItem>> olitoOpp = new  Map<Id,List<OpportunityLineItem>>();

for(OpportunityLineItem oli : [select Id,Quantity,UnitPrice,PricebookEntryId,Product2Id,OpportunityId from OpportunityLineItem where opportunityId In : oppId ]) {
    pcrId.add(oli.Product2Id);
    if(olitoOpp.containsKey(oli.opportunityId)) {
        olitoOpp.get(oli.opportunityId).add(oli);
    }
    else {
        olitoOpp.put(oli.opportunityId, new List<OpportunityLineItem>{oli});
    }
}
For(Order ord : trigger.new) {
    if(olitoOpp.containsKey(ord.opportunityId)) {
        for(OpportunityLineItem  oli : olitoOpp.get(ord.opportunityId)){

            OrderItem od = new OrderItem();
            od.OrderId=ord.Id;
            od.Quantity=oli.Quantity;
            od.PricebookEntryId=oli.PricebookEntryId;
            od.UnitPrice = oli.UnitPrice;
            od.Product2Id=oli.Product2Id;
            oliPist.add(od);
        }
    }

}

if(!oliPist.isEmpty()) {
    insert oliPist;
}

}


text:
Q: AFNetworking -- get redirect URL Use a AFNetworking against a REST API.

*

*POST to resources/

*Server responds with 303 -> see resources/3928.json

The the server is giving information here: the id 3928 has been assigned to your resource.
Is it possible to learn this URL during the POST operation? Also, I don't really need this resource. Can I avoid actually following the redirect?
Another option is to use a 200 with {status:"ok",insert_id:3928} but it feels like this is not necessary

A: -(void)call
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:YOUR_PARAMETER forKey:KEY];

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:YOUR_WEBSERVICE_URL];
    NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:WEBSERVICE_NAME parameters:params];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         //This is Redirect URL
         NSLog(@"%@",[[[operation response] URL] absoluteString]);
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Failure");
     }];

     [operation start];
}

A: I know this is a bit old, but I ran into this same type of problem. What helped me achieve finding the redirect URL was the following code snippet. I was able to get my redirect url out of the jsonDict.
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id jsonObject){
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"json: %@", jsonDict);
}failure:^(AFHTTPRequestOperation *operation, NSError *error){
    NSLog(@"failure");
}];


text:
Q: Is Force Lightning non lethal? According to this article, Force Lightning can be used to dispatch foes non lethally.  Of course, we've seen people survive force lightning before, but as the person casting it, how sure can you be that your victim will survive?

A: Introduction
Force lightning could be lethal or non-lethal, depending upon the goal of Force user. As a Force power, it is the same as all of the other Force powers insofar as it is an expression of a Force user's knowledge of and control over the Force, manifested as any number of effects, in this case discharging electricity (where the electricity actually comes from is another matter) towards a particular target. As with any other Force power, it is learned and practiced, and part of this learning is how to use it precisely.
The ability to use a Force power precisely can be shown in Force telekinesis, where its user can use it destructively or not depending on what they want to accomplish:

*

*a) Darth Vader uses Force telekinesis to snatch Han Solo's DL-44 blaster out of his hands on Cloud City, without destroying it (TESB)

*b) Darth Vader uses Force telekinesis over a long distance to choke Admiral Ozzel to death (TESB)
Force lightning under control
Force lightning was used, primarily (though not always) by the Sith, and while there are numerous examples in Legends of it being used to kill, it could also just be used to intentionally torture their target. Examples of a Sith using Force lightning only to torture their targets can be found in the Canon:

*

*in this youtube clip from TCW 3x14 where Count Dooku is using it to train Savage Opress

*in this youtube clip, also from TCW 3x14, where Dooku uses Force lightning to punish Savage Opress and then as a weapon during the battle

*in this youtube clip from TCW 5x16 involving Darth Sidious and Maul

*in its most famous example, when Darth Sidious uses it to slowly torture Luke Skywalker (though planning on it eventually killing him) in ROTJ, before unleashing a far more powerful blast at Darth Vader in his death throes (as it were)
These examples illustrate that Sith possessed the ability to use Force lightning only to inflict pain, not death, upon their target, if they so wished, and there are numerous more examples, usually from Legends stories involving the Sith.
A slightly different example of a Sith using Force lightning under control, from Legends, is Galen Marek/Starkiller from TFU games using it to activate or short out engines and blow up ammunition, as well as performing feats like directing Force lightning through his lightsaber and using it against multiple opponents simultaneously. The Wookieepedia page on Force lightning also illustrates many different variations on Force lightning that were used.
Conclusion
In order to use Force lightning, like any other Force-based power, it required practice and control, and an understanding of the Force itself. When Force lightning is used under control to achieve a specific object, this indicates that not only can it be controlled, but that control over it is learned through the Force.
The above examples, along with an understanding of what the Force is and how using the Force is necessary to generate and sustain Force lightning, indicate that in-universe, in Canon and in Legends, there is evidence that Force users (usually Sith) demonstrated the ability to attune their Force lightning attacks as desired, to be lethal, or not. That they demonstrated the use of this power to achieve specific goals indicates that they possessed the confidence, and therefore the ability, to do so.

N.B. As far as the physics of how they control it, if Force lightning is just electricity, and the Canon seems to suggest so, and the Sith know how to use it lethally or non-lethally, a technical explanation for how they actually accomplish it may be found in things like non-lethal lightning strikes, and in Tasers, where the distinction between volts, amps and watts comes into play, but someone who knows more about electricity than I should comment on that. The first comment below, by Null, links to a discussion about Force lightning as electricity.

A: Luke may have survived Palpatine's lightning attack, but Anakin definitely didn't, and Luke hadn't inflicted any lethal blows to his father.
It may break down to Darth Vader's armour and electric components, or even his prostheses as electric conductors. (Which leads to the question, why don't Jedi wear wooden shoes to neutralize force lightning?)
In my opinion, it clearly depends on the voltage used, which may boil down to the user's proficiency with the Force, or the capacity to 'decide' the level of voltage. Considering Palpatine's power, he shouldn't have had problems using it at its maximum capacity. So he either was toying with Luke, and then turned the amps up when Darth Vader surprise attacked him, or force lightning just isn't normally powerful enough to kill. Considering we even get to see Mace Windu's skeleton, I doubt that is the case.
Also, Force users have the capacity to use Force shields. The argument is pertinent to Jedi being attacked with Force Push or Strangle, and being able to shield against it. The proficiency with the Force of the two users involved should determine the outcome explaining why, in some cases, a Jedi should be a victim of Force Push and Strangle, a bit like Force Persuasion. Following this logic, we can assume that a Jedi can shield from Force Lightning, or at least partially, thus reducing the damage. This would explain Luke surviving it (maybe shielding his heart?) and ties in with Vader not being able to defend from Force Lightning as famously known.
Having said all this (and considering that birds can sit on high voltage without being electrocuted) just google anything about surviving electricity (https://www.thenakedscientists.com/forum/index.php?topic=33130.0) all Jedi are either total idiots (for not wearing rubber/wood/insulated shoes) or the normal laws of physics don't work in the Star Wars galaxy. (M theory suggests some laws of physics may be different in different multiverses).
Also another way of totally avoiding force lighting is levitation, and while we never saw proper levitation in canon we do see force users jump very high (eluding gravity briefly). Thus why Yoda would expend immense energies to absorb Palpatine's attack instead of just levitating or jumping very high is beyond me.
I don't think there's any way to give Force lightning a scientific explanation. It is just fiction and should be seen as such; there isn't much point in questioning whether it would be possible because it's just a double negatory. Even assuming you could use the Force in our reality, Force lightning doesn't follow any laws of physics. Just to further this point. Even a non Force user can protect himself from Force lightning by carrying with him something that attracts electricity to throw nearby when attacked and which would capture all electricity. You might not be aware that roofs of most building have lightning deflectors.
In short Force lightning is just fantasy and should be seen as such.

A: Only 10 milli amperes (0.0001 amps) through the heart is enough to kill a human.
High Skilled sith, may be able to redirect the electrical current to just your arm, or your legs, making them numb. Making it (Non Lethal) .
If he would like to kill you instanlty he will attack your heart.


text:
Q: Is there a "Save Page As PDF" for Shiny app? I posted an earlier question here about printing the page of a Shiny app to a pdf file for further use.
So I have found this Javascript code to print out certain CSS element to pdf
$('#downloadPDF').click(function () {
    domtoimage.toPng(document.getElementById('content2'))
      .then(function (blob) {
          var pdf = new jsPDF('l', 'pt', [$('#content2').width(), $('#content2').height()]);
          pdf.addImage(blob, 'PNG', 0, 0, $('#content2').width(), $('#content2').height());
          pdf.save("test.pdf");
      });
});

And I put that in a .js file in my RShiny project folder, and include includeScript("pdfOut.js") in my ui function (that the filename of the .js file). I also change the id of the element to those in my app as following:
$('#printPdf_CA').click(function () {
    domtoimage.toPng(document.getElementById('mainOrder_CA'))
        .then(function (blob) {
            var pdf = new jsPDF('l', 'pt', [$('#mainOrder_CA').width(), $('#mainOrder_CA').height()]);

            pdf.addImage(blob, 'PNG', 0, 0, $('#mainOrder_CA').width(), $('#mainOrder_CA').height());
            pdf.save("test.pdf");

            that.options.api.optionsChanged();
        });
});

Basically, I want to print the element mainOrder_CA (which is a div) into a pdf file name test.pdf if the app user clicks a button with id printPdf_CA
But it does not work. Nothing comes out, and there are no error message whatsoever. My app still runs as usual. I have zero knowledge on JS. Any advice on how to modify that code ? Basically, I am looking to print a div element into pdf when a user clicks an actionButton
Here is the original post for the JS code here

A: You have to load the JS libraries jsPDF and dom-to-image.
library(shiny)

js <- "
$(document).ready(function(){
  $('#printPdf_CA').click(function () {
    domtoimage.toPng(document.getElementById('mainOrder_CA'))
      .then(function (blob) {
        var pdf = new jsPDF('l', 'pt', [$('#mainOrder_CA').width(), $('#mainOrder_CA').height()]);
        pdf.addImage(blob, 'PNG', 0, 0, $('#mainOrder_CA').width(), $('#mainOrder_CA').height());
        pdf.save('test.pdf');
        // that.options.api.optionsChanged(); what is that?
      });
  });
});
"

ui <- fluidPage(
  tags$head(
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"),
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"),
    tags$script(js)
  ),
  br(),
  actionButton("printPdf_CA", "Print"),
  div(
    id = "mainOrder_CA",
    h3("Click on the button to print me")
  )
)

server <- function(input, output, session){

}

shinyApp(ui, server)

However, the pdf we get with this app is not nice, it does not respect the dimensions of the div. I don't know why.

EDIT
Hmm, this works fine when one removes the margins of the h3:
h3(style = "margin:0;", "Click on the button to print me")


text:
Q: How do ISVs hide their object code when you can decompile? My book says the following:
"Clients of a class do not need access to the class's source code in order to use the class. The clients do, however, need to be able to link to the class's object code (i.e., the compiled
version of the class). This encourages independent software vendors (ISVs) to provide class
libraries for sale or license. The ISVs provide in their products only the headers and the
object modules. No proprietary information is revealed—as would be the case if source
code were provided. The C++ user community benefits by having more ISV-produced
class libraries available."
Can't you just decompile the .o files to obtain their implementation?

A: You can, but generally it's hard to understand the decompiled code.
However, there exist good disassemblers -- HexRays produces quite understandable code, but is very expensive.


text:
Q: Can Eigen use more than Double precision in its linear algebra Ax=b I am using Eigen to do some linear algebra. i.e. find x in Ax=b. Where A is (n,n) matrix and x and b are (n,1) size vectors. I would like to know if it is possible to compute them with more than double precision.

A: Eigen can work with arbitrary precision arithmetic. There is an MPFR module readily available. Usually, this should not be necessary though (unless your original values already are stored in that high precision). You should first try using a more stable decomposition. Have a look at the available decompositions here. Which one is best, heavily depends on your use case.


text:
Q: python context manager not passing exceptions Why does the following unit test fail, and how do I get my context manager to pass exceptions properly? I'm using python 3.
test.py:
class test(object):
    def __enter__(self):
        pass
    def __exit__(self, *args):
        return args

test_test.py:
import test
import unittest

class TestTest(unittest.TestCase):
    def test_test(self):

        with self.assertRaises(OverflowError):
            with test.test():
                raise OverflowError()

if __name__ == '__main__':
    unittest.main()

Running the unit test, I get an error complaining that OverflowError was not raised. Why does this happen, and what do I need to do so that my context manager properly propagates exceptions?

A: Your issue is here:
def __exit__(self, ex_type, ex_val, tb):
    return ex_type, ex_val, tb

The return value of __exit__ implies that you want to suppress those errors raised inside the context block.
Simply change it to return nothing or raise the error if any overflow error occurs. If any truthy value is returned, the context block suppresses the error. You need to return false. An example is as follows:
def __exit__(self, ex_type, ex_val, tb):
    if ex_type is OverflowError:
        return False
    return True

Edit Martijn Pieters as always has a better explanation than me.


text:
Q: How to create custom animated floating label TextInput in React Native? I created a TextInput in React Native,

But I want the label go outside the box with animation when isFocused or filled with some value like:

If value is null or empty the label must be inside the input, otherwise the label must move outside the input with animation.
My Code:
export default function InputBox(props) {
  return (
    <View style={styles.container}>
      <Text style={styles.label}>{props.label}</Text>
      <TextInput
        style={styles.input}
        autoCapitalize="none"
        defaultValue={props.defaultValue}
        onChangeText={props.onChangeText}
        keyboardType={props.keyboardType}
        editable={props.editable}
      />
    </View>
  );
}

Style:
const styles = StyleSheet.create({
  container: {
    marginBottom: 20,
    backgroundColor: COLORS.WHITE,
    paddingTop: 5,
    paddingHorizontal: 10,
    borderWidth: 1,
    borderColor: COLORS.GREY_BORDER,
    borderRadius: 2,
  },
  icon: {
    width: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  input: {
    fontFamily: FONT_FAMILY.primaryMedium,
    fontSize: 13,
    height: 35,
    color: COLORS.BLACK,
  },
  label: {
    fontFamily: FONT_FAMILY.primary,
    color: COLORS.GREY,
    fontSize: 10,
  },
});

A: If you want to make your own animation you can wrap that label Text into a Animated.View component and give animation.
Try this:
import React, { useEffect, useState, useRef } from "react";
import {
  View,
  StyleSheet,
  TextInput,
  Text,
  Animated,
  Pressable,
} from "react-native";

const TestScreen = () => {
  const [value, setValue] = useState("");
  const moveText = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    if (value !== "") {
        moveTextTop();
    } else if (value === "") {
        moveTextBottom();
    }
  }, [value])

  const onChangeText = (text: string) => {
    setValue(text);
  };

  const onFocusHandler = () => {
    if (value !== "") {
      moveTextTop();
    }
  };

  const onBlurHandler = () => {
    if (value === "") {
      moveTextBottom();
    }
  };

  const moveTextTop = () => {
    Animated.timing(moveText, {
      toValue: 1,
      duration: 200,
      useNativeDriver: true,
    }).start();
  };

  const moveTextBottom = () => {
    Animated.timing(moveText, {
      toValue: 0,
      duration: 200,
      useNativeDriver: true,
    }).start();
  };

  const yVal = moveText.interpolate({
    inputRange: [0, 1],
    outputRange: [4, -20],
  });

  const animStyle = {
    transform: [
      {
        translateY: yVal,
      },
    ],
  };

  return (
    <View style={styles.container}>
      <Animated.View style={[styles.animatedStyle, animStyle]}>
        <Text style={styles.label}>Enter Your Name</Text>
      </Animated.View>
      <TextInput
        autoCapitalize={"none"}
        style={styles.input}
        value={value}
        onChangeText={(text: string) => onChangeText(text)}
        editable={true}
        onFocus={onFocusHandler}
        onBlur={onBlurHandler}
        blurOnSubmit
      />
    </View>
  );
};
export default TestScreen;

const styles = StyleSheet.create({
  container: {
    marginBottom: 20,
    marginTop: 20,
    backgroundColor: "#fff",
    paddingTop: 5,
    paddingHorizontal: 10,
    borderWidth: 1,
    borderColor: "#bdbdbd",
    borderRadius: 2,
    width: "90%",
    alignSelf: "center",
  },
  icon: {
    width: 40,
    justifyContent: "center",
    alignItems: "center",
  },
  input: {
    fontSize: 13,
    height: 35,
    color: "#000",
  },
  label: {
    color: "grey",
    fontSize: 10,
  },
  animatedStyle: {
    top: 5,
    left: 15,
    position: 'absolute',
    borderRadius: 90,
    zIndex: 10000,
  },
});


text:
Q: Stuck with a Custom Field Check box Array Been stuck on this for a while now.  Haven't come across anything that has shed any light on it for me...  Pardon my ignorance... quite a newbie at this level of php.
The problem:
I am using the wp-property plugin, but need a field that can have multiple numeric values.
Using Advanced Custom Fields to set up a checkbox field that can accept multiple numeric values.
I am attempting to add this field to the wp-property search function.
I get a dropdown menu, but it is populated with lines that look like unformatted arrays.
s:19.a:1:{i:0;s2  and so on.  My values are in that string but I don't know what to do to single them out.
I have this in my functions.php
add_filter('wpp_searchable_attributes', 'add_lease_to_searchable');
 function add_lease_to_searchable($fields) {

if(is_array($fields))

array_push($fields,  'lease-space1' );

return $fields;
}

Which gets that dropdown to be a part of the wp-property function.  If anybody has an idea on how to extract the values... even better put one on each dropdown line, that would be amazing. Feel stuck with no light at the end of the tunnel.

A: It's a serialized string. Use Unserialize to get an array out of this. Also checkout WP's maybe_unserialize method.
<?php $string = "s:19.a:1:{i:0;s2";

//Using WP maybe_unserialize
$result1 = maybe_unserialize($string);

//Using PHP unserialize
$result2 = unserialize($string);

echo "<pre>";
print_r($result1);
print_r($result2)
echo "</pre>";
?>

$result will hold what you want.


text:
Q: C3.js Line Graph Colors From URL So I am having troubles trying to change the colors of my line graph that is generated from JSON from a URL.  Here is my code to generate the chart:
var chart = c3.generate({
  bindto: '#chart',
  data: {
      url: '../URL.JSON',
      mimeType: 'json',
      keys: {
          x: 'Date',
          value: ["Line1", "Line2", "Line3", "Line4"]
      },
      type: 'line'
  },
  axis: {
      x: {
          type: 'category'
      }
  },
  size: {
      height: 500
  },
  colors: {
      'Line1': '#ff0000'
  }
});

And here is my JSON format:
[
    {'Date': '9/23/2014', 'Line1': 12, 'Line2': 54, 'Line3': 23, 'Line4': 5},
    {'Date': '9/22/2014', 'Line1': 56, 'Line2': 18, 'Line3': 25, 'Line4': 0}
]

For some reason the color does not change at all for Line1 with the colors attribute set.  So I was wondering if anyone knew how to change the colors to a url generated c3 graph.
Thankyou.

A: I figured out the answer to my own question so I thought that I would post it here.
I had to add:
color: {
    pattern: ['#363FBC', '#363FBC', '#B73540', '#B73540']
}

Instead of:
colors: {
  'Line1': '#ff0000'
}

A: The colors param should be inside the data object, like:
data: {
    columns: [
        ['data1', 30, 20, 50, 40, 60, 50],
        ['data2', 200, 130, 90, 240, 130, 220],
        ['data3', 300, 200, 160, 400, 250, 250]
    ],
    type: 'bar',
    colors: {
        data1: '#ff0000',
        data2: '#00ff00',
        data3: '#0000ff'
    }
}


text:
Q: Atleast one and atleast not one Requirement:
For a policy: At least one item (RAP03.propid) had discount (rap14.covid = 'SS') AND At least one item did not have discount (SS). Suppose we have one policy (rap01.plcy) , and with this policy we have 2 items (rap03.propid). So with one item SS should be there and with one item SS should not be there. I tried below but I got zero records. Is there any way to check both condition together.
we have to look respect of policy and item (PROPID) as well. One propid must contain SS but other propid must not contain SS.
Required result:
PLCY, PROPID, COVID
000000967428613 010 SS
000000967428613 011 BB

AND EXISTS
  (SELECT 1
    /*+ use_hash(RAP03 rap14) */
  FROM rap03
JOIN rap14
ON  rap14.j31_pt_line_cat_cd = rap01.j01_PT_LINE_CAT_CD
AND rap14.j31_pt_cdb_part_id = rap01.j01_PT_CDB_PART_ID
AND rap14.j31_pt_state_cd    = rap01.j01_PT_STATE_CD
AND rap14.plcy               = RAP01.plcy
AND rap14.propid             = RAP03.propid
AND trim(rap14.covid)        = 'SS'
AND tt.JA2_EFFDT_T BETWEEN rap14.enddt_t AND (rap14.dropdt_t - 1)
--
  WHERE RAP03.J12_PT_LINE_CAT_CD = RAP01.J01_PT_LINE_CAT_CD
  AND RAP03.J12_PT_CDB_PART_ID   = RAP01.J01_PT_CDB_PART_ID
  AND RAP03.J12_PT_STATE_CD      = RAP01.J01_PT_STATE_CD
  AND RAP03.PLCY                 = RAP01.PLCY
  AND tt.JA2_EFFDT_T BETWEEN rap03.adddt_t AND (rap03.dropdt_t  - 1)
  )
--
AND NOT EXISTS
  (SELECT 1
    /*+ use_hash(RAP03 rap14) */
  FROM rap03
JOIN rap14
ON  rap14.j31_pt_line_cat_cd = rap01.j01_PT_LINE_CAT_CD
AND rap14.j31_pt_cdb_part_id = rap01.j01_PT_CDB_PART_ID
AND rap14.j31_pt_state_cd    = rap01.j01_PT_STATE_CD
AND rap14.plcy               = RAP01.plcy
AND rap14.propid             = RAP03.propid
AND trim(rap14.covid)        = 'SS'
AND tt.JA2_EFFDT_T BETWEEN rap14.enddt_t AND (rap14.dropdt_t - 1)
--
  WHERE RAP03.J12_PT_LINE_CAT_CD = RAP01.J01_PT_LINE_CAT_CD
  AND RAP03.J12_PT_CDB_PART_ID   = RAP01.J01_PT_CDB_PART_ID
  AND RAP03.J12_PT_STATE_CD      = RAP01.J01_PT_STATE_CD
  AND RAP03.PLCY                 = RAP01.PLCY
  AND tt.JA2_EFFDT_T BETWEEN rap03.adddt_t AND (rap03.dropdt_t  - 1)
  )

A: You currently have WHERE EXISTS(query) AND NOT EXISTS(query) and both queries are identical; which is always going to be false.
I think the logic you want is WHERE (at least one record exists with 'SS') AND (at least one record exists that's not 'SS')
AND EXISTS
  (SELECT 1
    /*+ use_hash(RAP03 rap14) */
  FROM rap03
JOIN rap14
ON  rap14.j31_pt_line_cat_cd = rap01.j01_PT_LINE_CAT_CD
AND rap14.j31_pt_cdb_part_id = rap01.j01_PT_CDB_PART_ID
AND rap14.j31_pt_state_cd    = rap01.j01_PT_STATE_CD
AND rap14.plcy               = RAP01.plcy
AND rap14.propid             = RAP03.propid
AND trim(rap14.covid)        = 'SS'
AND tt.JA2_EFFDT_T BETWEEN rap14.enddt_t AND (rap14.dropdt_t - 1)
--
  WHERE RAP03.J12_PT_LINE_CAT_CD = RAP01.J01_PT_LINE_CAT_CD
  AND RAP03.J12_PT_CDB_PART_ID   = RAP01.J01_PT_CDB_PART_ID
  AND RAP03.J12_PT_STATE_CD      = RAP01.J01_PT_STATE_CD
  AND RAP03.PLCY                 = RAP01.PLCY
  AND tt.JA2_EFFDT_T BETWEEN rap03.adddt_t AND (rap03.dropdt_t  - 1)
  )
--

AND EXISTS -- CHANGE HERE (NOT removed)

  (SELECT 1
    /*+ use_hash(RAP03 rap14) */
  FROM rap03
JOIN rap14
ON  rap14.j31_pt_line_cat_cd = rap01.j01_PT_LINE_CAT_CD
AND rap14.j31_pt_cdb_part_id = rap01.j01_PT_CDB_PART_ID
AND rap14.j31_pt_state_cd    = rap01.j01_PT_STATE_CD
AND rap14.plcy               = RAP01.plcy
AND rap14.propid             = RAP03.propid

AND trim(rap14.covid)       <> 'SS'  -- CHANGE HERE (= becomes <>)

AND tt.JA2_EFFDT_T BETWEEN rap14.enddt_t AND (rap14.dropdt_t - 1)
--
  WHERE RAP03.J12_PT_LINE_CAT_CD = RAP01.J01_PT_LINE_CAT_CD
  AND RAP03.J12_PT_CDB_PART_ID   = RAP01.J01_PT_CDB_PART_ID
  AND RAP03.J12_PT_STATE_CD      = RAP01.J01_PT_STATE_CD
  AND RAP03.PLCY                 = RAP01.PLCY
  AND tt.JA2_EFFDT_T BETWEEN rap03.adddt_t AND (rap03.dropdt_t  - 1)
  )

Combining them reduces code, but may in-fact be slower because it can't 'stop' at the first record found...
AND EXISTS
(
  SELECT 1
    /*+ use_hash(RAP03 rap14) */
  FROM rap03
  JOIN rap14
    ON  rap14.j31_pt_line_cat_cd = rap01.j01_PT_LINE_CAT_CD
    AND rap14.j31_pt_cdb_part_id = rap01.j01_PT_CDB_PART_ID
    AND rap14.j31_pt_state_cd    = rap01.j01_PT_STATE_CD
    AND rap14.plcy               = RAP01.plcy
    AND rap14.propid             = RAP03.propid
    AND tt.JA2_EFFDT_T BETWEEN rap14.enddt_t AND (rap14.dropdt_t - 1)
--
  WHERE RAP03.J12_PT_LINE_CAT_CD = RAP01.J01_PT_LINE_CAT_CD
    AND RAP03.J12_PT_CDB_PART_ID   = RAP01.J01_PT_CDB_PART_ID
    AND RAP03.J12_PT_STATE_CD      = RAP01.J01_PT_STATE_CD
    AND RAP03.PLCY                 = RAP01.PLCY
    AND tt.JA2_EFFDT_T BETWEEN rap03.adddt_t AND (rap03.dropdt_t  - 1)
  HAVING
    MAX(CASE WHEN TRIM(rap14.covid) = 'SS' THEN 1 ELSE 0 END) = 1
    AND
    MIN(CASE WHEN TRIM(rap14.covid) = 'SS' THEN 1 ELSE 0 END) = 0
)

There may be better ways to formulate the query, but we would need more context (table definitions, full query, full logic explained, etc).


text:
Q: java.lang.ExceptionInIntilizerError in main My app crashes straight away with an exception

Here is the code of my main activity
package com.example.orientation;

import android.os.Bundle;
import android.app.FragmentManager;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;

public class MainActivity extends ActionBarActivity implements myList.Communication {
    myList listFragment;
    Details detailsFragment;
    FragmentManager manager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        manager=getFragmentManager();
        listFragment = (myList) manager.findFragmentById(R.id.listFragment);
        listFragment.setCommunicator(this);
    }

  @Override
    public void respond(int index) {
        detailsFragment = (Details) manager.findFragmentById(R.id.detailFragment);

        if (detailsFragment!=null && detailsFragment.isVisible()) {
            detailsFragment.changeData(index);
        }else{
            Intent intent = new Intent(this,DetailActity.class);
            intent.putExtra("index",index);
            startActivity(intent);
        }
    }
}

I tried reading documentation but could not get how to solve this. Any help will be appreciated. Thank You.

A: If you have only added android support jar, you must add the whole Appcompat project to your workspace:
right click -> IMport -> Android -> Project from Existing Source
Then go to SDK Folder where you installed and find extras/android/support/v7/appcompat
and add this whole Library.
It seems like you are missing resources needed for ActionBarActivity


text:
Q: Parsing a sentence using logical operators (Logical expressions) Parse the logical structure
"If everyone passes the quiz, Mr. Johnson will play his guitar."
-Use q as a constant to represent the quiz
-Use g as a constant to represent Mr. Johnson's guitar
-Use u as constant to represent Mr. Johnson
-Use $P(w, x)$ as the two-place predicate "w passes x"
-Use $Q(y, z)$ as the two-place predicate "y will play z"
Not sure if I am parsing this correctly
This what I have so far, but I feel that I am doing it wrong.
$\forall w(P(w,q))\rightarrow Q(u,g)$

A:
I don't know how to start this. I understand how logical operators work but don't know how I would parse the sentence into a logical expression.

Start by replacing the constants and predicates for words.  PS: I also suggest use $v$ for "his guitar".
Next, apply the universal quantifier and express "If ... , (then) ..." as a logical connective.

(edit)

Not sure if I am parsing this correctly. This what I have so far, but I feel that I am doing it wrong.
$\forall w~(P(w,q))~\to~ Q(u,g)$

That is correct.


text:
Q: setOrdinal not working properly when table is bind to datasource When I try to add new column and use SetOrdinal(2)
The newly added column was positioned in the last column
 conn = new MySqlConnection(connectString);
 conn.Open();
 fireAdapter = new MySqlDataAdapter(query, conn);
 fireBuilder = new MySqlCommandBuilder(fireAdapter);
 fireDataTable = new DataTable();
 fireAdapter.Fill(fireDataTable);
 fireSource = new BindingSource();
 fireSource.DataSource = fireDataTable;
 grid.DataSource = fireSource;
 conn.Close();

 DataColumn newcol = new DataColumn("Blah", typeof(string));
 fireDataTable.Columns.Add(newcol);
 newcol.SetOrdinal(2);

A: I'm pretty sure that your code does what you expect, it changes the position of the new column in the DataTable. But it is still shown as last column in the grid. So why you don't initialize the BindingSource after you have fully initialized the DataTable?
DataColumn newcol = new DataColumn("Blah", typeof(string));
fireDataTable.Columns.Add(newcol);
newcol.SetOrdinal(2);
// and now start assign it to the BindingSource


text:
Q: Kinect coordinates new SDK I can not find this method in the new microsoft kinect sdk
nui.SkeletonEngine.DepthImageToSkeleton
Can someone please some indications on how to accomplish this?
Microsoft Kinect SDK depth data to real world coordinates
in the new Microsoft Kinect SDK?

A: The method has changed to SkeletonPoint DepthImageFrame.MapToSkeletonPoint(int depthX, int depthY).  Like everything else in the new SDK, its located in the Microsoft.Kinect namespace.
Given a DepthImageFrame:
SkeletonPoint point = depthImageFrame.MapToSkeletonPoint(depthX, depthY);

A lot has changed with the new release.  A list of API changes can be found here: http://robrelyea.wordpress.com/2012/02/01/k4w-details-of-api-changes-from-beta2-to-v1-managed/#namespacesAssemblyName


text:
Q: How secure this PHP encryption/decryption will be? I am working in a project where users will need to encrypt/decrypt data. The encrypted data will be saved in a MySQL Database. The users do login from a a login page login.php and the function Login() is called. Data is encrypted and  Peppers are added at the end. Why? In case someone hacks the MySQL Database, the data is garbage for them because they also will need to have the Peppers to encrypt/decrypt data. The function ValidateLogin is not posted here but, the function is going to receive clear-text email and the encrypted password to validate if records exist in MySQL login table. Please answer me these questions:

*

*What is the best cipher to use? (I have no clue about this but, I am
using AES-256-CBC

*Do you think my script is good/secure enough to protect data?
File: peppers.php
<?php
define('PEPPER_PASSPHRASE', 'JkKli7YHUim6KH7tgyU6h56rykguhnBRvh23456%$%$#4c35$^$^Nm5GrBYB');
define('PEPPER_KEY', '6I7j5ih6tYHgbG4#$g%&h^&35$^g%7$VC$s23X#$%c^v$c35V^&b%&N6M8j^%4C54^#C5');
define('PEPPER_IV', '$^g%7&%b*45#$#4TF34TC3FG67H6755741532557B6$^v%$7$^^#$#%f&&B5B7V^*$6787');
?>

File: functions.php
    function Login(){
        $email = htmlentities($_POST["email"], ENT_QUOTES, "UTF-8");
        $password = htmlentities($_POST["password"], ENT_QUOTES, "UTF-8");
        if($email == NULL){ exit("Email can't be empty"); }
        if($password == NULL){ exit("Password can't be empty"); }
        @session_start();
        $_SESSION["passphrase"] = hash("SHA256", $password.PEPPER_PASSPHRASE);
        $password_encrypted = EncryptData($password);
        $password = NULL;
        ValidateLogin($email, $password_encrypted);
    }

    function EncryptData($data){
        @session_start();
        @$passphrase = $_SESSION["passphrase"];
        if($data == NULL){ exit("Missing data to encrypt"); }
        if($passphrase == NULL){ exit("Passphrase is not set"); }
        $key = hash("SHA256", $passphrase.PEPPER_KEY);
        $iv = substr(hash("SHA256", $passphrase.PEPPER_IV), 0, 16);
        $output = openssl_encrypt($data, "AES-256-CBC", $key, 0, $iv);
        return $output;
    }

    function DecryptData($data){
        @session_start();
        @$passphrase = $_SESSION["passphrase"];
        if($data == NULL){ exit("Missing data to encrypt"); }
        if($passphrase == NULL){ exit("Passphrase is not set"); }
        $key = hash("SHA256", $passphrase.PEPPER_KEY);
        $iv = substr(hash("SHA256", $passphrase.PEPPER_IV), 0, 16);
        $output = openssl_decrypt($data, "AES-256-CBC", $key, 0, $iv);
        return $output;
    }


text:
Q: CSS crop a image to a square I want to crop a image with a random size to a square aspect ratio. I just wanna use CSS and want it to be responsive and adapt the witdth and height automatically.
The css clip function does not work with percentages. (I'm using bootstrap grid)
Are there any other methods?
Thanks for your help and hints

A: The easiest thing to do would be to set a fixed width and height and backgroud-size cover.
.responsive-image {
    background-size: cover;
    background: url("url_of_the_image") 50% 50% no-repeat scroll transparent;
}
@media (max-width: 600px) {
    .responsive-image {
        height: 200px;
        width: 200px;
    }
}
@media (max-width: 800px) {
    .responsive-image {
        height: 400px;
        width: 400px;
    }
}

I'm not 100% sure about the syntax

A: You can use a background-image to accomplish this, with the cover background-size.
DEMO
In the demo I am using an image with rectangular dimensions(400x200) but the div element has a height and width of 200px.
By using the cover value you maintain the original aspect ratio of the image and cover the visible area of the element, essentially cropping the image.

div {
  background: #2a2828 url("http://lorempixel.com/400/200/") no-repeat center center/cover;
  height: 200px;
  width: 200px;
}
<div>
</div>


text:
Q: MongoDB - How to use $toInt in $sum of a field in an array? Can you guys help me with this problem?
Example:
Data:
{
      _id: "63f69650e820990f82dca60b",
      ...,
      transactions: [
        {
          ...,
          fee: "100",
          ...
        },
        {
          ...,
          fee: "200",
          ...
        }
      ]
    }

I want to add a total_fee field to calculate total fee of all the transactions in a document.
I tried using
$addfields: {
  total_fee: {
    $sum: {$toInt: "$transactions.fee"}
  }
}

But mongo return error about can't convert array to int

A: When you specify "$transactions.fee", it resolves to an array of strings. $toInt doesn't accept an array.
You use $reduce to iterate through the array and convert each string to integer, before adding.
db.collection.aggregate([
  {
    $addFields: {
      total_fee: {
        $reduce: {
          input: "$transactions.fee",   //1. Input is the array of strings
          initialValue: 0,              //2. Start
          in: {                         //3. iterate though the array
            $add: [
              "$$value",                //5. add the converted string to intermediate result, accessed using $value
              {$toInt: "$$this"}        //4. use $this to access current value of the iteration, convert it to int
            ]
          }
        }
      }
    }
  }
])

Demo

A: Using $reduce is an overkill in my opinion. $map should be simpler and is certainly faster:
db.collection.aggregate([
  {
    $addFields: {
      total_fee: {
        $sum: {
          $map: {
            input: "$transactions.fee",
            in: { $toInt: "$$this" }
          }
        }
      }
    }
  }
])

Of course, the proper solution is to store numeric values as number rather than strings.


text:
Q: "NoClassDefFoundError: Could not initialize class" error When I run my project, I get numerous outputs of this error:

Sep 9, 2009 8:22:23 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet Jersey threw exception
java.lang.NoClassDefFoundError: Could not initialize class SpringFactory
        at com.point2.prospect.persistence.hibernate.HibernateTransactionInterceptor.doFilter(HibernateTrans
actionInterceptor.java:17)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at com.point2.prospect.restapi.ServerErrorInterceptor.doFilter(ServerErrorInterceptor.java:27)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
        at java.lang.Thread.run(Thread.java:619)

I notice that this problem has a pattern of being asked all over the web, but with no real answers. What is a general cause for this kind of error?

A: You're missing the necessary class definition; typically caused by required JAR not being in classpath.
From J2SE API:

public class NoClassDefFoundError
  extends LinkageError
Thrown if the Java Virtual Machine or
  a ClassLoader instance tries to load
  in the definition of a class (as part
  of a normal method call or as part of
  creating a new instance using the new
  expression) and no definition of the
  class could be found.
The searched-for class definition
  existed when the currently executing
  class was compiled, but the definition
  can no longer be found.

A: NoClassDefFound error is a nebulous error and is often hiding a more serious issue. It is not the same as ClassNotFoundException (which is thrown when the class is just plain not there).
NoClassDefFound may indicate the class is not there, as the javadocs indicate, but it is typically thrown when, after the classloader has loaded the bytes for the class and calls "defineClass" on them.  Also carefully check your full stack trace for other clues or possible "cause" Exceptions (though your particular backtrace shows none).
The first place to look when you get a NoClassDefFoundError is in the static bits of your class i.e. any initialization that takes place during the defining of the class. If this fails it will throw a NoClassDefFoundError - it's supposed to throw an ExceptionInInitializerError and indicate the details of the problem but in my experience, these are rare. It will only do the ExceptionInInitializerError the first time it tries to define the class, after that it will just throw NoClassDefFound.  So look at earlier logs.
I would thus suggest looking at the code in that HibernateTransactionInterceptor line and seeing what it is requiring. It seems that it is unable to define the class SpringFactory. So maybe check the initialization code in that class, that might help.
If you can debug it, stop it at the last line above (17) and debug into so you can try find the exact line that is causing the exception. Also check higher up in the log, if you very lucky there might be an ExceptionInInitializerError.

A: I had faced the same issue, because the jar library was copied by other Linux user(root), and the logged in user(process) did not have sufficient privilege to read the jar file content.

A: I had this:
 class Util {
  static boolean isNeverAsync = System.getenv().get("asyncc_exclude_redundancy").equals("yes");
}

you can probably see the problem, the env var might return null instead of string.
So just to test my theory, I changed it to:
 class Util {
  static boolean isNeverAsync = false;
}

and the problem went away. Too bad that Java can't give you the exact stack trace of the error though, kinda weird.

A: I recently ran into this error on Windows 10. It turned out that windows was looking for .dll files necessary for my project and couldn't find them because it looks for them in the system path, PATH, rather than the CLASSPATH or -Djava.library.path

A: I had this same Error and it turns out, I had a method that was being called over and over, like an infinite loop, except it wasn't in an actual loop.

A: Realised that I was using OpenJDK when I saw this error. Fixed it once I installed the Oracle JDK instead.


text:
Q: How can I include this code within my website? I was wondering how I could embed this below into my website code. As I'm a beginner I was confused on how I can include this I'm just use to using the 12 grid system and never came across adding this to my website before.

$(document).ready(function() {
 $('#fullpage').fullpage();
});
.one {
  background: #F1E05A;
}

.two {
  background: #563D7C;
}

.three {
  background: #E34C26;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.css" rel="stylesheet"/>

FULL SITE CODE

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

           <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                           Toggle navigation

           </button>

Home

               About Me

Action

Contact

Something else here

Separated link

One more separated link

               Units

Action

Another action

Something else here

Separated link

One more separated link

Clients

Contact Me

A: You can include styles and scripts inline as below. Best practice would be to put these into their own files though. This allows you to better manage code and separate responsibility.

        <link href="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.css" rel="stylesheet"/>

Foo

Bar

Baz

I've also targeted the #Sections div for the JQuery function.

A: If what you are asking is how to display all of these things in an html page, this should get you started.  You could also move your styling into a custom css file.

<link href="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.css" rel="stylesheet" />

Color 1

Color 2

Color 3


text:
Q: Dompdf not rendering INR symbol in PDF I have come across an issue with dompdf while trying to use INR currency symbol. I have managed to resolve the  issue using Dejavu Sans font family  on my local server. But, when I upload the file to a live server it just generates a ? in place of the INR symbol. I have tried many methods like including providing @fontface{...} code ,define("DOMPDF_UNICODE_ENABLED",true), using 'Currencies' font family but it's not working.
require_once 'class-my-pdf-creator.php';
$dompdf = new my_pdf_obj();
define("DOMPDF_UNICODE_ENABLED", true);
$dompdf->set_option('isHtml5ParserEnabled', true);
$dompdf->loadHtml('₹');
// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');
$dompdf->set_option('font_subsetting', true);
// Render the HTML as PDF
$dompdf->render();
$dompdf->stream();

A: Dompdf 0.6.x and above support different encoding.
The easiest way to display the INR is to encode your document in UTF-8. Then you can reference the INR symbol.
Add below statement to your HTML:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

After adding above into your HTML, you can display INR symbol with below code:
₹


text:
Q: How can I solve my system of differential equations I have 3 differential equations and I want to obtain an analytic expression for f[r]. It does not matter what equations are and I just need the command to solve such equations. I know that these equations have two possible different solutions and maple can obtain them easily. I just need the command in Mathematica. For your check the solutions are f[r]=1+a*r^2+b/r^2 and f[r]=1+a*r+b*r^2.I will be grateful if someone help.
eq1 = Sin[t]^4*f[r]*r^4*D[f[r], {r, 4}] + (1/2)*r^3*Sin[t]^4*(10*f[r] + r*D[f[r], r])*D[f[r], {r, 3}] + (1/4)*r^4*Sin[t]^4*D[f[r], {r, 2}]^2 +
   (3/4)*Sin[t]^2*r^2*(r*Sin[t]^2*D[f[r], r] + (4/9 - (2/3)*f[r])*Sin[t]^2 - (2/9)*Cos[t]^2 + 2/9)*D[f[r], {r, 2}] - (5/2)*r^2*Sin[t]^4*D[f[r], r]^2 +
   (9/2)*Sin[t]^2*((-2/3 + f[r])*Sin[t]^2 + (1/3)*Cos[t]^2 - 1/3)*r*D[f[r], r] + (1/12)*(-32 - 24*f[r]^2 + 32*f[r])*Sin[t]^4 +
   (1/12)*(16 - 32*Cos[t]^2 + 16*f[r] - 16*f[r]*Cos[t]^2)*Sin[t]^2 - 2/3 + (8/3)*Cos[t]^2 - 2*Cos[t]^4

eq2 = -6*r^3*Sin[t]^4*(-2*f[r] + r*D[f[r], r])*D[f[r], {r, 3}] - 3*r^4*Sin[t]^4*D[f[r], {r, 2}]^2 -
   9*Sin[t]^2*r^2*(r*Sin[t]^2*D[f[r], r] + (4/9 - (10/3)*f[r])*Sin[t]^2 - (2/9)*Cos[t]^2 + 2/9)*D[f[r], {r, 2}] + 30*r^2*Sin[t]^4*D[f[r], r]^2 -
   102*Sin[t]^2*r*((f[r] - 6/17)*Sin[t]^2 - 3/17 + (3/17)*Cos[t]^2)*D[f[r], r] + (72*f[r]^2 + 32 - 64*f[r])*Sin[t]^4 +
   (32*f[r]*Cos[t]^2 + 32*Cos[t]^2 - 16 - 32*f[r])*Sin[t]^2 - 32*Cos[t]^2 + 24*Cos[t]^4 + 8

eq3 = 2*Sin[t]^4*f[r]*r^4*D[f[r], {r, 4}] + 2*r^3*Sin[t]^4*(4*f[r] + r*D[f[r], r])*D[f[r], {r, 3}] + r^4*Sin[t]^4*D[f[r], {r, 2}]^2 +
   3*Sin[t]^2*(r*Sin[t]^2*D[f[r], r] + (-2/3 - 2*f[r])*Sin[t]^2 + 4/3 - (4/3)*Cos[t]^2)*r^2*D[f[r], {r, 2}] - 10*r^2*Sin[t]^4*D[f[r], r]^2 +
   26*Sin[t]^2*((f[r] - 12/13)*Sin[t]^2 + 3/13 - (3/13)*Cos[t]^2)*r*D[f[r], r] + (-16*f[r]^2 - 8 + 36*f[r])*Sin[t]^4 +
   (12*f[r]*Cos[t]^2 + 20*Cos[t]^2 - 4 - 12*f[r])*Sin[t]^2 - 24*Cos[t]^2 + 20*Cos[t]^4 + 4

A: Original Solution
At first glance, the equations in the question would appear to have no analytical solutions, because there are three ODEs but only one dependent variable, and the coefficients in the ODEs depend on a second independent variable.  However, judicious use of DSolve obtains the solutions cited in the question.  Begin by eliminating the extra independent variable.
{eq1r, eq2r, eq3r} = FullSimplify[{eq1, eq2, eq3}]/Sin[t]^4
(* {(-8 - 8*f[r]^2 + r*(-10*r*D[f[r],r]^2 + r*D[f[r],{r,2}]*(2 + r^2*D[f[r],{r,2}])
    + D[f[r],r]*(-18 + 3*r^2*D[f[r],{r,2}] + 2*r^3*D[f[r],{r,3}])) +
    2*f[r]*(8 + 9*r*D[f[r],r] + r^2*(-D[f[r],{r,2}] + 2*r*(5*D[f[r],{r,3}]
    + r*D[f[r],{r,4}]))))/4,
    3*(8 + 24*f[r]^2 + 2*f[r]*(-16 - 17*r*D[f[r],r] + 5*r^2*D[f[r],{r,2}] +
  2*r^3*D[f[r],{r,3}]) - r*(-10*r*D[f[r],r]^2 + r*D[f[r],{r,2}]*(2 + r^2*D[f[r],{r,2}])
    + D[f[r],r]*(-18 + 3*r^2*D[f[r],{r,2}] + 2*r^3*D[f[r],{r,3}]))),
    -8 - 16*f[r]^2 + r*(-10*r*D[f[r],r]^2 + r*D[f[r],{r,2}]*(2 + r^2*D[f[r],{r,2}])
    + D[f[r],r]*(-18 + 3*r^2*D[f[r],{r,2}] + 2*r^3*D[f[r],{r,3}])) + 2*f[r]*(12 +
    13*r*D[f[r],r] - 3*r^2*D[f[r],{r,2}] + 4*r^3*D[f[r],{r,3}] + r^4*D[f[r],{r,4}])} *)

Unfortunately, DSolve cannot solve any of these equations individually and returns an error message when asked to solve all three at once.  It is, however, possible to obtain a solution with DSolve for
eqlin = Simplify[eq1r + eq2r/12]/f[r]
(* -4 + 4*f[r] - 4*r*D[f[r],r] + 2*r^2*D[f[r],{r,2}] +
   6*r^3*D[f[r],{r,3}] + r^4D[f[r],{r,4}] *)
DSolve[eqlin == 0, f, r][[1, 1]]
(* f -> Function[{r}, 1 + C[1]/r^2 + C[2]/r + r C[3] + r^2 C[4]] *)

Inserting this solution into the three original equations yields
Simplify[{eq1, eq2, eq3} /. %]/Sin[t]^4
(* {-((3 (14 C[1] C[2] + 9 r C[2]^2 + 5 r^3 C[2] C[3] + r^2 (4 C[2]
    + 6 C[1] C[3])))/(2 r^3)), ...} *)

where the second and third terms of the list are proportional to the first.  This determines the allowed values of the four constants of integration.
Reduce[Thread[CoefficientList[%[[1]] r^3, r] == 0], {C[1], C[2], C[3], C[4]}]
    //FullSimplify
(* (C[1] == 0 || C[3] == 0) && C[2] == 0 *)

In other words, C[2] and either C[1] or C[3] must be equal to zero, which is the desired result.
Addendum
The recurring expressions in the equations above suggest that relationships exist among {eq1r, eq2r, eq3r}.  Indeed,
eq1r == f[r] eqlin - eq2r/12
eq3r == 2 f[r] eqlin - eq2r/3

as can be demonstrated by applying Simplify to each of the two equalities.  Thus, the original question can, in principle, be answered by simultaneously solving {eqlin == 0, eq3r == 0}.
DSolve[{eqlin == 0, eq3r == 0}, f, r]

is, however, unable to do so directly, instead returning

DSolve::overdet: There are fewer dependent variables than equations, so the system is overdetermined.

Personally, I find this error message (and its documentation) unsatisfying, because it implies that this system of ODEs is ill-posed.  A more accurate message would be that DSolve is unable to determine whether this system of ODEs has a solution.  In general, non-trivial simultaneous solutions exist, if the manifolds of the solutions of each ODE, determined independently, intersect.  For the present problem, use DSolve to solve eqlin and then substitute the solution into eqr3 to obtain the desired results.  (This is, of course, equivalent to the final steps of my original answer.)
Incidentally, using Log[r] instead of r as the independent variable makes the two equations autonomous.  The value of doing so seems limited here, however.


text:
Q: How can you give 2 virtual servers the same name in the same domain? We had 3 laptops each having a vmware biztalk enviroment. this runs on a server 2008 and we used our doamin account to log in to them. all three virtual machines had the same name biztalkdev. and everything went fine with no problems (i know at least two of them were logged in at the same time.)
Now we replaced the three laptops with new ones, put on the virtual machines and the second person logging in had locked himself out (the domain has a trust violation error with the logon. This is solved by loggin in as admin and changing the domain from company.be to company but locks out the other two users) To top that off, the old machines now have the same problem as well and only one of the six machines can be in the domain.
Our network admin says it is due to all 3 vms having the same name but biztalk requires the servername in the projects and these get commited in svn. This means having three diffrent server names would mean everything we take something out of svn that we have to check and change all projects (after a few clients we have 12 projects, so this is still doable but it will only get worse.)
Although all the explanation about diffrent server names being impossible in the same domain, i don't get why it worked for nearly 3 weeks with all three servers having the same name. Is there trully no way to keep the server names of all three machines the same yet have all the acces on other domain locations?

A: The main problem will be the name resolution. Windows does this on various levels and with various technologies. ActiveDirectory does this in general with DNS (Also WINS may be used, but is no more centric). In DNS, there can a name only be used for one machine (at the same level).
However, active directory in its core uses a guid to uniquely identify a computer - not the computer name. This explains, why your were even able to have two computers with the same name in the same domain. But I'm pretty sure that there was a lot of functionality not working correcly. Only that it seems, that nobody noticed it. It's really an invalid or corrupt configuration and normally, AD does not allow you to to this.
I would recommend to post a question on StackOverflow about how to manage your Biztalk-configurations correctly. Trying to have more than one server with the same name in the same domain is probably not a good strategy. Holding hardcoded configurations in code is also not very advisable.
(I assume your not using any clustering or load ballancing)


text:
Q: AdaptiveCard with "mailto" Action.OpenUrl no longer works On Microsoft Teams, we have a bot that sends AdaptiveCard message activities to users through the Microsoft Bot Framework REST API. Sometimes, the AdaptiveCard contains an Action.OpenUrl. With regular links such as https://google.com it works as expected, but since about one month, URL parameters with a mailto url such as mailto:recipient@domain.com no longer work: the message is sent, the button appears but clicking it does not do anything.
Sample request:
POST https://smba.trafficmanager.net/emea/v3/conversations/<conversation_id>/activities
Body:
  "recipient": {
    "id": "29:1uuzUvFTkcseXZ1Q2wOva1inGkpH1SqbHwqdXjG8MhUa8mkFsdUnvrgn4FnPbX8CwBl_GwDHSQGIlRSPKczwUFg"
  },
  "type": "message",
  "attachments": [
    {
      "contentType": "application/vnd.microsoft.card.adaptive",
      "content": {
        "type": "AdaptiveCard",
        "version": "1.0",
        "body": [
          {
            "type": "ActionSet",
            "actions": [
              {
                "type": "Action.OpenUrl",
                "url": "mailto:antoine.chopin@heyaxel.com",
                "title": "TEST"
              }
            ]
          }
        ],
        "actions": []
      }
    }
  ]
}

A: Currently openSafeUrlMT does not allow mailto urls. we already have a backlog feature request on this. Concern team is working on this.


text:
Q: A quadrilateral drawn in the complex plane, Show that ABCD is a square if and only if $i(a-c) = (b-d)$.
A quadrilateral drawn in the complex plane has vertices $A,B,C,D$, labelled anticlockwise. These vertices are represented, respectively, by the complex numbers a, b, c, and d. Show that ABCD is a square if and only if $i(a-c) = (b-d)$.
Let PQRS be a quadrilateral in the complex plane, with vertices labelled anticlockwise, the internal angles of which are all less than 180. Squares with centres $X, Y, Z, T$ are constructed externally to the quadrilateral on the sides $PQ, QR, RS, SP$ respectively.
(1) If $P$ and $Q$ are represented by the complex numbers $p$ and $q$, respectively, show that $X$ can be represented by
$$\frac 1 2(p(1+i)+q(1-i))$$
(2) Show that XYZT is a square if and only if $PQRS$ is a parallelogram.

I got stuck from the first part above.
I know for a square, $\left|AB\right| =\left|BC\right|$ and they are 90 angles to each other.
So given they are in complex plane : $c-b = i(b-a)$ or $c-b = i(a-b)$
I am confused with which direction to take.
After this, how do i get to $i(a-c) = (b-d)$ and go the other way? Since the question is 'iff'?
As for Part (1) and (2) I do not even know where to start..
Many thanks in advance.


text:
Q: Distance To Move Two Polygons So They Touch Edges Best described in the image below.

I need to know the minimum distance to move a reference polygon (shown in red) in one axis (just y) such that will just touch the other polygon. If it's inside the polygon, it will need to move outwards.
I tried to look at all the lines in one polygon and all the points in another, project the point onto the line, and get the difference between the point y and the projection point y, then find the minimum distance. However, this had the issue that if the polygons overlapped and farthest line in one polygon and farthest point in the other had the minimum distance, it would give a result that would make the polygons overlap.
Edit: by projecting the point on the line, I mean find the y value for a point on the line that has the same x value as the original point. Skip this step if the x value lies outside of the line.

A: I'm not sure I have correctly understood your proposal (what's "projecting the point onto the line"?).
Anyway, I would try this (pseudo code), :
for pA: points of polygon A:
   for sB: segments of polygon B
      compute distance along y-axis d(pA,sB) and store in table
Find minimum distance in table: d1
Proceed as above by reversing A and B: d2
final d = min(d1,d2)

But unfortunatly, this probably isn't good if your polygons are concave, which seems to be the case.

A: You need to draw a vertical line through every vertex of both polygons and determine its intersection with the polygons (a line/polygon intersection is made of disjoint intervals).
On a given vertical, compute the difference between the highest endpoint of a polygon and the lowest of the other. The answer is the smallest difference among all verticals (which can be a negative number).
To perform the computation efficiently, you can use the scanline principle: sort all vertices from left to right and maintain an "active list", which is the list of edges that intersect the current vertical. As you move from one vertex to the next, you will update this list.
For two polygons of size N and M, sorting will cost O(N+M)Log(N+M)); then the scan will cost approximately O((N+M)K), where K is the average number of intersections of a vertical with a polygon, usually a small number between 2 and 4.