text:
Q: How to set a value for file upload button I have an application where we can select image and store it and when user needs to change a properties of image like height,width,image he will go to edit page and he will edit it..
But when the user does not change image if he changes only height and width then the image will no display because the image value will not fetch/set for file...
So how can we dynamically set path for a file upload button...

A: If you're talking about the HTML file input then you can't manipulate it's contents programmatically. This is a safety feature in modern browsers. For all intents and purposes you can consider it read-only.
Specs on the HTML file input

A: Answer is simple; you cannot.
Just check whether the image is set. If so, upload the new image. If not, don't replace the image with the image you already have. This is a safety measure, you don't want to be able to upload a file of the websites choise.


text:
Q: Various brackets on mathmode How do you write a code on LaTeX do to something like

Note that on the left there is a bracket (not captured on the photo)

A: You could use dcases and rcases from the mathtools package. Then you mess around with the \\[] to make the right space available
\documentclass{article}

\usepackage{amsmath,mathtools}

\begin{document}
\[
\begin{dcases}
\begin{rcases}
x=x\\
y=y\\
\end{rcases} &\text{if } a<0 \\[3ex]
\begin{rcases}
z=z\\
w=w\\
\end{rcases}&\text{if } a\ge 0\\[0.1ex]
\end{dcases}
\]
\end{document}

The same result is achieved using the dcases* environment which defaults the second column to normal "roman" text, so it will allow to insert text freely, as suggested by GustavoMezzetti. This keeps a neat logical division between the equation part (left) and the "explanation" part. You'll have to surround the math expressions contained in the second column with $, though
here is an example:
\documentclass{article}
\usepackage{amsmath,mathtools}

\begin{document}
\[
\begin{dcases*}
\begin{rcases}
x=x\\
y=y\\
\end{rcases} &if $a<0$ \\[3ex]
\begin{rcases}
z=z\\
w=w\\
\end{rcases}& if $a\ge 0$\\[0.1ex]
\end{dcases*}
\]
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: serialize() and $_SESSION Once the user is authenticated, I serialized the class object and stored it in a session. However, I cant seem to print its output even after using unserialize().
Creating the session variable:
if(!isset($_SESSION['myObj']) && empty($_SESSION['myObj'])) {
$myObj = new User($row['user_id'], $row['username'], $row['user_level']);
$_SESSION['username']= $myObj->usr_name;
$s_Obj = serialize($myObj);
$_SESSION['myObj'] = $s_Obj;

Accessing from a different page, no output:
$sObj = $_SESSION['Obj'];
$myObj = unserialize($s_Obj);
echo $myObj->usr_name;

This works however, so there's nothing wrong with my class. I am also using session_start() in both pages.
echo $_SESSION['username'];

Class user:
<?php

class User{
    public $usr_id;
    public $usr_name;
    public $usr_level;
    public $last_access_login;

    public function __construct($id, $usr_name, $usr_level) {
        $this->usr_id = $id;
        $this->usr_name = $usr_name;
        $this->usr_level = $usr_level;
        $this->last_access_login = date("F d Y H:i:s.",time());
  }
}
?>

Edit:
This is my vardump
array
  'myObj' =>
    object(__PHP_Incomplete_Class)[1]
      public '__PHP_Incomplete_Class_Name' => string 'User' (length=4)
      public 'usr_id' => string '3' (length=1)
      public 'usr_name' => string 'student' (length=7)
      public 'usr_level' => string '3' (length=1)
      public 'last_access_login' => string 'November 26 2011 20:12:38.' (length=26)
  'url' => string '/researchportal/proposal' (length=24)

A: Inital page:
$s_Obj = serialize($myObj);
$_SESSION['myObj'] = $s_Obj;

should be
$_SESSION['myObj'] = $myObj;

Next page:
$sObj = $_SESSION['Obj'];
$myObj = unserialize($s_Obj);

should be
$myObj = $_SESSION['myObj'];

In addition, try declaring your classes before your call to session_start().

A: Your unserialized object is being unserialized as an instance of __PHP_Incomplete_Class_Name because you are not including the definition of the User class prior to unserializing it. See Object Serialization. You must include the definition of the User class before you try to unserialize it.


text:
Q: Is the following interpretation for the stationary distribution of a Markov process correct? Imagine I have some Markov process with stationary distribution $\pi$ and a mixing time of $\tau$ after which $|Prob[x=s_i] - \pi(s_i)| \leq \epsilon$.
Can I assume the following:
A state $(x=s_i)$ will be sampled with probability at least $\pi(s_i)$ in time $\Theta(\tau)$?  Note that I'm talking about the average case, and saying nothing about variance.
If this assumption is false, how do we rectify this with the notion that we converge on $\pi$ after some appropriate amount of mixing time $\tau$?


text:
Q: Proving number of edges in $F = n - k$ So if we let $F = (V,E)$ be a forest with $n$ vertices and $k$ connected components (trees), how can I prove that the number of edges in $F = n - k$ ?
I was thinking of using induction, but I'm super lost. Can anyone guide me through this step by step? Would really appreciate it, thanks!

A: We note a tree $T$ with $n$ vertices has $n-1$ edges. So let $F = \bigcup_{i=1}^{k} T_{i}$ be the forest- a union of trees. Let $n_{i}$ be the number of vertices in each tree. So we have:
$|V(F)| = \sum_{i=1}^{k} n_{i} = n$
Since each component of the forest is a tree, we have $n_{i} - 1$ edges for $T_{i}$, giving us:
$|E(F)| = \sum_{i=1}^{k} (n_{i} - 1) = n - k$.


text:
Q: Issue passing values to a list - Lightning component I have been developing a lightning component to add products and can't seem to get my ids pushing to my productsList. My current revelant code is as follows:
CMP
<aura:component controller="AddProductsController" implements="flexipage:availableForAllPageTypes,force:hasRecordId" access="global">
<aura:attribute name="productList"  type="List"/>
<aura:attribute name="options" type="String" default="Nothing" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:handler name="change" value="{!v.cardType}" action="{!c.handleValueChange}"/>
    <aura:handler name="change" value="{!v.options}" action="{!c.handleSelect}"/>
    <aura:handler name="add" value="{!v.productList}" action="{!c.handleProduct}"/>

              <lightning:buttonicon iconName="utility:add" size="medium" alternativeText="Add" onclick="{!c.handleProduct}"/>

{!v.options} Added

            List:
           <aura:iteration var="list" items="{!v.productList}">
                {!productList.value}
            </aura:iteration>

My ids are passing into my options attribute fine.
Controller
handleProduct: function(cmp, evt){
    var Product = cmp.find("productType").get("v.value");
    cmp.set("v.options", Product);
    var PL = cmp.get("v.productList");
    PL.push(Product);
}

I think I have given all the relevant code associated with the action of passing to my list, obviously I am doing something wrong so any advice would be hugely appreciated.
Thanks

A: You want to set after push into a product List
handleProduct: function(cmp, evt){
var Product = cmp.find("productType").get("v.value"); cmp.set("v.options", Product);
 var PL = cmp.get("v.productList");
 PL.push(Product);
cmp.set("v.productList",PL);
}

And another bug in your code you iterating over list of Id that you are pushing in aura:iteration you want to refer using instance I.e) var
   <aura:iteration var="idInList" items="{!v.productList}">
{!idInList}
</aura:iteration>


text:
Q: Question closed as not constructive or argumentative with an answer If a question has been closed because it is likely to lead to heated or extended discussion, is it right that a single answer presenting the bias of the first person to respond be allowed to remain?

A: When a question is closed, the answers to it are generally considered separately; they are not automatically closed at all.
Though if the question gets deleted, the answers of course are deleted, too. If the question is that bad of a flame generator, that's likely going to happen.
The question might be reopened, as a general rule (not speaking to the specific case, which you have not linked). So generally, if the answer does not offend on its own then yes, it should be allowed to remain unless the question is deleted.


text:
Q: Change google chart type using ajax I have this js:
<script type="text/javascript">
    google.load('visualization', '1', {
        packages: ['corechart']
    });
    google.setOnLoadCallback(loadData);
    function loadData() {
        $.get({link loadData!}, function (results) {
            drawChart(results);
        });
    }
    function drawChart(results){
        var data = new google.visualization.DataTable();
        ...get some data etc...
        chart.draw(data, options);
    }
</script>

and i like to change chart type using ajax. I can redraw js and html code, but function loadData() doesn't start again. How can i fix it?

A: Run loadData() without google.setOnLoadCallback() resolved this problem


text:
Q: Lightswitch 2013 HTML Client - change background on one screen rather than all I know this will be possible but I have been unable to work this out so far... will this be done within the screen created code on the screen or is there a specific file I need to look in to achieve my goal?
thanks

A: Remember that HTML5 screens are built on Jquerymobile, so they also have the inherited richness of the Jquery selector model.
So... if you go to your designer, highlight the group control just below the TAB and click on the Edit PostRender Code link in the properties screen, you can add something like this:
myapp.ViewBook.Details_postRender = function (element, contentItem) {
    // Write code here.
    $(element).parent().parent().css({ background: '#FFDFDF' });
};

You could probably also edit other CSS styling elements in the same place.


text:
Q: probability of selecting dvds studying for a test, cant figure out this probability problem
A bin at Blockbuster contains 100 DVD's of which 20 are defective. You
randomly select 10 and try them out at home. You discover that there 2
defective DVD's in the 10 that you selected. The store now allows you to
select 2 replacements from the same bin (which now only has 90 DVD's in
it, since you already removed 10). What is the probability that none of 10
DVD's you finally end up with are defective? What is the answer to this
question if you find k defectives in your initial choice?

A: HINT: You're selecting $2$ replacements from a bin that has $90$ DVDs, of which $18$ are defective (since you removed $2$ defective DVDs in your first selection of $10$). That means that the bin contains $72$ good DVDs. You need to select $2$ good DVDs in order to end up with $10$ good ones.
There are $\dbinom{90}2$ ways to choose $2$ DVDs from the bin, and $\dbinom{72}2$ ways to select $2$ good DVDs.

*

*What do you do with these numbers to get the desired probability?

*What changes in the calculation if $2$ is replaced by $k$?


text:
Q: How to calculate separable closures of an algebraic extension? In my study of fields, the notion of the separability of an algebraic field extension is one of the more slippery concepts I have encountered thusfar. What is particularly vexing to me is the notion of a separable closure. Let $E/F$ be an algebraic field extension. The separable closure of $F$ in $E$ is defined to be the subfield
$E_{sep}=\{\alpha \in E \; | \; \alpha $ is separable over $ F \}$.
While the concept of a separable closure is easy enough to understand based on the definition, the actual calculation of a separable closure $E_{sep}$ for a given algebraic field extension $E/F$ is not obvious to me.
For example, I was recently assigned the following problem:

Let $k=\mathbb{F}_2(t)$, $\alpha$ be a root of $X^4+tX^2+t\in k[X]$ in an algebraic closure of $k$ and $K=k(\alpha)$, where $\mathbb{F_2}=\mathbb{Z}/2\mathbb{Z}$. Determine $K_{sep}$ and $[K_{sep}:K]$.

My first thought is that since the separability of an element $a$ of the algebraic field extension $E/F$ is defined based on the structure of its minimal polynomial $m_{a,F}(X) \in F[X]$, we can use this to determine the elements of $E_{sep}$. An element $e \in E$ is inseparable if and only if $m_{e,F}(X)=g(X^p)$ for some separable $g(X) \in F[X]$. So the separable elements of $E$ are those whose minimal polynomial is not an element of $F[X^p]$. This, however, does not seems to be a tractable idea.
My questions are

How does one approach the problem of calculation the separable closure of an algebraic extension, like, for example, the one above?
If there is no general, one-size-fits-all method, what are some examples of techniques used to deduce the separable closure?

Note: any questions asked herein are not current homework questions.

A: Here are a few details, completing Zev's completely correct, succinct comment (which I upvoted, of course).
An important first  remark is that the polynomial $f(X)=X^4+tX^2+t\in k[X]$ is irreducible over $k=\mathbb F_2(t)=Frac (\mathbb F_2[t])$ : this is Eisenstein's criterion in all its splendour,  applied with  the prime $t\in \mathbb F_2[t].\:$    Hence  $[K:k]=4$.
The polynomial $g(X)=X^2+tX+t\in k[X]$ is then also irreducible , so that $\alpha^2$ is of degree $2$ over $k$, since it is killed by $g$.
 Moreover since $g$ is  not a polynomial in $X^2$   and is irreducible ( an important, often forgotten condition!) , it is separable over $k$ and  so is  $\alpha ^2$, one of its roots.
So we have the tower of quadratic extensions  $k\subset k(\alpha ^2)\subset K$ with $k\subset k(\alpha ^2)$ separable and $k(\alpha ^2)\subset K=k(\alpha )$ obviously purely inseparable.
Only one intermediate field of $k\subset K$  can perform both these feats: $K_{sep}$ .
 Hence  $K_{sep}=k(\alpha^2)$.


text:
Q: How to pixelate part of image using ImageMagick? I'm trying to figure out a way to pixelate only part of an image but no success so far.
Currently I'm following the following this tutorial: http://www.mutinydesign.co.uk/free-scripts/live-photo-blurring-script/
Using the jQuery plugin "imgAreaSelect" so that users can select part of the picture from the UI.  Then the click 'pixelate'.  This then makes an ajax call to the pixelate function written in php for imagemagick.  The pixelate function looks like this:
<?php
$x1 = $_GET['x1'];
$y1 = $_GET['y1'];
$x2 = $_GET['x2'];
$y2 = $_GET['y2'];
$inputImage = $_GET['inputImage'];
$outputImage = 'output_'.$_GET['inputImage'];

exec( "convert {$inputImage} \( +clone -scale 20%  -scale 500% \) \
      \( +clone -gamma 0 -fill white \
      -draw 'rectangle {$x1},{$y1} {$x2},{$y2}' -blur  10x4 \) \
      -composite  {$outputImage}" );

echo $outputImage;
?>

This does work but it pixelates the whole image and not just the part selected.  Any ideas or suggestions appreciated.  Has anyone been able to accomplish something similar?

A: What you need to do is split the image into two variables, duplicating it. Then you crop one image in around the desired location. Pixel it up, then plop it right back onto the other image in the same place it was.
Then output it.
You'll have a sub-section of the image with blur, and the rest clear.


text:
Q: How can I visualise the 3D voronoi diagram in MATLAB? I don't understand the documentation that describes the visualisation of voronoi regions in MATLAB.
the documentation says the following:

You can plot individual bounded cells of an N-D Voronoi diagram. To do this, use the convhulln function to compute the vertices of the facets that make up the Voronoi cell. Then, use patch or other plotting functions to generate the figure.

I have a set of 3D points (P) that I calculated voronoin for using [v,c]=voronoin(P)
What do I do next to visualise this ?
voronoin always generates a row of inf values in v. So how can I use v to generate/visualise the voronoi regions/diagram?
Thanks


text:
Q: Zooming jQuery Plugin to Zoom the Page I need the jQuery Plugin to Zoom the Page to maximum 3 level larger and 3 level smaller.

*

*Selected Zoom should be stored in Cookie / somewhere to display in the same selected Zoom Size even the user refresh the page.

*Website has PopUp also, so my popup page should work with that too.

*It should work with all the browsers like Firefox, Chrome, IE8, Safari, Mac Safari.

*It should work with other devices like IPAD, IPHONE, Android Mobiles, Windows Mobile.

I'm breaking my head to solve this problem, Anyone please suggest a good jQuery plugin / any other libraries to solve this problem.

A: I just have tried Zoomooz.js. Works fine for me with FF and IE8.

A: Here is an example on how to do page zooming with jQuery:
 window.onload = function() {
 var currFFZoom = 1;
 var currIEZoom = 100;

 $('#In').on('click',function(){
     if (navigator.userAgent.indexOf('Firefox') != -1 && parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf('Firefox') + 8)) >= 3.6){//Firefox
         var step = 0.02;
         currFFZoom += step;
         $('body').css('MozTransform','scale(' + currFFZoom + ')');
     } else {
         var step = 2;
         currIEZoom += step;
         $('body').css('zoom', ' ' + currIEZoom + '%');
     }
 });

 $('#Out').on('click',function(){
     if (navigator.userAgent.indexOf('Firefox') != -1 && parseFloat(navigator.userAgent.substring(navigator.userAgent.indexOf('Firefox') + 8)) >= 3.6){//Firefox
         var step = 0.02;
         currFFZoom -= step;
         $('body').css('MozTransform','scale(' + currFFZoom + ')');

     } else {
         var step = 2;
         currIEZoom -= step;
         $('body').css('zoom', ' ' + currIEZoom + '%');
     }
 });};

 <input type="button" id="Out" alt="Zoom Out"/>
 <input type="button" id="In" alt="Zoom In"/>

Note: I haven't tested this across many browsers.


text:
Q: Network access behaviour problem I have Debian Wheezy 64 bit installed on my PC. The problem is that in some situations I can only ping localhost and 127.0.0.1 and don't have access to outside world. And in other cases I can ping everywhere but localhost.
Here is /etc/hosts
=======================================
    127.0.0.1   localhost
    127.0.0.1   my-pc

    # The following lines are desirable for IPv6 capable hosts
    ::1     localhost ip6-localhost ip6-loopback
    ff02::1 ip6-allnodes
    ff02::2 ip6-allrouters

=======================================
And here is /etc/network/interfaces
=======================================
    # This file describes the network interfaces available on your system
    # and how to activate them. For more information, see interfaces(5).

    # The loopback network interface
    auto lo
    iface lo inet loopback

    # The primary network interface
    allow-hotplug eth0
    iface eth0 inet static
        address 192.168.5.65
        netmask 255.255.255.0
        network 192.168.5.0
        broadcast 192.168.5.255
        gateway 192.168.5.1
    # dns-* options are implemented by the resolvconf package, if installed
        dns-nameservers 192.168.5.1 8.8.8.8 4.4.4.4

    #iface eth0 inet static
    #   address 192.168.5.65
    #   netmask 255.255.255.0
    #   gateway 192.168.5.1
    #auto eth0

    #allow-hotplug eth0
    #iface eth0 inet dhcp

=======================================
And here is /run/network/ifstate
=======================================
    lo=lo
    eth0=eth0

=======================================
After a restart, ping localhost fails and ping [rest of the world] works. but after any restart in networking service, only ping localhost works.

A: Solution
File /etc/nsswitch.conf must be present and contain the below line:
    hosts: dns files

In my case it was solved. Don't know why, but it was empty!


text:
Q: Validation using angularJS in multi step form I have a multi-step form

<form name="mf" novalidate  ng-submit="mfCtrl.postForm()"   >

            Full Name
            <input type="text" class="form-control" placeholder="Name" name="name" ng-model="mfCtrl.inputData.name" required />

                    Your name is required.

        <button type="button" class="btn btn-primary next"  ng-click="tab=2" >Next</button>

            Mobile
            <input type="text" class="form-control inputfield" id="exampleInputEmail1" maxlength="10" placeholder="Mobile" name="mobile" ng-model="mfCtrl.inputData.mobile" ng-minlength=10 ng-pattern="/^[0-9]{1,10}$/" required  />

                    Your mobile number is required.

        <button type="button" class="btn btn-primary next"  ng-click="tab=3" >Next</button>

</form>

I want to do validation at each step but the button at each step is not a submit button.
I have tried many things but nothing is working.In one of the method I used on clicking the button the validation works but it also increments tab which is of no use.
Please provide a solution for this problem.
Note- I don't wont to disable my button but show error on button click

A: you may need this post
also I guess(I'm not sure it will work, just try :), you can try to use ng-if instead of ng-show:
<form name="mf" novalidate  ng-submit="mfCtrl.postForm()"   >

        Full Name
        <input type="text" class="form-control" placeholder="Name" name="name" ng-model="mfCtrl.inputData.name" required />

                Your name is required.

    <button type="button" class="btn btn-primary next"  ng-click="tab=2" >Next</button>

        Mobile
        <input type="text" class="form-control inputfield" id="exampleInputEmail1" maxlength="10" placeholder="Mobile" name="mobile" ng-model="mfCtrl.inputData.mobile" ng-minlength=10 ng-pattern="/^[0-9]{1,10}$/" required  />

                Your mobile number is required.

    <button type="button" class="btn btn-primary next"  ng-click="tab=3" >Next</button>

A: Finally after banging my head for 1 day I have found the solution. So, anyone looking to create a multi step form with easy validation using AngularJS can use this code:

 {{cctab}}
  <form name="signup_form" ng-submit="signupForm()"  novalidate>

      Your name
      <input type="text"    placeholder="Name"  name="name" ng-model="signup.name"   ng-minlength=3 ng-maxlength=20 required />

     Your name is required.

     Your name is required to be at least 3 characters

     Your name cannot be longer than    20 characters

   <input type="button" ng-click="go()" value="next" >

<input type="text" name="username" id="name" placeholder="lname"/>
<input type="button"  >

</form>

A: Note: this is not a direct answer to this question, but recommendation
I've worked on a project where exact kind of thing was needed, multi step wizard with validation, data saving and so on. And as started doing it with ui-router, finally it became very buggy, then I've found a brilliant module: angular-multi-step-form and it saved me a lot of time and was bug free. it has validation, data saving and so on.


text:
Q: How to Get Output from R Scripts I have a .R Script and I am using deployR. My application is in Java and I have a client code interacting with the R code. The R code works fine and running it through deployR it generates a csv file too. This file is the output data that I need in my application.
I tried using the following :
RProjectExecution Execution = project.executeScript("XYZ.R", "root", "user", "", ExecutionOptions);
RData rDataOut =  Execution.about().workspaceObjects.get(0);

but the value of rDataOut  results to NULL. I cannot share the whole code due to company policy.
Any help will be appreciated.

A: Output files named in the API as artifacts:
List<RProjectFile> files = exec.about().artifacts;

Read more about https://msdn.microsoft.com/en-us/microsoft-r/deployr-client-library


text:
Q: HTML5 Geolocation on distance callback Is there any function available in HTML5 Geolocation  to get the location callback on distance traveled e.g. on every 1000 meter i want a lat lng.
i can use
navigator.geolocation.watchPosition(success, error, options);

and on the success callback calculate the distance between this and previous point if its greater than 1000 fire my distance callback, is there any other solution?

A: Use this function to get lat and long:
function initiate_watchlocation() {
    if (watchProcess == null) {
        watchProcess = navigator.geolocation.watchPosition(onSuccess, onError);
    }
}
var onSuccess = function(position) {
    var lat= position.coords.latitude;
    var long= position.coords.longitude;

    };

    function onError(error) {
            alert_box('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }

and keep it in DB and map that to lat1 and lon1, then keep watching lat and lon and map it to lat2 and lon2 respectively. and keep performing below function with old one.
function distance(lat1, lon1, lat2, lon2, unit) {
    var radlat1 = Math.PI * lat1/180
    var radlat2 = Math.PI * lat2/180
    var radlon1 = Math.PI * lon1/180
    var radlon2 = Math.PI * lon2/180
    var theta = lon1-lon2
    var radtheta = Math.PI * theta/180
    var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
    dist = Math.acos(dist)
    dist = dist * 180/Math.PI
    dist = dist * 60 * 1.1515
    if (unit=="K") { dist = dist * 1.609344 }
    if (unit=="N") { dist = dist * 0.8684 }
    return dist
}

then perform this:
if(distance(lat1, lon1, lat2, lon2, K) ==1){
   alert("1000 m");
}


text:
Q: Let $r\subseteq V^2$ a set-like relation, for every set $x$ there is a minimal, r-closed set $y$ that contains $x$. I came across this brief statement in my lecture notes that I'm unable to demonstrate to myself:
"In $ZF^{--} +$ Infinity, if $r\subseteq V^2$ is a set-like relation, then for every set $x$ there is a minimal(with respect to inclusion) r-closed set $y$ that contains $x$. Further, this does not hold in $ZF$ without Infinity, and it generally does not hold if $r$ is not set-like."

Note:
(1) $ZF^{--}$ stands for the set of axioms: Existence, Pairing, Union, Extensionality, Separation and Replacement axioms.
(2) a relation is set-like if the collection of all $r$-predecessors of a set is a set.

I am also not certain what "with respect to inclusion" implies:
Does it mean that
(a) $\forall a, a\in y \rightarrow$ "a is not r-closed"?
Or
(b) $\forall a, a\subseteq y \rightarrow$ "a is not r-closed"?
or something else?

A: The way I understand your question, a set $y$ is $r$-closed if whenever $a\in y$ and $b\ r\ a$ holds then $b\in y$. For a set $a$, let $p(a)=\{b\vert b\ r\ a\}$ deonte the $r$-predecessors of $a$. As $r$ is set-like, $p(a)$ is a set for any $a$. Start with a set $x$. We want to find $x\subseteq y$ such that $y$ is $r$-closed and whenever $x\subseteq z\subsetneq y$, $z$ is not $r$-closed (this is what I understand to be the ''inclusion minimal'' part).
Just take $y=\bigcup_{n<\omega} \bigcup p^n[x]$ where $p^0=id$ and $p^{n+1}(a)=p(p^n(a))$. It is not hard to check that $y$ is as desired in $ZF^{--}$.
For the second part: $V_\omega$ is a model of $ZF-Inf$. Consider the relation $r\subseteq\omega^2$ where $m\ r\ n$ iff $m=n+1$. The inculsion least $r$-closed $\{0\}\subseteq y$ would be $\omega$, but $\omega\notin V_\omega$.


text:
Q: Retrieve all emails from a google at work email group .net I don't even know what to look for. I tried using the directory API to accomplish this however I was not lucky. I have a service account key created so that my console app (which will become a azure web job) doesn't have to approve any permissions...
Can someone help with direction? I just don't even know where to start...

A: Depends where you want to start. There are probably a few libraries that will emulate the IMAP or POP3 protocols for you.
However you can also code the following protocols fairly easily.
https://code.msdn.microsoft.com/windowsdesktop/Simple-IMAP-CLIENT-b249d2e6
This example should get you started for IMAP, and POP3 will follow similar protocols.
EDIT:
I misunderstood the question. I was looking at gmail groups and I think I understand what you're trying to do. Retrieving emails from a group isnt really possible as the emails aren't shared. All a gmail group is, is a distribution list which sends emails to all the attendees in the list.
What i would do now is create a new Gmail account, and add it to the work group and have it receive all the emails. Use the Google SDK or the self created protocol to retrieve all the messages manually from the message box.


text:
Q: Why would all tables not be temporal tables by default? I'm creating a new database and plan to use temporal tables to log all changes. The data stored will be updated daily but will not be more than 5000 records per table
Is there any reason I shouldn't just make all tables temporal?
Ps. I am aware of the space usage of temporal tables, this is not as far as I understand a problem

A:
I am aware of the space usage of temporal tables, this is not as far as I understand a problem

On the contrary - it's pretty big problem - and there are many other downsides too.
When you use Temporal Tables (at least in SQL Server), every UPDATE operation (even if the data is unchanged) results in a copy being made in the History table (granted, under-the-hood this may be a COW-optimized copy, but it's still another conceptual entity instance).
Secondly - from my personal experience working with LoB applications: most changes to databases are not important enough to justify creating an entire copy of a row, for example, imagine a table with 4 columns ( CREATE TABLE People ( FirstName nvarchar(50), LastName nvarchar(50), Address nvarchar(200), Biography nvarchar(max): whenever a typo in FirstName is fixed then all of the data in the other columns is copied-over, even if Biography contains a 4GB worth of text data - even if this is COW-optimized it's still creating copies for every user action that results in a change.

Is there any reason I shouldn't just make all tables temporal?

The main reason, in my experience, is that it makes changing your table schema much harder because the schemas (aka "table design") of the Active and History tables must be identical: so if you have a table with a NULL column that you want to change to a NOT NULL column and you have NULL values in your History table then you're stuck - at least until you write a data transformation step that will supply the History table with valid data - it's basically creating more work for yourself with little to gain.
Also, don't confuse Temporal Tables with Immutable, Append-only data-stores (like the Bitcoin Blockchain) - while they share similar design objectives (except true immutability) they exist to solve different problems - and if you consider the size requirements and scaling issues of the Ethereum block-chain (over a terabyte by now) then that should give you another idea why it's probably not a good idea.
Finally, even if Temporal Tables didn't have these issues - you still need to go through the effort to write your main software such that it can natively handle temporal data - and things like Entity Framework still don't have built-in support for querying Temporal Data.
...and even with all the historical records you've managed to save in the History table, what do you want it for? Do you really need to track every corrected typo and small, inconsequential change?  How will your users react to needing to manually audit the changes to determine what's meaningful or not?
In short:

*

*If your table design probably won't change much in the future...

*AND small updates happen infrequently...

*OR large updates happen regularly AND you need an audit record

*...then go ahead and use Temporal Tables wherever you can.

*if not, then you're just creating more future work for yourself with little to gain.

A: "log all changes" is not a good use case for the temporal features in SQL.
The use case for the SYSTEM TIME temporal feature is when there is a pressing requirement obligating you/the user to be able to easily and quickly reconstruct (should be in scare quotes actually) the state that your database was in at a given moment in time.  That is difficult and error-prone and expensive if all you have is a true log of past changes.  But if you can suffice with keeping just a log of the changes, then do that (it will be difficult and error-prone and expensive to recreate past database states from the current state and your log, but that's not a pressing problem if there's no pressing need).
Also note that the SQL temporal features encompass also the notion of BUSINESS TIME, which is a different time dimension than the SYSTEM TIME one.  Business time is targeted to keeping a history of the world situation, system time is targeted at keeping a history of your database itself, that is, a history of your records of the world situation.


text:
Q: Transfer function of differential equation I'm trying to find out the transfer function of simple differential equation:
   $$a_0\dot y + a_1y=b_0x+b_1$$
The problem is i have no idea what to do with $b_1$.
If we apply the Laplace transform then we will have
$$a_0sY(s) + a_1Y(s)=b_0X(s)+b_1/s$$
The problem is that i have to reach $X(s)/Y(s)$ .
What is the Laplace transform transfer function of affine expression $\dot x = bu + c$?
 Based on this we do not have a solution?

A: What you could do is to introduce a new variable $\bar{x}(t) := x(t) + \frac{b_1}{b_0}$. This would enable you to express the transfer function by means of $\bar{X}(s)$, at least:
$$ \frac{\bar{X}(s)}{Y(s)} = \frac{a_0s+a_1}{b_0}. $$


text:
Q: Do tank bullets inflict damage on other tanks and jets in Battlefield 3? When I'm in a tank and manning the gun on top, I'm often confused as to what I should be doing when an enemy jet or tank starts getting to close to my position. I often open fire on them and try to inflict as much damage as possible. However, as far as I can tell, they're not doing anything at all. Am I mistaken, and can I actually hurt jets and tanks using tank bullets(not shells)? Or should I be focusing on checking for nearby engies or other soldiers?

A: The bullets from a tank's secondary position will inflict damage on most vehicles and all infantry.
Damage to aerial vehicles is fair, it's definitely worth shooting them to at least annoy them, and possibly disable them if they stick around long enough.
Damage to enemy armour is non-existant, and you're better off looking for enemy engineers repairing the tank, or scanning around for any sneaky engineers/supports who are looking for an easy kill on a distracted tank.

A: bullets from machine guns do not affect tanks or APCs.  They DO affect aircraft if the aircraft are close enough. They are most effective against scout helicopters, far less effective against attack helicopters, and if you can hit a jet, they are somewhat effective, but really not worth shooting because the jets get out of the kill zone so quickly.
As others have said, you are best off shooting at soldiers on foot or in jeeps so you don't get C4'd or blown up by RPG.
One thing also to remember is that if you get a lucky shot through the canopy of ANY aircraft, you can also get a kill. I have seen snipers do that on rare occasion, and have been killed that way in a helicopter. You will also find scumbag teammates occasionally teamkill you with a rifle when you're in an airplane or chopper just before takeoff: They scumbag teamkiller will shoot you through the canopy of the jet or glass of the helo.  That is also the way some snipers abuse spawns: They camp so they can see the planes or helo spawns and shoot the pilots as soon as they spawn in the aircraft.  That is not possible with a tank, though. Bullets do nothing to armor. And as another person said, remember that the gun on an attack helicopter is an armor-piercing cannon; the gun on the scout helo is just a machine gun, but even so, it will destroy a tank after about 6 full-magazine unloads on the tank. Any tank stupid enough to just sit there while you shoot it up deserves to get destroyed. But more likely you will as you move low-level within range of other tanks, SAMs, and even ground soldiers shooting into your helo.


text:
Q: Java: Check if string only contains 1,0 or a dot I'm attempting to check if a string contains only

*

*1

*0

*.
or a combination of these three.
First I had this code:
public static boolean controleSubnetmask(String mask) {
    try {
        String[] maskArray = mask.split(".");
        int[] subnetmask = new int[4];

        //array of string to array of int
        for (int i = 0; i < maskArray.length; i++) {
            subnetmask[i] = Integer.parseInt(maskArray[i]);
        }
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

but that is rather complicated for what it does, and it doesn't check if only 1 and 0 are entered.
So now I have this, but it seems I misunderstood regular expressions because it doesn't work:
public static void controleSubnetmask(String mask) {
    mask = "1100.110...11";
    String test = "p";
    if (mask.contains("[^10\\.]") == true) {
        System.out.println("wrong input");
    }
    if (test.contains("[^10\\.]") == true) {
        System.out.println("wrong input");
    }
}

I expected a 'wrong input' message on the test String, which didn't appear. So I believe my regex:
[^01\\.]

is wrong, but I really have no clue how to specify it.
Thanks in advance!

A: String.contains works with Strings  NOT with REGEX. use String.matches
 instead. As @lazy points out, you could use Pattern and Matcher classes as well.
test.contains("[^10\\.]") == true

All you are doing here is checking whether test contains the String literals [^10\.]


text:
Q: Why My App Throws No Static Method While It exists I have a java file that contains a static method and after running the app , it shows me that the method does not exist, I decomplied my app source code and found the method exists , so why it throws that Exception[this is the error which is being thrown on Runtime
My Code
My App's Runtime Exception


text:
Q: How to differentiate new items from existing items in SharePoint workflow I have a SPD workflow that is set to run when an item changes but it keeps getting triggered on new items, which is pretty annoying. I'm looking into why this is happening but I'm also looking for a way to terminate the workflow if the item is new as a temporary workaround.
I tried to compare the Created field to the Modified field i.e. if Created and Modified are the same then don't run. This didn't work, either as a date or string comparison.
Any suggestions would be much appreciated.

A: Store a flag in a hidden field the first time the workflow is run. Check if the flag is present, if not then it is the first time (created), otherwise it is updated.

A: I have faced this same issue and I solved with the workaround like this

*

*Take created date and add 1 minute with it and assign it to a variable

*Check this variable less than current time.
It done with the following assumption
a. No one try t edit the item within one minute, it created
b. Workflow will execute within one minete
In my case it was success

A: The comparison between the created time and modified time works on SharePoint 2010 (it is used here). Perhaps the comparison is done incorrectly or the wrong object is used to get the data from?
If said approach does not work on 2007, perhaps it may be possible to use the owshiddenversion field (directly access as property if not correctly exposed). It should be 1 for a newly created item, and > 1 otherwise. It may only be available on versioned lists, I do not recall.

A: Try adding a condition which compares the create date with the modified date.
i.e.: if current item:created not equals current item:modified


text:
Q: Setting the Python interpreter in PyCharm 2020.2.3, using QGIS 3.10.11. Error "No module qgis exists" I'm trying to find out where I'm going wrong in trying to set up PyCharm to make standalone QGIS Python scripts.
The very first step in the tutorial is "from qgis.core import *"
I've tried each Python installed in the QGIS folder, they all have no module named qgis.

The error is the same


text:
Q: Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1) error i am on a game project in android with andengine like FruitNinja in which i am using to throw images from bottom to top
project is working fine but giving error this sometimes
i used System.gc() but not helpful
Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1)
my code is
private void throwHardware(final float pX, final float pY) {

    final FixtureDef boxFixtureDef = PhysicsFactory.createFixtureDef(0.1f,
            0.5f, 0.5f);
    boxFixtureDef.filter.categoryBits = 0x0002;
    boxFixtureDef.filter.maskBits = 0x0004;
    boxFixtureDef.filter.groupIndex = 2;
    Random rng = new Random();
    generated1 = new ArrayList<Integer>();
    r = rng.nextInt(8);
    Log.e(Integer.toString(r), "r");
    if (r == 0) {
        Hardware = new Sprite(pX, pY, java,
                this.getVertexBufferObjectManager());
        body = PhysicsFactory.createBoxBody(this.mPhysicsWorldg, Hardware,
                BodyType.DynamicBody, boxFixtureDef);
        mHardware[active] = new Sprite(pX, pY, java,
                this.getVertexBufferObjectManager()) {
            @Override
            public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
                    float X, float Y) {
                if (pSceneTouchEvent.isActionDown()) {

                    if (a == 0) {
                        score();
                        remove();
                        question();
                    } else {
                        remove();
                        wrong();
                        question();

                    }
                    return true;
                }
                return true;
            };
        };
    } else if (r == 1) {
        Hardware = new Sprite(pX, pY, facebook,
                this.getVertexBufferObjectManager());
        body = PhysicsFactory.createBoxBody(this.mPhysicsWorldg, Hardware,
                BodyType.DynamicBody, boxFixtureDef);

        mHardware[active] = new Sprite(pX, pY, this.facebook,
                this.getVertexBufferObjectManager()) {
            @Override
            public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
                    float X, float Y) {
                if (pSceneTouchEvent.isActionDown()) {
                    if (a == 1) {
                        score();
                        remove();
                        question();
                    } else {
                        remove();
                        wrong();
                        question();
                    }
                    return true;
                }
                return true;
            };
        };
    } else if (r == 2) {
        Hardware = new Sprite(pX, pY, android,
                this.getVertexBufferObjectManager());
        body = PhysicsFactory.createBoxBody(this.mPhysicsWorldg, Hardware,
                BodyType.DynamicBody, boxFixtureDef);
        mHardware[active] = new Sprite(pX, pY, android,
                this.getVertexBufferObjectManager()) {
            @Override
            public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
                    float X, float Y) {
                if (pSceneTouchEvent.isActionDown()) {
                    if (a == 2) {
                        score();
                        remove();
                        question();
                    } else {
                        remove();
                        wrong();
                        question();

                    }
                    return true;
                }
                return true;
            };
        };
    } else if (r == 3) {
        Hardware = new Sprite(pX, pY, usb,
                this.getVertexBufferObjectManager());
        body = PhysicsFactory.createBoxBody(this.mPhysicsWorldg, Hardware,
                BodyType.DynamicBody, boxFixtureDef);
        mHardware[active] = new Sprite(pX, pY, usb,
                this.getVertexBufferObjectManager()) {
            @Override
            public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
                    float X, float Y) {
                if (pSceneTouchEvent.isActionDown()) {
                    if (a == 3) {
                        score();
                        remove();
                        question();
                    } else {
                        remove();
                        wrong();
                        question();

                    }
                    return true;
                }
                return true;
            };
        };
    } else if (r == 4) {
        Hardware = new Sprite(pX, pY, google,
                this.getVertexBufferObjectManager());
        body = PhysicsFactory.createBoxBody(this.mPhysicsWorldg, Hardware,
                BodyType.DynamicBody, boxFixtureDef);
        mHardware[active] = new Sprite(pX, pY, google,
                this.getVertexBufferObjectManager()) {
            @Override
            public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
                    float X, float Y) {
                if (pSceneTouchEvent.isActionDown()) {
                    if (a == 4) {
                        score();
                        remove();
                        question();
                    } else {
                        remove();
                        question();
                        wrong();
                    }
                    return true;
                }
                return true;
            };
        };
    } else if (r == 5) {
        Hardware = new Sprite(pX, pY, ram,
                this.getVertexBufferObjectManager());
        body = PhysicsFactory.createBoxBody(this.mPhysicsWorldg, Hardware,
                BodyType.DynamicBody, boxFixtureDef);
        mHardware[active] = new Sprite(pX, pY, ram,
                this.getVertexBufferObjectManager()) {
            @Override
            public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
                    float X, float Y) {
                if (pSceneTouchEvent.isActionDown()) {
                    if (a == 5) {
                        score();
                        remove();
                        question();
                    } else {
                        remove();
                        question();
                        wrong();
                    }
                    return true;
                }
                return true;
            };
        };
    } else if (r == 6) {
        Hardware = new Sprite(pX, pY, cd,
                this.getVertexBufferObjectManager());
        body = PhysicsFactory.createBoxBody(this.mPhysicsWorldg, Hardware,
                BodyType.DynamicBody, boxFixtureDef);
        mHardware[active] = new Sprite(pX, pY, cd,
                this.getVertexBufferObjectManager()) {
            @Override
            public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
                    float X, float Y) {
                if (pSceneTouchEvent.isActionDown()) {
                    if (a == 6) {
                        score();
                        remove();
                        question();
                    } else {

                        remove();
                        wrong();
                        question();
                    }
                    return true;
                }
                return true;
            }

        };
    } else if (r == 7) {
        Hardware = new Sprite(pX, pY, samsung,
                this.getVertexBufferObjectManager());
        body = PhysicsFactory.createBoxBody(this.mPhysicsWorldg, Hardware,
                BodyType.DynamicBody, boxFixtureDef);
        mHardware[active] = new Sprite(pX, pY, samsung,
                this.getVertexBufferObjectManager()) {
            @Override
            public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
                    float X, float Y) {
                if (pSceneTouchEvent.isActionDown()) {
                    if (a == 7) {
                        score();
                        remove();
                        question();
                    } else {
                        remove();
                        wrong();
                        question();
                    }
                    return true;
                }
                return true;
            };
        };
    }

    mHardwareBody[active] = PhysicsFactory.createBoxBody(
            this.mPhysicsWorldg, mHardware[active], BodyType.DynamicBody,
            boxFixtureDef);

    scene.attachChild(mHardware[active]);

    this.mPhysicsWorldg.registerPhysicsConnector(new PhysicsConnector(
            mHardware[active], mHardwareBody[active], true, false));

    Vector2 velocity = Vector2Pool.obtain(-1, -16);
    body.setTransform(velocity, 85);
    mHardwareBody[active].setLinearVelocity(velocity);
    Vector2Pool.recycle(velocity);
    this.scene.registerTouchArea(mHardware[active]);

}

A: Something's corrupted or uninitialised. 0xdeadbaad looks like one of those debugging/sentinel addresses like 0xdeadbeef or 0xbaadf00d.
Something you may want to look into is heap corruption. According to the Wikipedia HexSpeak page:

0xDEADBAAD ("dead bad") is used by the Android libc abort() function when native heap corruption is detected.

There's not really enough information in your question to give specific guidanve for fixing such a problem, it may be worth contacting the AndEngine bods to see what they think, assuming it's something being caused by their code (or your code indirectly through theirs).


text:
Q: SQL ERROR: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result I have the below MySQL query which is returning bool false when doing var_dump. The mySQL statement is correct as I tested in phpMyAdmin. Any suggestions to fix this please?
<?php
    $sql = "SELECT enBody FROM page WHERE pageName='wine'";
    $en = $db->query($sql);

    var_dump($enOutput=mysqli_fetch_assoc($en));
    var_dump($en);//returns bool false too
    while($enOutput=mysqli_fetch_assoc($en)) :
        $enDisplay=$enOutput['enBody'];
        echo $enDisplay;
    endwhile;

A: The problem was with the connection string. There was the database name which was different, missing one capital character....stupid me. apologies and thanks all

A: The best guess would be SQL query is unable to find the requested rows so it's returning by assuming you don't have any error in sql query.
if You aren't sure about query then use this to check by replacing the query with this
$sql = "SELECT enBody FROM page WHERE pageName='wine'";
$result= $db->query($sql) or die(mysqli_error($db));

null and mysqli_fetch_assoc only accepts mysqli result
So you just need to put a basic if else statement check whether the SQL Query has returned result or not
Try this and let me know if it works or not
I basically just used a function mysqli_num_rows which returns the number of rows fetched by query and followed by conditional to check
$sql = "SELECT enBody FROM page WHERE pageName='wine'";
$result= $db->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
       print_r($row);

    }
} else {
    echo "0 results";
}

A: You are mixing Object oriented style with  Procedural style.
While using Object oriented style you should not use mysqli_* functions as these belongs to Procedural style.
For Procedural style refer: http://php.net/manual/en/function.mysqli-connect.php
For Object oriented style refer: http://php.net/manual/en/mysqli.construct.php
For you code:
Object oriented style:
<?php
$sql = "SELECT enBody FROM page WHERE pageName='wine'";

if($en = $db->query($sql)):
    /* fetch associative array */
    while($enOutput=$en->fetch_assoc($en)) :
        $enDisplay=$enOutput['enBody'];
        echo $enDisplay;
    endwhile;
    /* free result set */
    $en->free();
endif;

Also, for fetch_assoc, refer: http://php.net/manual/en/mysqli-result.fetch-assoc.php


text:
Q: shared memory in web application Hi I'm writing a web application using Django. I'm still learning the framework and reading the howto book. I know I might be asking this question prematurely however i'd really like to know. I want to  create a python data structure in memory that is shared across all the sessions. What would be the best and most scalable way to perform this. So far I have read about redis however I would like to more flexibility and understand redis can only store strings instead of python objects..

A: This post is partially close to what you want (excluding the java part and the later update on the post). The summary of the answer is that django is a muti-process environment, and thus sharing objects across sessions is not feasible. One option is to use the database for storing such shared objects.


text:
Q: Disable CPU frequency scaling? I need to run ATLAS on my ubuntu laptop, but the software won't run unless you dissable CPU frequency scaling. I've tried the instructions from here http://math-atlas.sourceforge.net/atlas_install/node5.html but they aren't working on my Toshiba laptop. With freq-scaling turned on the software becomes useless.
Can anyone help?

A: Replace default governor with performance in the following files:
/etc/init.d/cpufrequtils

/etc/default/cpufrequtils

Disable ondemand service
sudo update-rc.d ondemand disable

then run
update-initramfs -u -k all

then reboot
More info: How I can disable CPU frequency scaling and set the system to performance?
https://wiki.debian.org/HowTo/CpuFrequencyScaling
https://wiki.archlinux.org/index.php/CPU_frequency_scaling

A: I wrote cpuf GUI to set minimum and maximum frequencies at will. You can use it just before your Math app to set all frequencies to max. After running your Math app you can reset frequencies normal for long battery life and less heat.
cpuf - Simple Bash GUI to set CPU Min/Max Frequency
Demonstration
In this demo cpuf window is on left and conky system information is on right side. This is how the demo progresses:

*

*Demo starts whilst youtube video is already running

*Default CPU min/max frequencies are 800 / 3500

*Override CPU min/max to 800 / 800 and CPU usage jumps to 20%

*Override CPU min/max to 3500 / 3500 and CPU usage drops to 10%

*Demo loops back and starts again

With three monitors cpuf can appear 10 feet away, so use parameter 1 --geometry option to put it close to conky:
sudo cpuf --geometry="450x450+4720+80" /home/rick/Pictures/icons/cpu-intel-128.svg

*

*Parameter 1 --geometry is Window Width x Height + Width Offset + Height Offset

*Parameter 2 can be your own icon (in this case Intel CPU image) otherwise it defaults to computer icon

cpuf Bash script
This section requires you to open a terminal with Ctrl+Alt+T.
How to setup
In order to function, cpuf bash script requires:
sudo apt install yad         # from the repository universe
sudo apt install coreutils   # installed by default in most distros

It's easiest when you place cpuf script into a root-owned directory within your search path. For example: /usr/local/bin.
To create cpuf script open the editor with sudo -H gedit /usr/local/bin/cpuf.

*

*Highlight the lines in section below

*Right click and select "Copy"

*Toggle back to your editor

*Right click and select "Paste"

*From the editor menu select "Save" and then "Exit"

Make the script executable with sudo chmod a+x /usr/local/bin/cpuf.
cpuf code to copy to your editor
#!/bin/bash

# NAME: cpuf (Pronounced SEA-PUFF)
# CALL: sudo cpuf
# PARM: $1 = --geometry=WidthxHeight+VertOffset+HorizOffset
#       $2 = Optional image icon

# DESC: Simple GUI script to set CPU Min and Max Frequency.
#       For Ask Ubuntu Question: https://askubuntu.com/q/1141605/307523
# DATE: May 12, 2019.
# UPDT: No updates yet.
# NOTE: No notes yet.

### Dependancies ###

command -v yad >/dev/null 2>&1 || { echo >&2 \
        "yad package required but it is not installed.  Aborting."; \
        exit 1; }

command -v nproc >/dev/null 2>&1 || { echo >&2 \
        "coreutils package required but it is not installed.  Aborting."; \
        exit 2; }

if [[ $(id -u) != 0 ]]; then # root powers needed to call this script
    echo >&2 Must be called with sudo powers
    exit 3
fi

# $TERM variable may be missing when called via desktop shortcut
CurrentTERM=$(env | grep TERM)
if [[ $CurrentTERM == "" ]] ; then
    notify-send --urgency=critical \
    "$0 cannot be run from GUI without TERM environment variable."
    exit 4
fi

### Program constants ###

## Yad Window parameters
# Hard code Height & Width to suit your screen resolution and scaling factor
GEOMETRY="--width 400 --height 500"
# Pass Parameter 1 with ---geometry="WidxHgt+WidOff+HgtOff" to override
[[ "$1" == --geometry=* ]] && GEOMETRY="$1"

TITLE="cpuf"
TEXT="Set CPU Min/Max Frequencies"
ICON="/usr/share/icons/Adwaita/48x48/devices/computer.png"
# Pass Parameter 2 with icon for window image
# Intel CPU comes from: https://www.gnome-look.org/p/1107932/
[[ ! -z "$2" ]] && ICON="$2"

## Virtual File System directories
      CPU0_DIR=/sys/devices/system/cpu/cpu0/cpufreq
    PSTATE_DIR=/sys/devices/system/cpu/intel_pstate
 CURR_MIN_FREQ="$CPU0_DIR/scaling_min_freq"
 CURR_MAX_FREQ="$CPU0_DIR/scaling_max_freq"
ALLOW_MIN_FREQ="$CPU0_DIR/cpuinfo_min_freq"
ALLOW_MAX_FREQ="$CPU0_DIR/cpuinfo_max_freq"

OLD_IFS=$IFS            # Save current Input File Separtor (IFS)
declare -a Arr          # Array for YAD Window input
NumCPU=$(nproc --all)   # Number of CPUs (nproc from coreutils)

### Error Message Functions ###

Abend () {
    # Abnormal Ending - Parameter 1 = message to display, Parameter 2=exit code

    yad --image "dialog-error" --image-on-top --title "$TITLE - Fatal Error" \
        "$GEOMETRY" --button=gtk-ok:0 --text "$1" 2>/dev/null
    exit "$2"

} # Abend

ErrMsg () {
    # Parmater 1 = message to display

    yad --image "dialog-error" --title "$TITLE - Logical Error" \
        "$GEOMETRY" --button=gtk-ok:0 --text "$1" 2>/dev/null

    fErrMsgForceContinue=true

} # ErrMsg

### Initialize Variables ###

InitVars () {

    [[ ! -e "$ALLOW_MIN_FREQ" ]] && Abend "$ALLOW_MIN_FREQ not found" 11
    AllowMinFreq=$(cat "$ALLOW_MIN_FREQ")
    AllowMinFreq="${AllowMinFreq::-3}"  # Chop off three decimals at end

    [[ ! -e "$ALLOW_MAX_FREQ" ]] && Abend "$ALLOW_MAX_FREQ not found" 12
    AllowMaxFreq=$(cat "$ALLOW_MAX_FREQ")
    AllowMaxFreq="${AllowMaxFreq::-3}"

    [[ ! -e "$CURR_MIN_FREQ" ]] && Abend "$CURR_MIN_FREQ not found" 13
    CurrMinFreq=$(cat "$CURR_MIN_FREQ")
    CurrMinFreq="${CurrMinFreq::-3}"
    NewMinFreq="$CurrMinFreq"

    [[ ! -e "$CURR_MAX_FREQ" ]] && Abend "$CURR_MAX_FREQ not found" 14
    CurrMaxFreq=$(cat "$CURR_MAX_FREQ")
    CurrMaxFreq="${CurrMaxFreq::-3}"
    NewMaxFreq="$CurrMaxFreq"

    if [[ -e "$PSTATE_DIR" ]] ; then
        NumPstates=$(cat "$PSTATE_DIR/num_pstates")
        if [[ $(cat "$PSTATE_DIR/no_turbo") -eq 0 ]] ; then
            TurboBoost="Enabled"
        else
            TurboBoost="Disabled"
        fi
    else
        NumPstates="Not found"
        TurboBoost="Not found"
    fi

    if [[ -e "$CPU0_DIR/scaling_governor" ]] ; then
        Governor=$(cat "$CPU0_DIR/scaling_governor")
    else
        Governor="Not found"
    fi

    if [[ -e "$CPU0_DIR/scaling_cur_freq" ]] ; then
        CurrFreq=$(cat "$CPU0_DIR/scaling_cur_freq")
        # Chop off three decimals at end
        CurrFreq="${CurrFreq::-3}"
    else
        CurrFreq="Not found"
    fi

} # InitVars

### Paint / repaint window and get new frequencies ###

GetParameters () {

    # +------------------------------------------+
    # |  cpuf - Set CPU Min/Max Frequencies      |
    # +------------------------------------------+
    # |                                          |
    # |  Turbo Boost:            Enabled         |
    # |                                          |
    # |  Number of pstates:      99              |
    # |  Speed Governor Used:    powersave       |
    # |  Current CPU0 frequency: 9999 Mhz        |
    # |                                          |
    # |  Current Minimum Freq.:  9999 Mhz        |
    # |  Current Maximum Freq.:  9999 Mhz        |
    # |                                          |
    # |  New Minimum Frequency   9999            |
    # |  New Maximum Frequency   9999            |
    # |                                          |
    # +------------------------------------------+

    IFS="|"
    Arr=($(yad "$GEOMETRY" --form \
        --title "$TITLE" --text "$TEXT" \
        --window-icon="$ICON" --image="$ICON" \
        --field="Turbo Boost:":RO "$TurboBoost" \
        --field="Number of pstates:":RO "$NumPstates" \
        --field="Speed Governor:":RO "$Governor" \
        --field="Current Frequency:":RO "$CurrFreq MHz" \
        --field="Allowable Minimum Frequency:":RO "$AllowMinFreq MHz" \
        --field="Allowable Maximum Frequency:":RO "$AllowMaxFreq MHz" \
        --field="Current Minimum Frequency:":RO "$CurrMinFreq MHz" \
        --field="Current Maximum Frequency:":RO "$CurrMaxFreq MHz" \
        --field="New Minimum Frequency" "$NewMinFreq" \
        --field="New Maximum Frequency" "$NewMaxFreq" 2>/dev/null))

    Return="$?"
    NewMinFreq="${Arr[8]}"
    NewMaxFreq="${Arr[9]}"

} # GetParameters

###################################
#            MAINLINE             #
###################################

ALL_PREFIX="/sys/devices/system/cpu/cpu"
MIN_SUFFIX="/cpufreq/scaling_min_freq"
MAX_SUFFIX="/cpufreq/scaling_max_freq"

while true ; do

    InitVars
    GetParameters
    [[ ! "$Return" -eq 0 ]] && break ; # Exit on Cancel=1 or Close Window=252

    # Sanity checks
    fErrMsgForceContinue=false
    [[ $NewMinFreq -lt $AllowMinFreq ]] && ErrMsg "Minimum frequency too low"
    [[ $NewMaxFreq -gt $AllowMaxFreq ]] && ErrMsg "Maximum frequency too high"
    [[ $NewMinFreq -gt $NewMaxFreq ]]   && ErrMsg "Minimum frequency greater than Maximum Frequency"
    [[ $fErrMsgForceContinue == true ]] && continue

    # Set new Min/Max frequencies
    for (( i=0 ; i<NumCPU ; i++ )) ; do
        # If New Min > Curr Max, set Max first then Min
        if [[ $NewMinFreq -gt $CurrMaxFreq ]] ; then
            echo "$NewMaxFreq""000" > "$ALL_PREFIX$i$MAX_SUFFIX"
            echo "$NewMinFreq""000" > "$ALL_PREFIX$i$MIN_SUFFIX"
        else
            echo "$NewMinFreq""000" > "$ALL_PREFIX$i$MIN_SUFFIX"
            echo "$NewMaxFreq""000" > "$ALL_PREFIX$i$MAX_SUFFIX"
        fi
    done

done

IFS="$OLD_IFS"
exit 0

A: Readers need to understand that is is ATLAS that is annoying here.
Please know that with modern processors the CPU will scale down frequency on its own and as a function of the idle states it goes into when not busy, even in performance mode.
If you want to "pin" the CPU frequencies at maximum then disable all idle states >= 0, in addition to setting performance mode.
NOTE: This will create a lot of waste heat from your processor make sure your system can handle it.
Example:
Starting conditions:
doug@s15:~/idle$ cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_driver
intel_cpufreq
intel_cpufreq
intel_cpufreq
intel_cpufreq
intel_cpufreq
intel_cpufreq
intel_cpufreq
intel_cpufreq
doug@s15:~/idle$ cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
performance
performance
performance
performance
performance
performance
performance
performance

Step 1: How many idle states does my system have?
doug@s15:~/idle$ ls -l -d /sys/devices/system/cpu/cpu*/cpuidle/state*
drwxr-xr-x 2 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu0/cpuidle/state0
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu0/cpuidle/state1
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu0/cpuidle/state2
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu0/cpuidle/state3
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu0/cpuidle/state4
drwxr-xr-x 2 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu1/cpuidle/state0
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu1/cpuidle/state1
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu1/cpuidle/state2
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu1/cpuidle/state3
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu1/cpuidle/state4
drwxr-xr-x 2 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu2/cpuidle/state0
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu2/cpuidle/state1
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu2/cpuidle/state2
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu2/cpuidle/state3
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu2/cpuidle/state4
drwxr-xr-x 2 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu3/cpuidle/state0
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu3/cpuidle/state1
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu3/cpuidle/state2
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu3/cpuidle/state3
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu3/cpuidle/state4
drwxr-xr-x 2 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu4/cpuidle/state0
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu4/cpuidle/state1
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu4/cpuidle/state2
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu4/cpuidle/state3
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu4/cpuidle/state4
drwxr-xr-x 2 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu5/cpuidle/state0
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu5/cpuidle/state1
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu5/cpuidle/state2
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu5/cpuidle/state3
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu5/cpuidle/state4
drwxr-xr-x 2 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu6/cpuidle/state0
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu6/cpuidle/state1
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu6/cpuidle/state2
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu6/cpuidle/state3
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu6/cpuidle/state4
drwxr-xr-x 2 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu7/cpuidle/state0
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu7/cpuidle/state1
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu7/cpuidle/state2
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu7/cpuidle/state3
drwxr-xr-x 3 root root 0 Jul  3 11:41 /sys/devices/system/cpu/cpu7/cpuidle/state4

O.K. I have 5 idle states, 0-4:
Step 2: Disable states 1-4 (I use scripts run as sudo):
doug@s15:~/idle$ cat idle_1-4_disable
#! /bin/bash
echo "idle disable states 1-4:"

/home/doug/idle/idle_state1_disable
/home/doug/idle/idle_state2_disable
/home/doug/idle/idle_state3_disable
/home/doug/idle/idle_state4_disable

doug@s15:~/idle$ cat idle_state1_disable
#! /bin/bash
echo "idle state 1: before:"
cat /sys/devices/system/cpu/cpu*/cpuidle/state1/disable

for file in /sys/devices/system/cpu/cpu*/cpuidle/state1/disable; do echo "1" > $file; done

echo "idle state 1: after:"
cat /sys/devices/system/cpu/cpu*/cpuidle/state1/disable

Resulting in:
doug@s15:~/idle$ sudo ./idle_1-4_disable
idle disable states 1-4:
idle state 1: before:
0
0
0
0
0
0
0
0
idle state 1: after:
1
1
1
1
1
1
1
1
idle state 2: before:
0
0
0
0
0
0
0
0
idle state 2: after:
1
1
1
1
1
1
1
1
idle state 3: before:
0
0
0
0
0
0
0
0
idle state 3: after:
1
1
1
1
1
1
1
1
idle state 4: before:
0
0
0
0
0
0
0
0
idle state 4: after:
1
1
1
1
1
1
1
1
doug@s15:~/idle$

And if we watch all this with turbostat:
doug@s15:~/idle$ sudo turbostat --quiet --Summary --show Busy%,Bzy_MHz,PkgTmp,PkgWatt,GFXWatt,IRQ --interval 15
Busy%   Bzy_MHz IRQ     PkgTmp  PkgWatt GFXWatt
0.02    2743    438     30      3.75    0.12
0.02    2753    406     29      3.75    0.12
0.02    2806    402     29      3.75    0.12
0.02    2764    436     29      3.75    0.12
58.62   3500    70887   50      30.75   0.12  <<<< ilde state 1-4 disabled
100.00  3500    120240  55      50.39   0.12  <<<< tubostat counts idle state 0 as busy
100.00  3500    120243  58      50.95   0.12  <<<< The system is actually still idle.
100.00  3500    120241  60      51.38   0.12
100.00  3500    120248  62      51.91   0.12
100.00  3500    120241  64      52.58   0.12
100.00  3500    120244  65      52.88   0.12
100.00  3500    120252  67      53.13   0.12
100.00  3500    120251  68      53.29   0.12
100.00  3500    120242  68      53.46   0.12
100.00  3500    120268  68      53.56   0.12
100.00  3500    120260  68      53.63   0.12
100.00  3500    120267  70      53.69   0.12

If the processor temperature gets to high, then limit your upper CPU frequency limit. Intel Pstate example:
doug@s15:~/idle$ echo 60 | sudo tee /sys/devices/system/cpu/intel_pstate/max_perf_pct
60

resulting in:
100.00  3500    120267  70      53.96   0.12
100.00  3500    120274  71      53.92   0.12
100.00  3500    120256  70      53.95   0.12
100.00  3500    120277  70      53.93   0.12
100.00  3500    120326  70      53.95   0.12
34.97   3500    42719   48      21.53   0.12
0.02    2712    378     45      4.00    0.12
0.02    2754    396     42      3.96    0.12
0.02    2724    504     40      3.92    0.12
0.02    2816    378     39      3.89    0.12
94.33   3500    113569  60      48.59   0.12
100.00  3500    120242  63      51.88   0.12
100.00  3500    120240  65      52.64   0.12
100.00  3500    120280  68      53.08   0.12
100.00  3500    120333  68      53.32   0.12
100.00  1713    120348  55      20.29   0.12  <<< Had to toggle to powersave governor
100.00  2201    120280  57      26.31   0.12  <<< And then back to performance governor
100.00  2300    120239  56      27.58   0.12  <<< Now new max is in effect.
100.00  2300    120237  56      27.53   0.12  <<< And processor temp is less
100.00  2300    120237  55      27.46   0.12
100.00  2300    120232  54      27.42   0.12


text:
Q: C++ undefined symbol I am creating a C++ console application where I am saving and loading a vector to a file. The file I am saving and loading has a header that has the size of the vector.
Here is my code:
void loadFromFile()
    {
        ifstream iStream("file.ext", ios::binary);
        fileHeader_t fHeader;
        iStream.read((char*)&fHeader, sizeof(fileHeader_t));
        if (fHeader.magicNumber = 0xDEADBEAF)
        {
            appointments.resize(fHeader.appointmentCount); iStream.read((char*)&appointments[0], fHeader.appointmentCount * sizeof(appointment));
        }
    }
    void saveToFile()
    {
        ofstream oStream("file.ext", ios::binary);
        fileHeader_t fHeader;
        fHeader.magicNumber = 0xDEADBEAF;
        fHeader.appointmentCount = appointments.size();
        oStream.write((char*)&fHeader, sizeof(fileHeader_t));
        oStream.write((char*)&appointments[0], sizeof(appointment) * appointments.size());
    }

And here is the header struct:
struct fileHeader_s
{
DWORD magicNumber;
size_t appointmentsCount;
}fileHeader_t;

I am getting the following errors:

E2379 Statement missing ;
  E2451 Undefined symbol 'fHeader'

At the following lines:
fileHeader_t fHeader;

Why is this happening, and more importantly, how can I fix it?
Thanks
Update
Here is my full code:
class appointment
{
public:
    appointment(string aDate, string aTime, string aType,
    string aLocation, string aComments, bool aIsImportant,
    string aReminderDate, string aReminderTime)
    {
        appDate = aDate;
        appTime = aTime;
        appType = aType;
        appLocation = aLocation;
        appComments = aComments;
        appIsImportant = aIsImportant;
        appReminderDate = aReminderDate;
        appReminderTime = aReminderTime;
    }
    void setDate(string aDate)
    {
        appDate = aDate;
    }
    void setTime(string aTime)
    {
        appTime = aTime;
    }
    void setType(string aType)
    {
        appType = aType;
    }
    void setLocation(string aLocation)
    {
        appLocation = aLocation;
    }
    void setComments(string aComments)
    {
        appComments = aComments;
    }
    void setIsImportant(bool aIsImportant)
    {
        appIsImportant = aIsImportant;
    }
    void setReminderDate(string aReminderDate)
    {
        appReminderDate = aReminderDate;
    }
    void setReminderTime(string aReminderTime)
    {
        appReminderTime = aReminderTime;
    }
    string getDate()
    {
        return appDate;
    }
    string getTime()
    {
        return appTime;
    }
    string getType()
    {
        return appType;
    }
    string getLocation()
    {
        return appLocation;
    }
    string getComments()
    {
        return appComments;
    }
    bool getIsImportant()
    {
        return appIsImportant;
    }
    string getReminderDate()
    {
        return appReminderDate;
    }
    string getReminderTime()
    {
        return appReminderTime;
    }
private:
    appointment();
    string appDate;
    string appTime;
    string appType;
    string appLocation;
    string appComments;
    bool appIsImportant;
    string appReminderDate;
    string appReminderTime;
    //person owner;
};

class calendar
{
public:
    calendar()
    {
        loadFromFile();
    }
    ~calendar()
    {
        saveToFile();
    }

    void createAppointment(string aDate, string aTime, string aType, string aLocation, string aComments, bool aIsImportant, string aReminderDate, string aReminderTime)
    {
        appointment newAppointment(aDate, aTime, aType, aLocation, aComments, aIsImportant, aReminderDate, aReminderTime);
        appointments.push_back(newAppointment);
    }

private:
    vector<appointment> appointments;
    string calCurrentDate;
    string calCurrentTime;
    void loadFromFile()
    {
        ifstream iStream("file.ext", ios::binary);
        fileHeader_t fHeader;
        iStream.read((char*)&fHeader, sizeof(fileHeader_t));
        if (fHeader.magicNumber = 0xDEADBEAF)
        {
            appointments.resize(fHeader.appointmentCount); iStream.read((char*)&appointments[0], fHeader.appointmentCount * sizeof(appointment));
        }
    }
    void saveToFile()
    {
        ofstream oStream("file.ext", ios::binary);
        fileHeader_t fHeader;
        fHeader.magicNumber = 0xDEADBEAF;
        fHeader.appointmentCount = appointments.size();
        oStream.write((char*)&fHeader, sizeof(fileHeader_t));
        oStream.write((char*)&appointments[0], sizeof(appointment) * appointments.size());
    }
    typedef struct fileHeader_s
    {
        DWORD magicNumber;
        size_t appointmentCount;
    }fileHeader_t;
};

I am getting the following 2 errors:
[BCC32 Warning] Person.cpp(271): W8060 Possibly incorrect assignment
  Full parser context
    Person.cpp(245): class calendar
    Person.cpp(290): decision to instantiate: void calendar::loadFromFile()
    --- Resetting parser context for instantiation...
    Person.cpp(267): parsing: void calendar::loadFromFile()
[BCC32 Error] vector(608): E2247 'appointment::appointment()' is not accessible
  Full parser context
    vector(607): decision to instantiate: void vector >::resize(unsigned int)
    --- Resetting parser context for instantiation...
    Person.cpp(18): #include c:\program files (x86)\embarcadero\rad studio\9.0\include\dinkumware\vector
    vector(8): namespace std
    vector(330): class vector<_Ty,_Ax>
    vector(607): parsing: void vector >::resize(unsigned int)
Can I please have some help to fix this?

A: You are missing the typedef keyword in struct definition.
typedef struct fileHeader_s
{

}fileHeader_t;

However, in C++ it is not required for the typedef keyword. In that case, struct name is still fileHeader_s.

A: I think what you want is a typedef
typedef struct fileHeader_s
{
DWORD magicNumber;
size_t appointmentsCount;
}fileHeader_t;


text:
Q: Push fields if record is matching in group aggregation in MongoDB I have these "$group" parameters in the aggregation query :
{
 _id: {
    user_uuid: "$actor.user.uuid",

    date_string: {
        $dateToString: {
            format: "%Y-%m-%d",
            date: {
                $toDate: "$time",
            },
            timezone: "America/New_York",
        },
    },

  },

  exit_time: {$max: "$time"},
  entry_time: {$min: "$time"},

  records: {
      $push: {
          time: "$time",
          user_name: "$actor.user.name",
          email: "$actor.user.email",
          door:"$door.name",
          //entry_door:{$cond: { if: { $eq: [ "$entry_time", "$time" ] }, then: "$door.name", else: "$$REMOVE" }},
          //exit_door:{$cond: { if: { $eq: [ "$exit_time", "$time" ] }, then: "$door.name", else: "$$REMOVE" }},

      },
  }

}

and this is my sample document :
{

  "time": {
    "$date": {
      "$numberLong": "1654061180000"
    }
  },

  "actor": {
    "type": "USER",
    "user": {
      "uuid": "6fff0a80-8409-4008-9850-9ec8fb8431ee",
      "name": "firstname lastname",
      "email": "firstname.lastname@example.com",
      "department": "Sales",
      "employee_number": null,
      "cost_center": "USA",
      "role": "ADMIN",

    }
  },

  "door": {
    "uuid": "42ac456e-df9b-4146-afb7-619dd584a524",
    "name": "Door Plaza Parking entry 2",
    "is_elevator_door": false,
    "elevator_door_type": null,
    "is_door_force_masked": true,
    "is_door_held_masked": true,
    "is_door_force_seen": false,
    "is_temperature_screening": false
  },

}

For your understanding this is related to access control. We need to track the attendance according to who is coming and going from the door so for that particular user on that date if user is making first entrance from the door then this is entry time and last exit is exit time.
I am first matching the records and then grouping it as per above query. I want the data of the users on that particular date to track the attendance after calculating the entry and exit time. Till here I am on track and query is fine but with this I also want which is the door from which user entered and which one is the door from which the user took exit because a lot of doors are there but we need to take only entry and exit door.
I was trying the method like at the time of calculating the max and min time I can store the door information at that time but I am not able to figure out what to do. I have commented out the entry and exit door condition because it is not correct.
Please help me out in this.
Let me know if more details are required.
Thanks


text:
Q: Mapping logical expressions to arithmetical expressions I wrote a program that is able to evaluate arithmetical expressions, like
1 + 3.0 * 4 / (1 - 1 * 3.2)

What I want is to use the same program to evaluate logical expressions. For that, suppose $1$ means true and $0$ means false. For example, let's consider the logical operation AND
0 ^ 0 = 0
0 ^ 1 = 0
1 ^ 0 = 0
1 ^ 1 = 1

We could easily represent the AND operator using multiplication
0 * 0 = 0
0 * 1 = 0
1 * 0 = 0
1 * 1 = 1

My question is: given a logical expression (e.g.: $1 \lor \lnot1\land(0\rightarrow 1)$), is there a mapping to turn it into an arithmetical expression such that its evaluation would give the same value than the logical?

A: it depends on the programming language you use, but the answer is yes for most of languages:
for (A AND B) use A * B
for (A OR B) use (A + B) - (A + B) / 2 where "/" is integer division, not real division
for (NOT A) use (A + 1) mod 2
for all other - the answer is yes as soon as you can express them with AND, OR and NOT operations
for example (A => B) = (NOT A) OR B, etc.

A: Yes, this is possible:

*

*NOT(A) = 1-A

*AND(A,B) = A*B = min(A,B)

*OR(A,B) = A+B-A*B = max(A,B)

*IMPLIES(A,B) = 1-A+A*B

*BIIMPLIES(A,B) = 1-|A-B|

*XOR(A,B) = |A-B|


text:
Q: Update de usuário Firebase com Node SDK Estou tentando atualizar dados de login de um usuário do firebase usando o sdk admin do Node. Meu código tem esta aparência:

var uid = req.body.uid;
var objectUpdate = {
    "displayName": "David Coelho"
};
admin.auth().updateUser(uid, objectUpdate)
    .then(função(userRecord) {
        // var id = userRecord.uid;
        //usersRef.child(id).set(userDatabase (req, res))
        res.status(200).json({
            "return": "Atualizar usuário com sucesso"
        })
    })
    .catch(função(erro) {
            res.status(500).json({
                "return": error
            })
        });

Mas não consigo atualizar o usuário. Firebase envia-me a seguinte mensagem de erro:
"Código": "auth / internal-error",
"Mensagem": "Ocorreu um erro interno."

Alguém pode me ajudar?


text:
Q: Armadillo and C++ - Matrix initialization with 2D-array I need to initialize Armadillo matrix with the array of doubles. I've found this constructor in the original documentation:
mat(*aux_mem, n_rows, n_cols, copy_aux_mem = true, strict = true)

and I've found the question about it here on SO:
armadillo C++: matrix initialization from array
The problem is, it appears that the constructor works only for initialization with one-dimensional arrays, not 2D. If I try it to use this way:
double **matrix = new double *[block_size];
for(int i = 0; i < block_size; i++) {
    matrix[i] = new double[block_size];
}

arma::mat arma_matrix( &matrix[0][0], matrix_size, matrix_size, true, true );

cout << "am: " << arma_matrix[1][0] << endl;

I get the error:
fined_grain:103/init_function: In function 'void place_user_fn_103(ca::Context&, ca::TokenList<double>&)':
fined_grain:103/init_function:61:42: error: invalid types 'double[int]' for array subscript

So, what's the ideal way to initialize Arma matrix with 2D-array? I prefer the fastest solution, because I need to use big matrices.

A: I took a quick glance at the armadillo library documentation and I see the following problems.

*

*The argument you are passing to arma_matrix is syntactically right but incorrect. You need to use:
double *matrix = new double [block_size*block_size];
arma::mat arma_matrix( matrix, block_size, block_size, true, true );

*The syntax for accessing the elements is:
cout << "am: " << arma_matrix(1, 0) << endl;

You can also use:
int row = 1;
int col = 0;
cout << "am: " << arma_matrix[row*block_size+col] << endl;


text:
Q: Inverting a Set of Equations Consistently Let $n$ be an integer. Let $x = n/c$, where $c$ is a predetermined constant and let the remainder, $r$, be $r = n - (x \times c)$. We defined two additional integers as follows:

$$ \text{If} \;  r = 0, \text{then} \; k = x \; \text{and} \; l =c;   $$
$$ \text{If} \;  r \neq 0, \text{then} \; k = x + 1 \; \text{and} \; l = r.   $$

I need help with inverting the set of equations. Assume that $k$ and $l$ are given. How does one determine $n$, consistent with the rule above on a case by case basis -- as above. It'd be great for both the cases, someone could give me easily programmable conditions -- ideally in terms of the inputs, $k$ and $l$.

A: If $l=c$, then you're in the first case, and
$$n=cx+r=ck$$
If $l<c$, then you're in the second case, and
$$n=cx+r=cx+l=c(k-1)+l$$


text:
Q: Can't reference existing QML elements from python I do not create the elements dynamically from python, I just intend to access existing elements already declared in the qml file.
I use findChild to get a QObject reference and connect to signals. This works fine, but when I try to be more specific and get a widget (not a QObject) like a QComboBox, I always get None. Am I missing something or findChild is not meant to be used with widgets?
This is my simple qml code:
Window {
    visible:true
    width:600
    height:400

    Button {
        id: clickMe
        objectName: "clickMe"
        x: 244
        y: 263
        text: qsTr("click me!")
    }
   ComboBox {
       id: comboBox
       objectName: "comboBox"
       x: 199
       y: 157
       width: 200
   }
}

And this is my python code:
# qt imports
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QMessageBox
from PyQt5.QtWidgets import QComboBox, QPushButton
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QObject

app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.load('main.qml')
win = engine.rootObjects()[0]
win.show()

# this does work because it is QObject:
clickMe = win.findChild(QObject, "clickMe")
clickMe.clicked.connect(Foo)

# this does not work, I get None so can't add items to the combobox:
comboBox = win.findChild(QComboBox, "comboBox")
comboBox.addItem("a")

sys.exit(app.exec_())

A: First of all, the QML Item Combobox is not a QtWidgets QComboBox so you should not filter using that class, that's why your attempt fails. It is also bad practice to access QML elements from python (or C++) since the life cycle is not managed (for example objects of the same "id" can be deleted and recreated without notifying), instead you must create QObject that allow exchanging information, for example for the QComboBox you can create a model:
main.py
import os
import sys

# qt imports
from PyQt5.QtCore import pyqtProperty, pyqtSlot, QObject, QUrl
from PyQt5.QtGui import QGuiApplication, QStandardItem, QStandardItemModel
from PyQt5.QtQml import QQmlApplicationEngine

CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))

class Manager(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._model = QStandardItemModel()

    @pyqtProperty(QObject, constant=True)
    def model(self):
        return self._model

    @pyqtSlot()
    def foo(self):
        print("clicked")

def main():
    app = QGuiApplication(sys.argv)

    manager = Manager()

    engine = QQmlApplicationEngine()
    engine.rootContext().setContextProperty("manager", manager)

    filename = os.path.join(CURRENT_DIR, "main.qml")

    engine.load(QUrl.fromLocalFile(filename))

    item = QStandardItem("a")
    manager.model.appendRow(item)

    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

main.qml
import QtQuick.Window 2.15
import QtQuick.Controls 2.15

Window {
    visible:true
    width:600
    height:400

    Button {
        id: clickMe
        x: 244
        y: 263
        text: qsTr("click me!")
        onClicked: manager.foo()
    }
   ComboBox {
       id: comboBox
       x: 199
       y: 157
       width: 200
       model: manager.model
       textRole: "display"
   }
}

I recommend you also read my other answers:

*

*How to connect Python and QML with PySide2?

*How Can I Update a Qml Object's Property from my Python file?


text:
Q: Generate a sequence of numbers I want to create sequence numbers in asp.net mvc2..
Then number should start from { 0 to 1000}. I tried like following,
 var seq = Enumerable.Range(1, 1000);
        ViewData["OrderNo"] = seq;

In view:
 <%:Html.Hidden("OrderNo") %>
            <%:ViewData["OrderNo"] %>

My result is
System.Linq.Enumerable+<RangeIterator>d__b8

But when getting value in view it is not working... How to generate sequential numbers?

A: It's unclear what you mean or what you consider a failure, but the parameters of Enumerable.Range are start and count, not start and end.
If you want to generate numbers that start from 0 and end at 1000 you will have to write:
Enumerable.Range(0,1001);

If you have a different problem (eg the sequence doesn't persist between user calls, or from user to user or whatever), you will have to be specific.
Perhaps what you mean is that the IEnumerable you store in the ViewData doesn't get persisted as you expected in the View? That's because Range returns an object that implements IEnumerable and uses deferred execution to produce the requested values. Unless you force the enumeration with a for or a ToArray() the numbers will not be generated at all. Storing the object somewhere doesn't force an enumeration.

A: If you want to enumerate a sequence of numbers (IEnumerable<int>) from 0 to a variable end, then try
Enumerable.Range(0, ++end);

In explanation, to get a sequence of numbers from 0 to 1000, you want the sequence to start at 0 (remembering that there are 1001 numbers between 0 and 1000, inclusive).

If you want an unlimited linear series, you could write a function like
IEnumerable<int> Series(int k = 0, int n = 1, int c = 1)
{
    while (true)
    {
        yield return k;
        k = (c * k) + n;
    }
}

which you could use like
var ZeroTo1000 = Series().Take(1001);

If you want a function you can call repeatedly to generate incrementing numbers, perhaps you want somthing like.
using System.Threading;

private static int orderNumber = 0;

int Seq()
{
    return Interlocked.Increment(ref orderNumber);
}

When you call Seq() it will return the next order number and increment the counter.


text:
Q: Laravel Create Model for a pivot table I have a MenuItem model which uses menu_items table with the following fields:
$table->bigIncrements('id');
            $table->string('name')->nullable(false);
            $table->unsignedBigInteger( 'category_id')->nullable(false);
            $table->text('description')->nullable();
            $table->string('image')->nullable();
            $table->decimal('price')->nullable(false);
            $table->boolean('available')->default(true);
            $table->boolean('active')->default(true);
            $table->timestamps();

            $table->foreign('category_id')
                ->references('id')
                ->on('categories');

Now, there are certain menu items which can have sides. These sides are also menu items and are defined by its category (side category).
For instance: I wanna have a MenuItem that belongs to a MainDish category. For this special category a menu item can have sides. These sides are also MenuItem. So I want to store the sides associated to a MainDish.
To do so, I've created a menu_item_sides migration:
Schema::create('menu_item_sides', function (Blueprint $table) {
            $table->primary(['main_item_id', 'side_item_id']);
            $table->unsignedBigInteger('main_item_id');
            $table->unsignedBigInteger('side_item_id');
            $table->timestamps();

            $table->foreign('main_item_id')
                ->references('id')
                ->on('menu_items')
                ->onDelete('cascade');

            $table->foreign('side_item_id')
                ->references('id')
                ->on('menu_items')
                ->onDelete('cascade');

        });

and its respective MenuItemSide model. As you can see, menu_item_sides has a composite key with
main_item_id', 'side_item_id' and both keys point to the same PK in menu_items.
In this specific case, how do I declare the relationships between the MenuItem and MenuItemSide models?

A: In addition to customizing the name of the joining table, you may also customize the column names of the keys on the table by passing additional arguments to the belongsToMany method. The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:
  #Example for MenuItem model
public function menuItemSides()
{
    return $this->belongsToMany('App\MenuItemSide', 'menu_item_sides', 'main_item_id', 'side_item_id');
}

#Example for MenuItemSide model
public function menuItems()
{
    return $this->belongsToMany('App\MenuItem', 'menu_item_sides', 'side_item_id', 'main_item_id');
}

Or See: https://laravel.com/docs/6.x/eloquent-relationships#many-to-many


text:
Q: Python Writing To CSV All in One Cell I'm trying to shave the top 7 lines off a csv file.
There is probably a more concise way to do this, but right now I am reading one file and writing each line other than the first 7 to another file. When I write to the file though, all the contents for the line show up in the first cell instead of spread out in organized columns.
Here is my code:
with open('file1.csv', 'r') as file_org:
    with open("file2.csv","w") as file_stripped:
        writer = csv.writer(file_stripped)
        for i, line in enumerate(file_org, -7):
            if i>=0:
                writer.writerow([line])

Thank you!

A: reading in csv do need you to specify the seperator, which is usually ";", you can find the constructor usage in manual, and you should open the file and see the content, not by some other tool like excel
if you are not meant to change the content, you could just treat them as normal files / line, or just by
line.split(";")

or
";".join(splited_line)

manully


text:
Q: Does cudpp only work for devices of a certain compute capability I want to use cudpp. I am curious if it only works for devices of a certain compute capability ?
If yes, what is the lower bound.
I found this error message in their hash table implementation code:
"Error in cudppHashTable call in testHashTable (make sure your device is at                      least compute version 2.0\n"
I dont know which compute version they are referring to??

A: For as far as I'm aware, there are no restrictions with regards to compute capability. There are some optimizations for cards with a Fermi architecture (sm_20) according to the change logs.
CUDPP 2.0 does however state it only works for CUDA 3.0 or higher (and they advice to use versions higher than 3.2), but this has no direct relation to compute capability.
Update:
As found by the OP, there is indeed functionality which explicitly requires a 2.0 architecture, such as cudppHashTable. As per the doc in the source (line 206):

The hash table implementation requires hardware capability 2.0 or
  higher (64-bit atomic operations).

From the wording I would assume there are special cases in which a certain compute capability is required, but it is not a general requirement.


text:
Q: Number of independent KCL equations? When using nodal analysis, my book says you will always end up with \$n-1\$ linearly independent equations, where \$n\$ is the number of nodes.
Can someone intuitively explain why this is true? If it's too hard too give intuition, I'll settle for a formal proof.


text:
Q: Can't copy from Samba shares after upgrade to 18.04 A server "S" runs Ubuntu 18.04 LTS and Samba 4.7.6-Ubuntu.   smb.conf has been left with all the default settings, except for workgroup name changed, and the following blocks added at the bottom:
[lan_share]
   path = /disk2
   browseable = yes
   read only = yes

[lan_share_1]
  path = /disk1
  browseable = yes
  read only = yes

[lan_share_3]
  path = /disk3
  browseable = yes
  read only = yes

When the client was Debian 8 with packages samba and 'cifs-utils`, everything worked as expected, including ability to copy from the client-mounted  share to local disks.
Now new client, workstation "W", is running Ubuntu 18.04 LTS with the latest samba and cifs-utils, and copying from shares to local is not working.
The shares on W are set up by lines in /etc/fstab as follows:
//192.168.1.233/lan_share_1 /disk1     cifs  credentials=/etc/samba/user,noexec  0 0
//192.168.1.233/lan_share   /disk2     cifs  credentials=/etc/samba/user,noexec  0 0
//192.168.1.233/lan_share_3 /disk3     cifs  credentials=/etc/samba/user,noexec  0 0

There's a credentials file at the path listed above which, again, works fine with Debian, and probably is OK on Ubuntu too, as there are no error messages about permissions.
All this has been copied exactly from the Debian client which had no problem.  Now an attempt to copy a directory tree thru the GUI file browser - say, from /disk2 to home directory - will appear to succeed at first, then the progress dialog freezes partway thru and can't even be cancelled.  The progress dialog remains until the Thunar (file browser) process is killed - unless the user clicks the big red "Cancel" icon, in that case the dialog says "Cancelling..." until the process is killed.  Only the first few files get copied.
I've checked that:

*

*workgroup name is the same on both server and client

*ufw on the server allows the ports in "samba" application profile

*files in the share are OK on the server (accessible via SSH, SCP)

*everything else works correctly on the client

I still have the Debian system where everything works normally when connecting to the same share - a whole directory structure can be copied from the share to local thru the GUI. Web searching has found various other Samba issues, some relating to going from earlier versions to Ubuntu 18, but none quite describing this situation.
Update: This ("Trouble mounting cifs shares after upgrade to 17.10") looked promising. I found out the "noexec" is unnecessary (1) and based on the former page, I replaced the ",noexec" with ",vers=2.1".
Also, on the server, did this: sudo chmod-R 775 /disk2.  And with one or both of these changes in place, I can now successfully copy from the locally mounted share to home directory using command line - but it still makes Thunar hang.  Now thinking it may be at least partially a GUI problem.
Update: Thanks Terrance, I'm going to check out NFS right away. I don't have Windows clients and if it's less problematic, well I just need the functionality.

A: I had the same problem with Linux mint xfce 19.1 and 19.0. First I had a problem with my "WD My Book Live" NAS server. I solved this with adding vers=2.0 in fstab (I tried vers 3.0 2.1 and 2.0 and chose the highest working version). First I thought the problems were solved, but later there were sometimes problems with copying files from the NAS. The problem only appears while copying files with extension html ,gif,ico and txt (but makes a good copy of the problem files). After making a copy of these files, the copy process freezes. Copying files with extension flac, zip and tar.gz was no problem. When copying multiple files, the copy process freezes when it reaches the problem files.
I solved it by changing vers=2.0 to vers=1.0 in fstab.
There seems to be a compatibility problem with version 2.0? With testing the NAS connection, I used a 3 Gb iso file. I don't copy much of those problem files (may be there are more problem extensions) from my NAS, so the problems mostly keeps invisible. But after some times I understand there was a structural problem with some extensions. And maybe the extensions are not the problem, but may be the sizes of the files are the problem. With my example files the problem files were small!