text:
Q: Drag and Drop at particular Location + Occupy space available in Main Div As You can see in Figure 1 .
I have a Main div - which is Droppable
With Four Draggables namely A , B , C , Fit.
On drag Of A , B or  C div  into the droppable Main Div - It occupies the space as shown in Fig 2 (shows when I drag A into the Main Div ).Now if I drag another div (A , B or C) then it should occupy the space with respect to their width size. (height is same as Main Div)
Fig 1

Fig 2

Now if I drag the 4th draggable div i.e with name Fit then a div should be formed inside the Main div with the width equal to whatever space is left in the two adjacent Divs in Main div.
For example : . Suppose 10px space is between A and B (inside Main) and between B and c , space is 40px , So if i Drop FIT in between A and B then a div should be formed with their space difference i.e 10px , similarly 40px div should be formed in between B and C on drag of FIT
It shouldn't squeeze the divs present in the Main Div , neither it should overflow Main DIv
Please Let me know How I can Place the Draggables A, B and C inside the Main div at the user positioned location, without Disturbing the Main div Width.
What I have done is
I made div's A , B , C as draggable
$(".classname").draggable({
  helper: 'clone',
  stop: function(event, ui) {
  }
});

and main div Droppable:
$(".maindivclass").droppable();

and on drop of the draggables , I am making those Divs Draggable inside the main div
$("#" + Dropped_div_id).draggable({
  axis: 'x',
  containment: "#Main_divID",
});

But on drop of A, B and C , It always occupies the center location and right now I can drop any number of divs inside the Main div. Please tell me how to make draggables position the exact location where User is dropping and summation of width of all divs dropped should be always equal to the Main div width. Maybe Grid is the solution, but I have dynamic Width divs to drop.
I researched a lot and found something - 10 % relevant to my task is this http://gridster.net/ - But here the container is not fixed height or width. In my case Height of all divs are the same. Only width varies.
More Addtional Info When Asked in comments:
1) When A, B, or C is dragged and dropped to Main, you want the item to be appended into Main.
2) When another is dragged, it should not be dropped / overlap on other divs already present in Main.
3)  On drag of Fit, Whatever space left in the Main should become occupied. I mean div with respective width should be created as per the space left in Main div

A: That was Fun and Dirty.
Made you an example that basically does two extra things:

*

*Keeps track of the "Dropped" elements positions.

*Calculates the distance between two elements (or sides) when you drop the FIT element.

JSnippet "Drag and Fit" :)
The code obviously need immprovement but I'm sure it will help you get on track.
JS code:
$(function() {
    var set = {
        appendClass: 'added',
        area: { s:"#droppable", w:0, left:0 },
        added : [],
    };
    $( ".exact-pos, #drag_fit" ).draggable({
        revert: "invalid",
        appendTo: ".wrap",
        helper: "clone"
    });
    $( "#droppable" ).droppable({
      accept:".exact-pos, .fill",
      drop: function( event, ui ) {
        var $area = $(this);
        var $origin_ele = $(ui.draggable).clone();
        var $ele_clone = $area.closest('.wrap').find('.ui-draggable-dragging').eq(0);
        var mes = {};
        set.area.w = $area.outerWidth();
        set.area.l = $area.offset().left;
        if (!$origin_ele.hasClass("fill")) { // Handle non fit
             mes = { // measure
               s:$origin_ele.attr('class') + " " + set.appendClass,
               l:$ele_clone.offset().left - set.area.l,
               w:$(ui.draggable).outerWidth(),
               r:0
             }
             //Check borders:
             if (mes.l < 0) { mes.l = 0; }
             if (mes.l + mes.w > set.area.w) { mes.l = set.area.w - mes.w; }
             //Set right side:
             mes.r = mes.l + mes.w;
             var revert = false;
             //Check overlaping left:
             $.each(set.added, function(index, ele) {
                if (mes.l >= ele.l && mes.l <= ele.r) {
                   mes.l = ele.r;
                   mes.r = mes.l + mes.w;
                }
             });
             //Check overlapping right: will revert
             $.each(set.added, function(index, ele) {
                if (mes.r >= ele.l && mes.r <= ele.r) {
                    revert = true;
                } else if (mes.r >= ele.r && mes.l <= ele.l) {
                    revert = true;
                } else if (mes.r > set.area.w) {
                    revert = true;
                }
             });
             //append or revert
             if (!revert) {
                ui.draggable.draggable('option','revert',false);
                $area.append($origin_ele.addClass("added").css({"left":mes.l}));
                set.added.push($.extend(true, {}, mes));
             } else {
                ui.draggable.draggable('option','revert',true);
             }
        } else {
            var f = { l:0,w:0,r:0 };
            var c = $ele_clone.offset().left - set.area.l + ($(ui.draggable).outerWidth() / 2);
            var betw = -1;
            var fleft = 0;
            var fright = 0;
            var revert = false;
            //sort by position:
            set.added.sort(function(a, b) {
                return a.l - b.l;
            });
            //after which elemnt:
            $.each(set.added, function(index, ele) {
                if (ele.r < c) { betw = index; }
             });
            //calc dim:
            if (betw == -1 && set.added.length == 0) {
                fright = set.area.w;
            } else if (betw == -1 && set.added.length > 0) {
                fright = set.added[0].l;
            } else if (betw == set.added.length - 1) {
                fleft = set.added[betw].r;
                fright = set.area.w;
            } else if (typeof set.added[betw + 1] != 'undefined') {
                fleft = set.added[betw].r;
                fright = set.added[betw + 1].l;
            }
            if (fright - fleft > 1) {
                f.l = fleft;
                f.w = fright - fleft;
                f.r = f.l + f.w;
            } else {
              revert = true;
            }
            //append or revert:
            if (!revert) {
                ui.draggable.draggable('option','revert',false);
                $area.append($origin_ele.addClass("added").css({"left":f.l, width:f.w}).text(""));
                set.added.push($.extend(true, {}, f));
             } else {
                ui.draggable.draggable('option','revert',true);
             }
        }
      }
    });
    $('#resetAll').click(function resetAll() {
        set.added = [];
        $(set.area.s).find('div').fadeOut(function(){ $(this).remove(); });
    });
});

A: This answer is not fully complete, yet it is very functional and I plan on updating it. This currently will perform the following functions:

*

*Drag an A, B, C, or Fit object into the Main area

*Drag/Move an object that is already in the Main area

*Drag other A, B, C, or Fit object into Main area but not on top of existing objects

*Reset for more testing

*If Fit object is dragged into Main area, and no other objects exist, it will fill the entire area

*If Fit object is dragged into Main area that contains objects, will determine the remaining space between objects and boundry of Main area and will fill the area left or right of existing objects

Current working example: https://jsfiddle.net/Twisty/35nd6y3g/10/
HTML

Main Div - droppable

drag A

drag B

drag C

fit

<button id="resetBtn">Reset</button>
<input type="text" id="leftDetails" style="width: 75%" />

CSS
body {
  overflow: hidden;
}

.wrapper {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  height: 450px;
}

.box {
  border: 1px solid black;
  display: flex;
  //justify-content: center;
  align-items: center;
}

#main {
  position: relative;
  width: 150px;
  height: 450px;
}

#main .box {
  background: #9d9d9d;
}

#a {
  width: 30px;
  height: 450px;
}

#b {
  width: 45px;
  height: 450px;
}

#c {
  width: 75px;
  height: 450px;
}

#fit {
  width: 30px;
  height: 40px;
}

jQuery
$(document).ready(function() {
  console.log("Main: " + $("#main").position().left + " Drag A: " + $("#a").position().left + "Drag B: " + $("#b").position().left + " Drag C: " + $("#c").position().left);
  var mainBoxes = {};
  $("#resetBtn").click(function() {
    $("#main").find("div.box").remove();
    mainBoxes = {};
  });
  var dragOrig;
  $(".draggable").draggable({
    containment: "#main",
    axis: "x",
    revert: true,
    start: function(e, ui) {
      dragOrig = ui.position;
    },
    drag: function(e, ui) {
      $("#leftDetails").val(ui.helper.text() + " pos left: " + ui.position.left + " off left: " + ui.offset.left);
      if (Object.keys(mainBoxes).length === 0) {
        return;
      }
      var offLeft = ui.offset.left - $("#main").offset().left;
      var offRight = offLeft + ui.helper.width();
      //var offMouse = e.clientX - $("#main").offset().left;
      $.each(mainBoxes, function(k, v) {
        if (offLeft >= v.left && offLeft <= v.right) {
          ui.position.left = ui.position.left + v.right;
          console.log("Info: Left Edge collided with ", k, ui.position);
        }
        if (offRight > v.left && offRight < v.right) {
          //ui.position.left = ui.position.left + (v.left - ui.helper.width());
          ui.position.left = ui.position.left + v.right;
          console.log("Info: Right Edge collided with ", k, ui.position);
        }
      });
    },
  });
  $(".droppable").droppable({
    hoverClass: "hover",
    accept: ".box",
    drop: function(event, ui) {
      // add functionality here
      //var pos = ui.position;
      var off = ui.offset;
      var c = $("#main .box").length + 1;
      var $newBox = ui.draggable.clone();
      if (ui.draggable.attr("id") === "fit") {
        console.log("Info: Adding 'fit' class");
        $newBox.addClass("fit");
        if (Object.keys(mainBoxes).length === 0) {
          console.log("Info: No other boxes found. Set Max Width.");
          $newBox.css({
            width: "150px",
            height: "450px",
            left: "-1px"
          });
        } else {
          var lefts = Object.keys(mainBoxes).map(function(k) {
            return mainBoxes[k].left;
          });
          var rights = Object.keys(mainBoxes).map(function(k) {
            return mainBoxes[k].right;
          });
          var minLeft = Math.min.apply(null, lefts);
          var maxRight = Math.max.apply(null, rights);
          if ((ui.offset.left - $("#main").offset().left) + ui.helper.width() < minLeft) {
            console.log("Info: 'fit' dropped left of boxes.");
            $newBox.css({
              width: minLeft + "px",
              height: "450px",
              left: "-1px"
            });
            $newBox.data("width", minLeft);
            console.log("Info: ", minLeft, maxRight, $newBox[0]);
          }
          if ((ui.offset.left - $("#main").offset().left) > maxRight) {
            console.log("Info: 'fit' dropped right of boxes.");
            $newBox.css({
              width: (150 - maxRight) + "px",
              height: "450px",
              left: maxRight + "px"
            });
            $newBox.data("width", 150 - maxRight);
            console.log("Info: ", minLeft, maxRight, (450 - maxRight), $newBox[0]);
          }
        }
      } else {
        $newBox = ui.draggable.clone();
        if ($newBox.hasClass("new")) {
          $newBox.removeClass("new");
        } else {
          return;
        }
      }
      console.log("Info: Removing .draggable");
      $newBox.removeClass("draggable");
      console.log("Info: Setting ID = box" + c);
      $newBox.attr("id", "box" + c);
      $newBox.draggable({
        containment: "#main",
        axis: "x",
        drag: function(e, ui) {
          if (Object.keys(mainBoxes).length === 0) {
            return;
          }
          var offLeft = ui.offset.left - $("#main").offset().left;
          var offRight = offLeft + ui.helper.width();
          $.each(mainBoxes, function(k, v) {
            if (k == ui.helper.attr("id")) {
              return false;
            }
            if (offLeft > v.left && offLeft < v.right) {
              ui.position.left = v.right;
              console.log("Left Edge Collison with ", k);
            }
            if (offRight > v.left && offRight < v.right) {
              ui.position.left = v.left - ui.helper.width();
              console.log("Info: Right Edge Collision with ", k);
            }
          });
        },
        stop: function(e, ui) {
          mainBoxes[ui.helper.attr("id")] = {
            left: ui.offset.left - $("#main").offset().left,
            right: (ui.offset.left - $("#main").offset().left) + ui.helper.width()
          };
          console.log("Info: Updating ", ui.helper.attr("id"), mainBoxes);
        }
      });
      if ($newBox.draggable("instance") !== "undefined") {
        console.log("box" + c + ": is draggable.");
      }
      $newBox.css({
        left: $newBox.hasClass("fit") ? $newBox.css("left") : (off.left - $("#main").offset().left) + "px",
        top: "-1px",
        position: 'absolute',
        height: "450px",
        width: $newBox.hasClass("fit") ? $newBox.css("width") : ui.draggable.width() + "px"
      });
      console.log("box" + c + ": ", $newBox[0], " now being appended.");
      $("#main").append($newBox);
      mainBoxes['box' + c] = {
        'width': $newBox.width(),
        'left': off.left - $("#main").offset().left,
        'right': (off.left - $("#main").offset().left) + $newBox.width()
      };
      console.log("Added: ", $newBox.attr("id"), mainBoxes);
    }
  });
});

As mentioned, this is nearly complete. Due to the use of Viewport Units, positioning is being thrown off. This is not a good use case, but it's what I started with from the fiddle that was offered up.
To track object, I created an Object called mainBoxes. This gets updated when an object is dropped into the droppable. Each index contains a left, right, and width that is populated from the offset left position value. mainBoxes is used for collision detection when dragging further objects and to calculate the width forfit` objects.
We have 2 drag scenarios, dragging a new item into the Main are or moving an item that is already there. When we drag and drop a new item, it is updated, draggable is destroyed, draggable is reset with new properties, and we append it into #main. Draggable by default does not append elements, it simply changes it's position on the page. Thus, the div would be moved, but would never be a child of #main.
The Viewport units created challenges to collision detection and the prevention of dragging an object onto another existing object. I have added lots of details to console for a clear understanding of all the activity. I plan to address this by converting all the lengths and positions to Pixel units.
This should get you going. I also found the following plugin: https://sourceforge.net/projects/jquidragcollide/ I may investigate if this is a better tool to make use of.


text:
Q: MongoDB: aggregating data in lower levels I have a mongoDB database, called trips with the following structure:
{'Name': 'Joe Doe',
 'WentTo' :
   [{ 'Destination':
      { 'City': 'Tirana',
        'Country': 'Albania'}},
    { 'Destination':
      { 'City': 'Bari',
        'Country': 'Italy'}},
    { 'Destination':
      { 'City': 'Pisa',
        'Country': 'Italy'}} }] }
{'Name': 'Jane Doe',
 'WentTo' :
   [{ 'Destination':
      { 'City': 'Perth',
        'Country': 'Australia'}},
    { 'Destination':
      { 'City': 'Bern',
        'Country': 'Switzerland'}},
    { 'Destination':
      { 'City': 'Rome',
        'Country': 'Italy'}} }] }

I would like to list the travelers that have been to Italy and the number of times they have been there, like this:
{ "Name" : "Joe Doe", "Times in Italy" : 2 }
{ "Name" : "Jane Doe", "Times in Italy" : 1 }

I came up with this approach but MongoDB doesn't output anything.
db.trips.aggregate([ {$unwind:'$WentTo.Destination'},
{$match: {'Country':'Italy'}}, {$group:{_id:'$Name', Times in Italy:{$sum:1}}}])

Any ideas?

A: Maybe something like this:
Option 1:
$filter/$size (Faster and effective when there is no duplicate records with same name )
db.collection.aggregate([
{
"$addFields": {
  "WentTo": {
    $size: {
      "$filter": {
        "input": "$WentTo",
        "as": "w",
        "cond": {
          "$eq": [
            "$$w.Destination.Country",
            "Italy"
          ]
        }
       }
     }
   }
  }
},
{
   $project: {
     "Times in Italy": "$WentTo",
     Name:1
   }
 }
])

Explained:

*

*Use addFields with $filter to match only array elements having Italy as Country and count them with $size

*Project the "WentTo" array as "Times in Italy" and Name as per requested.

Playground 1
Option 2:
This is your query with small corrections that is also covering the case when there is dulicated records per name  ,please, note for bigger collections $unwind operation can be performance impacting and slow ...
 db.collection.aggregate([
 {
   $unwind: "$WentTo"
 },
 {
  $match: {
    "WentTo.Destination.Country": "Italy"
  }
 },
 {
  $group: {
    _id: "$Name",
      "Times in Italy": {
        $sum: 1
    }
   }
  }
 ])

Playground 2

redpajama_set_name: RedPajamaStackExchange


text:
Q: buildTypes not working build.gradle Android Studio I am new to Android studio and I need to add:
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        debuggable true
    }
}

in my build.gradle Android Studio, but getting error:

Gradle DSL method not found:'buildTypes()'

A: Try to configure buildTypes from "File-> Project Structure" and select your module, you can easily configure everything on the right side panel.

A: are you sure that your build file is set up correctly?
The buildTypes have to be in the android closure. It should look something like this
note: this is just a example you can't just copy and paste this
android {
compileSdkVersion "Google Inc.:Glass Development Kit Preview:19"
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "com.your.package"
    minSdkVersion 19
    targetSdkVersion 21
    versionCode 1
    versionName "1.0"
}

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

Hope this is of use for you


text:
Q: How to hide links from ui-grid after click in AngularJS? Using Angular-UI-Grid... I have the following data (paginated):
Name | Link
A | Show Hide
B | Show Hide
In my options:
cellTemplate:'
' +
               '  Show Hide' +'
' }

How can I make it such that if I click "Show", hide is displayed for that specific row. If I click "Hide", then "Show" is displayed for that specific row?

A: I would use a boolean to keep track of what is being shown.
Then in your methods invert your boolean.
As an example:
   $scope.isShowing = true;

Then modify your anchors.
 Show

and
Hide' +'
'

and in your show/hide methods
$scope.isShowing = !$scope.isShowing

A: @Ashley Kurkowski in Angular ui-grid you wont have access to isShowing in your appScopeProvider scope. But with a slight adjustment your approach is correct.
cellTemplate: '
Show Hide
'

I created a Plunkr for that.


text:
Q: Evaluating $ \lim_{n \to \infty} {\sqrt[n]{\frac{(2n - 1)!}{n!}}} $ I have such limit to solve:
$$
\lim_{n \to \infty} {\sqrt[n]{\frac{(2n - 1)!}{n!}}}
$$
I understand that with the n-root I should go to $e^{\ln n}$, but the real problem cause factorials. What can I do with them?

A: $$\sqrt[n]{\frac{(2n-1)!}{n!}}=\sqrt[n]{\prod_{k=1}^{n-1} (n+k)}\ge
\sqrt[n]{\prod_{k=1}^{n-1} n}= \sqrt[n]{n^{n-1}}=n(\sqrt[n]{n})^{-1}\to+\infty$$
because $\sqrt[n]{n}\to 1$

A: Hint: Use Stirling's approximation
\begin{align*}
n!\sim\sqrt{2\pi n}\left(\frac{n}{e}\right)^n
\end{align*}

A: Consider the more general problem of
$$\lim_{n \to \infty} {\sqrt[n]{\frac{(an +b)!}{n!}}}$$ Let
$$A_n={\sqrt[n]{\frac{(an +b)!}{n!}}}\implies \log(A_n)=\frac 1n \left(\log[(an+b)!]-\log(n!]\right)$$ Using twice Stirling approximation and continuing with Taylor series for large $n$, then
$$ \log(A_n)=a\log(a)+(a-1)\log \left(\frac{n}{e}\right)+\frac{\left(b+\frac{1}{2}\right) \log (a)+b \log (n)}{n}+O\left(\frac{1}{n^2}\right)$$ Notice that $b$ does not play any role in the limit.
Now, consider the three cases : $0<a<1$, $a=1$ and $a>1$

A: The key is that
$(n!)^{1/n} \approx \dfrac{n}{e}
$
and
$n^{1/n}\to 1$
So
$\begin{array}\\
\left(\dfrac{(2n - 1)!}{n!}\right)^{1/n}
&=\dfrac{(2n - 1)!^{1/n}}{n!^{1/n}}\\
&=\dfrac{(2n)!^{1/n}}{(2n)^{1/n}n!^{1/n}}\\
&\approx\dfrac{((2n)!^{1/(2n)})^2}{(2n)^{1/n}n!^{1/n}}\\
&\approx\dfrac{(2n/e)^2}{n/e}\\
&\approx \dfrac{4n}{e}\\
&\to \infty\\
\end{array}
$


text:
Q: What is the nginx equivalent of worker and prefork MPMs in Apache? I'm seriously considering the switch from Apache to nginx, and I'd like to understand nginx better - I'm no Apache guru either, so I think I'll learn more about Apache in the answers to these questions. I think it will be apparent from my questions that I really have a lot to learn in this area and have probably misunderstood much. But that's why I'm asking:

*

*So does nginx have no equivalent of Apache's prefork MPM? If so,
then how is nginx different from the worker MPM? And if it's like
the worker MPM, then why aren't there the same concerns about thread
safety which make people not use Apache's mod_php with a worker MPM?

*If a process is an OS process, and a process can
have multiple threads (similar to Java where java executable is the
single process and it can start multiple threads), how do
'requests' fit into this model? I understand that a client
request doesn't result in a new OS process with nginx, but does it result in a
new thread or can a thread handle multiple simultaneous requests? Or if not, then multiple sequential connections where when a thread has finished with one request it can handle another?

*What is the relationships between 'requests' and 'connections'? If a client makes 10 requests, are these 10 connections, or is it 1 connection? How long does a connection last? I realize that if a client makes 10 requests over a period of a month, those could be part of the same session (if the session cookie persists), but surely that wouldn't be the same connection. So where's the line drawn for what constitutes a connection?

*What are the different ways of using PHP from nginx? Unless I'm
mistaken, Apache has 3 (mod_php, mod_fastcgi, and mod_fcgid). For
nginx I've heard of PHP-FPM and FastCGI. Are there other options or
are these the only 2 ways, and if so how do they differ from each
other? I keep reading the PHP-FPM is another way of doing FastCGI
so I'm not exactly sure what the difference is.

*If there are 10 clients connected to the server accessing PHP pages,
how many processes will I see when running the 'top' command if using
nginx, and what will they be named? (I imagine the answer depends on the response to the question in the previous paragraph.) If this was with Apache prefork MPM and
mod_php, if I understand correctly then I think I'd see 10 httpd
processes when running 'top'.

*How many ports on my server will now be occupied? Before it was just port 80 by Apache. Now I imagine there'll be port 80 by nginx, plus some other port for nginx to communicate with the thing that's actually processing the PHP. And what exactly is that thing that runs the PHP, is it the 'PHP' executable, or 'FastCGI', or something else?

*So if nginx is configured to use multiple 'backend' PHP processors (is this possible?) how many APC instances will there be? And how would requests from nginx be handed to them (e.g. would it use the session cookie to send the same user back to the same PHP processor?)
So many questions, I know, but hopefully some out there who actually understand all this can help me understand as well. I really want to! Thanks.

A: This article should answer pretty much everything: http://arstechnica.com/business/news/2011/11/a-faster-web-server-ripping-out-apache-for-nginx.ars about Apache v.s. Nginx
As for the other questions:
3) A request is just that, a request for some resource on the server. GET /index.html is one request. POST /formhandler.php is another request. A connection is the literally TCP socket setup that links the client browser to the server. A connection is what the request will travel through. One connection can handle multiple requests, or it can handle only one request. It depends on if HTTP Keep-Alives are allowed/requested, and what mood the client and server are in that day. Best case, 1 connection handles 10 requests, requiring only one TCP handshake sequence. Worst case, each request goes over a separate connection, requiring 10 tcp handshakes.
6) There'll be one or two listening ports open on the server (port 80 for regular, 443 for ssl, maybe). Any number of requests can be multiplexed onto a single port. There'll never be LESS than one port held open by the webserver, but should never really be more than 1 or 2 either.


text:
Q: Pull Django App from Heroku I have built a web app using Django and I'm using Heroku to host it. There is a form where users can enter information and that information is stored in a database (db.SQLITE3). So everything is getting stored in the database which is on the server. Next time when I'm pushing my project after making some changes, the updated server database is getting replaced by my backdated local database which basically deletes the new information. So, I realized, I have to pull (Obviously) the server side code first before making the changes.
I have tried

    heroku db:pull

which gives an error

    db:pull is not a heroku command.
    !    Perhaps you meant pg:pull?

So I tried

    heroku pg:pull DATABASE_URL db --app mywebapp

which is giving an error

    heroku-cli: Pulling postgresql-reticulated-26036 ---> db
    'createdb' is not recognized as an internal or external command,
    operable program or batch file.

I'm really confused now, can someone please tell me how to pull the project from Heroku? Or maybe how I can get the updated database?
Thanks!


text: Q: difference between git checkout file and git checkout -- file I'm learning git and in the git-checkout documentation points that if you delete a file (from the explorer not from git directly) then you can recover by calling git checkout -- file, but I tried without the double dash as git checkout file and the result is exactly the same apparentrly... in this context, what it means --?


text:
Q: Is there an automated way to remove XAML default properties? Are there any automated tools that will parse through XAML code and clean out values that are explicitly declared to their defaults?
Example:
<Grid Margin="0,0,0,0" Height="Auto" Width="Auto">

I would expect to be reduced to:
<Grid>

A: Kaxaml has a scrubber feature that does this. Be careful with removing XAML default properties. Sometimes they are necessary for animation starting values.

A: XAML Power Toys has a utility to remove designer generated XAML.  It is not specifically for items that are set to their default values, but it is close to what you are lookig for.


text:
Q: Getting weird error in system.log after fresh installation of Magento CE 1.7.0.2 related to GeoIP After a fresh installation of Magento CE 1.7.0.2, I am getting a 404 Page not found on localhost/index.php and localhost/index.php/admin. I enabled debugging in index.php and I am getting the following log over and over (every time I refresh the page):
2014-08-01T14:49:38+00:00 DEBUG (7): GEOIP::COUNTRY::APPFR
2014-08-01T14:49:38+00:00 DEBUG (7): GEOIP::CONTINENT::APPEU
Notice the "APP" before the "FR" (for France)? I have no idea how I am getting this error.
By the way, i installed the GeoIP extension after I built a Ubuntu 14.0.2 VM with LAMP installation (PHP 5.5.9 and MySQL 5.5.38). The weird thing is the GeoIP extension didn't come with PHP5.5, I had to install it separately (apt-get install php5-geoip) in order to be able to install the database through Magento Installation Wizard.
Thanks

A: This bug was due to an error in the source code. After a fresh new installation with new code, the problem is gone.


text:
Q: How can I speed up the performance by using numpy einsum and numexpr in calculating kernel functions? I am trying to define a few of famous kernels like RBF, hyperbolic tangent, Fourier and etc for svm.SVR method in sklearn library. I started working on rbf (I know there's a default kernel in svm for rbf but I need to define one to be able to customize it later), and found some useful link in here and chose this one:
def my_kernel(X,Y):
    K = np.zeros((X.shape[0],Y.shape[0]))
    for i,x in enumerate(X):
        for j,y in enumerate(Y):
            K[i,j] = np.exp(-1*np.linalg.norm(x-y)**2)
    return K

clf=SVR(kernel=my_kernel)

I used this one because I could use it for my train (with shape of [3850,4]) and test data (with shape of [1200,4]) which have different shapes. But the problem is that it's too slow and I have to wait so long for the results. I even used static-typing and memoryviews in cython, but its performance is not as good as the default svm rbf kernel. I also found this link which is about the same problem but working with numpy.einsum and numexpr.evaluate is a little bit confusing for me. It turns out that this was the best code in terms of speed performance:
from scipy.linalg.blas import sgemm
def app2(X, gamma, var):
    X_norm = -gamma*np.einsum('ij,ij->i',X,X)
    return ne.evaluate('v * exp(A + B + C)', {\
        'A' : X_norm[:,None],\
        'B' : X_norm[None,:],\
        'C' : sgemm(alpha=2.0*gamma, a=X, b=X, trans_b=True),\
        'g' : gamma,\
        'v' : var\
    })

This code just works for one input (X) and I couldn't find a way to modify it for my case (two inputs with two different sizes - The kernel function gets matrices with shape (m,n) and (l,n) and outputs (m,l) according to svm docs  ). I guess I only need to replace the K[i,j] = np.exp(-1*np.linalg.norm(x-y)**2) from the first code in the second one to speed it up. Any helps would be appreciated.

A: You can just pipe your original kernel through pythran
kernel.py:
import numpy as np

#pythran export my_kernel(float64[:,:], float64[:,:])
def my_kernel(X,Y):
    K = np.zeros((X.shape[0],Y.shape[0]))
    for i,x in enumerate(X):
        for j,y in enumerate(Y):
            K[i,j] = np.exp(-1*np.linalg.norm(x-y)**2)
    return K

Compilation step:
> pythran kernel.py

There's no rewriting step (you need to put the kernel in a separate file though) and the acceleration is significant: 19 times faster on my laptop, using
> python -m timeit -s 'from numpy.random import random; x = random((100,100)); y = random((100,100)); from svr_kernel import my_kernel as k' 'k(x,y)'

to gather timings.

A: Three possible variants
Variants 1 and 3 makes use of

(a-b)^2 = a^2 + b^2 - 2ab

as described here or here. But for special cases like a small second dimension Variant 2 is also OK.
import numpy as np
import numba as nb
import numexpr as ne
from scipy.linalg.blas import sgemm

def vers_1(X,Y, gamma, var):
    X_norm = -gamma*np.einsum('ij,ij->i',X,X)
    Y_norm = -gamma*np.einsum('ij,ij->i',Y,Y)
    return ne.evaluate('v * exp(A + B + C)', {\
        'A' : X_norm[:,None],\
        'B' : Y_norm[None,:],\
        'C' : sgemm(alpha=2.0*gamma, a=X, b=Y, trans_b=True),\
        'g' : gamma,\
        'v' : var\
    })

#Maybe easier to read but slow, if X.shape[1] gets bigger
@nb.njit(fastmath=True,parallel=True)
def vers_2(X,Y):
    K = np.empty((X.shape[0],Y.shape[0]),dtype=X.dtype)
    for i in nb.prange(X.shape[0]):
        for j in range(Y.shape[0]):
            sum=0.
            for k in range(X.shape[1]):
                sum+=(X[i,k]-Y[j,k])**2
            K[i,j] = np.exp(-1*sum)
    return K

@nb.njit(fastmath=True,parallel=True)
def vers_3(A,B):
    dist=np.dot(A,B.T)

    TMP_A=np.empty(A.shape[0],dtype=A.dtype)
    for i in nb.prange(A.shape[0]):
        sum=0.
        for j in range(A.shape[1]):
            sum+=A[i,j]**2
        TMP_A[i]=sum

    TMP_B=np.empty(B.shape[0],dtype=A.dtype)
    for i in nb.prange(B.shape[0]):
        sum=0.
        for j in range(B.shape[1]):
            sum+=B[i,j]**2
        TMP_B[i]=sum

    for i in nb.prange(A.shape[0]):
        for j in range(B.shape[0]):
            dist[i,j]=np.exp((-2.*dist[i,j]+TMP_A[i]+TMP_B[j])*-1)
    return dist

Timings
gamma = 1.
var = 1.
X=np.random.rand(3850,4)
Y=np.random.rand(1200,4)

res_1=vers_1(X,Y, gamma, var)
res_2=vers_2(X,Y)
res_3=vers_3(X,Y)
np.allclose(res_1,res_2)
np.allclose(res_1,res_3)

%timeit res_1=vers_1(X,Y, gamma, var)
19.8 ms ± 615 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit res_2=vers_2(X,Y)
16.1 ms ± 938 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit res_3=vers_3(X,Y)
13.5 ms ± 162 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


text:
Q: Passing Storable Vector to a C function allocating stored data on GPU I have the following C code:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cuda_runtime.h>
#include <cublas_v2.h>

double enorm(double* v1, int length){
    cublasHandle_t handle;
    double result = 0;
    double* vector;
    cudaMalloc((void**) &vector, length * sizeof(double));
    cublasSetVector(length, sizeof(double), v1, 1, vector,1);
    cublasCreate(&handle);
    cublasDnrm2(handle, length, vector, 1, &result);
    cudaFree(vector);
    return result;
}

double testnorm(double* v1, int len){
    double tmp = 0;
    for(int i = 0; i < len; i++){
        tmp += v1[i]*v1[i];
    }
    return sqrt(tmp);
}

int main() {
    double* a = malloc(2 * sizeof(double));
    a[0] = 3;
    a[1] = 4;
    printf("%.f\n", enorm(a, 2));
    printf("%.f\n", testnorm(a,2));
    return 0;
}

And following Haskell code, which borrows functions from above:
import qualified Foreign.Ptr as P
import System.IO.Unsafe
import Foreign.C.Types
import qualified Data.Vector.Storable as SV
import Foreign.C.Types

foreign import ccall "enorm" c_enorm :: P.Ptr CDouble -> CInt -> CDouble

foreign import ccall "testnorm" c_testnorm :: P.Ptr CDouble -> CInt -> CDouble

enorm :: SV.Vector CDouble -> CDouble
enorm v1 = unsafePerformIO $ do
  let len = fromIntegral $ SV.length v1
  SV.unsafeWith v1 $ \ptr -> return (c_enorm ptr len)

testnorm :: SV.Vector CDouble -> CDouble
testnorm v1 = unsafePerformIO $ do
  let len = fromIntegral $ SV.length v1
  SV.unsafeWith v1 $ \ptr -> return (c_testnorm ptr len)

main :: IO ()
main = do
  let a = SV.fromList [3,4] :: SV.Vector CDouble
  print $ enorm a
  print $ testnorm a

For some reason even though C program returns, as expected 5 and 5, the Haskell equivalent returns 0 and 5 which means that even though array is successfully passed to C function, there is some problem with copying this data to GPU. What is the cause of this behavior and how to do it so that it would give expected result?
C is compiled with:
gcc -o cmain blas.c -I/opt/cuda/include -L/opt/cuda/lib64 -lcublas -lcudart -lm

Haskell:
gcc -c -fPIC -o testblas.o blas.c -I/opt/cuda/include -L/opt/cuda/lib64 -lcublas -lcudart -lm
gcc -shared -o libtestblas.so  testblas.o
ghc -o main Main.hs -I/opt/cuda/include -L/opt/cuda/lib64 -lcublas -lcudart -lm -L./ -ltestblas
export LD_LIBRARY_PATH=./; ./main

EDIT: In Haskell cudaMalloc returns cudaErrorMemoryAllocation (unable to allocate enough memory) while in C everything ends with success.


text:
Q: Fetch request to http address from a https website Is it some how possible to send a get request from a https website to a http address with fetch api.
fetch('http://103.82.8.194/Data/', { mode: 'no-cors' })
    .then(response => response.json())
    .then(data =>
        console.log(data)
    );

Like is it some how possible send this request from https://rionislam.github.io ?
Thanks...

A: It's not possible to request http address from a https website directly because of the Mixed Content Security Policy, it'll be blocked by the browser.
You can use a https proxy to do so, something like: https://some-proxy-url?url=http://103.82.8.194/Data/.
or just upgrade http server to https


text:
Q: Vectorizar - Ilustrator | Photoshop Como hacer para vectorizar un logo con pixeles a linea perfecta?
Es decir, se como pasar de una imagen pixeleada a vector, pero no me queda de forma lineal.
Hay alguna forma?


text:
Q: Perform operation based on matching column values from another table in Postgres I would like to write two queries for a postgres database, but my skills are still a bit too low and I don't have quite clear how to do that.
I have three tables, with data related to visits to a web platform and the edits made by users.
The first one contains the daily visits for each page (pageid) on the platform.
Table 1
pageid |    date   | visits
---------------------------
pageid1| 01-01-2016|   2
pageid1| 02-01-2016|   1
pageid1| 03-01-2016|   3
pageid1| 04-01-2016|   4
pageid1| 05-01-2016|   3
pageid1| 06-01-2016|   2
...
pageid1| 01-02-2016|   4
...
pageid2| 01-01-2016|   5
...

The second one contains the edits made to each page, there can be more than one edit per day (currently the table has a timestamp, but I can easily convert that into a date).
Table 2
 pageid|    date   | content
-----------------------------
pageid1| 01-01-2016|   a
pageid1| 01-01-2016|   b
pageid1| 03-01-2016|   c
pageid1| 03-01-2016|   c
pageid1| 03-01-2016|   e
pageid1| 04-01-2016|   e
pageid1| 04-01-2016|   c
pageid1| 05-01-2016|   e
pageid1| 06-01-2016|   f
...

The third table contains only the edits made to some elements that are in the pages. There may be more than one element per page.
Table 3
 pageid|  page_ref  |    date   | content_ref
---------------------------------------------
pageid1| page_ref_1 | 01-01-2016|   a
pageid1| page_ref_1 | 03-01-2016|   b
pageid1| page_ref_2 | 03-01-2016|   c
pageid1| page_ref_2 | 05-01-2016|   c
pageid1| page_ref_2 | 06-01-2016|   c
pageid1| page_ref_3 | 02-01-2016|   c
pageid1| page_ref_3 | 07-03-2016|   c
pageid1| page_ref_3 | 03-04-2016|   c
...

What I would like to achieve with my queries is:

*

*For each element in a page (page_ref), compute the number of page visits between each edit and the previous one.

*For each element in a page (page_ref), compute the number of page edits between each edit and the previous one.

Eventually, I would like to have a table like this:
Table 4
 pageid|  page_ref  |    date   | content_ref | visit_no | edit_no
-------------------------------------------------------------------
pageid1| page_ref_1 | 01-01-2016|   a         |    NA    |    NA
pageid1| page_ref_1 | 03-01-2016|   b         |     6    |     4
pageid1| page_ref_2 | 03-01-2016|   c         |    NA    |     NA
pageid1| page_ref_2 | 05-01-2016|   c         |    10    |     6
pageid1| page_ref_2 | 06-01-2016|   c         |    5     |     2
...

I hope what I ask is clear, many thanks in advance for your help :)


text:
Q: Dispatching an argument's default value from an S4 generic function to its associated methods Suppose all of your S4 methods associated to a specific S4 generic function/method share a formal argument that is supposed to have a specific default value. Intuitively, I would state such an argument in the definition of the S4 generic (as opposed to stating it in each method definition which would seem somewhat redundant to me).
However, I noticed that this way I'm running into trouble as it seems that the default value of the formal argument is not dispatched to the methods and thus an error is thrown.
Isn't this somewhat against the idea of having a combination of a generic and methods? Why would I have to state the formal argument in each method separately again when the default value is always the same? Can I explicitly dispatch formal arguments' default values somehow?

Below you'll find a short illustration of the behavior
Generic function
setGeneric(
    name="testFoo",
    signature=c("x", "y"),
    def=function(
        x,
        y,
        do.both=FALSE,
        ...
    ) {
    standardGeneric("testFoo")
    }
)

Method
setMethod(
    f="testFoo",
    signature=signature(x="numeric", y="numeric"),
    definition=function(
        x,
        y
    ) {
    if (do.both) {
        out <- list(x=x, y=y)
    } else {
        out <- x
    }
    return(out)
    }
)

Error
> testFoo(x=1, y=2)
Error in .local(x, y, ...) : object 'do.both' not found

Redundant statement of do.both fixes it
setMethod(
    f="testFoo",
    signature=signature(x="numeric", y="numeric"),
    definition=function(
        x,
        y,
        do.both=FALSE
    ) {
    if (do.both) {
        out <- list(x=x, y=y)
    } else {
        out <- x
    }
    return(out)
    }
)

> testFoo(x=1, y=2)
[1] 1

A: When you call testFoo(x=1, y=2), it is processed first by the S4 generic, which looks for a method, finds it, and dispatches to it a call that looks like this: testFoo(x=1, y=2, do.both=FALSE, ...).
In the words of ?standardGeneric:

'standardGeneric' dispatches the method defined for a generic
    function named 'f', using the actual arguments in the frame from
    which it is called.

If the method to which it dispatches that call does not take a do.both argument, the method --- just like any other R function --- throws an error. No function can process a call containing an argument foo unless it's function definition contains either (a) a formal argument foo or (b) a "dots" argument, ..., which can absorb arbitrary supplied arguments.
Basically what you've tried is no different than the following, which fails in a similarly but perhaps easier-to-see way:
testFooGeneric <- function(x=1, y=2, do.both=FALSE, ...) {
    ## The line below does essentially what standardGeneric() does
    if(is.numeric(x) & is.numeric(y)) {
        testFooMethod(x=x, y=y, do.both=do.both)
    }
}

testFooMethod <- function(x, y) {
    cat("Success!\n")
}

testFooGeneric(x=1, y=2)
# Error in testFooMethod(x = x, y = y, do.both = do.both) :
#   unused argument(s) (do.both = do.both)

To fix the above, you need to redefine testFooMethod() in one of the following two ways, either of which will also remedy your S4 method:
## Option 1
testFooMethod <- function(x, y, do.both) {
    cat("Success!\n")
}
testFooGeneric(x=1, y=2)
# Success!

## Option 2
testFooMethod <- function(x, y, ...) {
    cat("Success!\n")
}
testFooGeneric(x=1, y=2)
## Success!


text:
Q: ReactJs connect 2 child components If in Angular 2 is possible to connect two child components with each other how is  it manageable in react js?

A: A) You can use Redux or Flux to keep a single state for the whole application, which you will be able to access from any component that you decide to connect with this state, called the Store.
You can read more about this in https://github.com/reduxjs/redux.
B) If both components are siblings, and the state you are trying to share is not something that you would care about in the rest of the application, you can pass the state from the parent to both children, as props, and also pass a function that allows the children to set the parent's state.
For example:
class Parent extends Component {
  state = {
    something: '',
  }

  changeSomething = (e) => {
    this.setState({
      something: e.target.value,
    })
  }

  render() {
    const { something, changeSomething } = this.state;
    return(
      <div>
        <ChildrenA
          something={something}
          changeSomething={changeSomething}
        >
        <ChildrenB
          something={something}
          changeSomething={changeSomething}
        >
      </div>
    );
}

Now both children have access to this.props.something and this.props.changeSomething and they can both change the parent's state and both will see the changes.
Hope it helps


text:
Q: Notation and proof of statement about convex functions I am reading my course notes on convex optimisation, but the notes provide a notation that I am unfamiliar with. The notes makes the claim that if $f:\mathbb{R}^n\mapsto\mathbb{R}$ is convex, ${\bf x}$, ${\bf y}\in\mathcal{D}(f)$, ${\bf a}\in\partial f({\bf x})$ and ${\bf b}\in\partial f({\bf y})$, then $({\bf a}-{\bf b})^\mathrm{T}({\bf x}-{\bf y})\geq{\bf 0}$. I therefore would like to check the following.

*

*$\mathcal{D}$ either represents domain or preimage, which is it? I suspect it is domain because of the it starts with 'D', but nevertheless it is worthwhile to check.

*What exactly are $\partial f({\bf x})$ and $\partial f({\bf y})$? In physics, I know that $\partial V$ represents the surface bounding a volume $V$, are they related? If it is referring to a "surface", what is the proper mathematical way to define $\partial f({\bf x})$ and $\partial f({\bf y})$?

*Assuming I have gotten the interpretations of these right, I wanted to prove it as follows: using without proof a claim that further appears in the notes, I have $f({\bf x}+{\bf d})-f({\bf x})\geq{\bf a}^\mathrm{T}{\bf d}$ and $f({\bf y}+{\bf d})-f({\bf y})\geq{\bf b}^\mathrm{T}{\bf d}$. If I could "subtract" these two inequalities intuitively I know I will be close, but I just can't seem to figure out how. What have I done wrong here?

A: Here $\mathcal{D}(f)$ should be the domain of $f$:
$$
\mathcal{D}(f) := \{ x \in \mathbb{R}^n \mid f(x) < \infty \}.
$$
Moreover, $\partial f(x)$ is the subdifferential of $f$ at $x$. You can think of it as a generalization of the gradient. In particular, you always have the inequality
$$
f(y) \geq f(x) + \zeta^{\mathsf{T}}(y - x), \; \forall x, y \in \mathcal{D}(f), \; \forall \zeta \in \partial f(x).
$$
Your idea for proving the inequality is correct. Applying the above inequality twice, with the order of $y$ and $x$ reversed, you have
$$
f(y) - f(x) \geq \zeta^{\mathsf{T}}(y - x), \; \forall \zeta \in \partial f(x). \\
f(x) - f(y) \geq w^{\mathsf{T}}(x - y), \; \forall w \in \partial f(y).
$$
Add them together and the LHS cancels; rearranging will give you
$$
(\zeta - w)^{\mathsf{T}}(x - y) \geq 0,
$$
and since the choice of $x$ and $y$ was arbitrary the inequality follows.
(Note that this is exactly the proof you suggested, with $d = (y - x)$ in the first invocation and $d = (x - y)$ in the second one.)


text:
Q: Updating JTable row dynamically after the deletion successive rows I have a JTable and I am inserting rows to that JTable dynamically.
After some user intervention, a new row will be inserted .Then I will call a function with parameter as selected row number and inside that function, I have some code which will update the same row accordingly. Each row insertion and row value update code will run in a separate thread.
public void updateRow(int row,JTable myTable)
{
  String text = "";
 //After lot of processing, setting the table cell value at the 'row' on the 4th column
  myTable.setValueAt(text, row, 4);
}

The issue I am facing is as follows,
If the user deleting any row, then row's position will change and at that time if the function updateRow() trying to update some other row, then it will fail because of change of row count.
Lets say I have 3 row at a time and each row's updateRow is in progress.
updateRow(0,userTable);//For the 1st row
updateRow(1,userTable);//For the 2nd row
updateRow(2,userTable);//For the 3rd row

and assume 2nd row's updateRow() is completed. This will cause issue in updateRow() function of 3rd row. Because, it has the row value as '2' . Since the 3rd row got deleted, there is no 3rd row and which in turn cause the following code to fail
myTable.setValueAt(text, row, 4);//Currently, row has the value as '2'

Can anyone suggest me how can I keep track of the row update with row values accordingly, even if the row's position got changed dynamically ?
Thanks in advance.

A: Instead of relying on the view's row number, operate on the model directly, as suggested in a comment by @mKorbel; if you alter the model, the view will follow. As discussed here, "JTable provides methods that convert from model coordinates to view coordinates — convertColumnIndexToView and convertRowIndexToView — and that convert from view coordinates to model coordinates — convertColumnIndexToModel and convertRowIndexToModel.


text:
Q: Calling methods in the main program I am trying to access some information that my program isnt letting me.
 in my method "addTrack" it doesnt recognise the myTracklist object. how do i call myTracklist.count by using a method in the main class?
public class CD {
    String art;
    String tit;
    public CD(String artist, String title){
        art = artist;
        tit = title;
        tracklist myTracklist = new tracklist(100);
    }

    public static void main(String[] args) {
        String mainArtist;
        String mainTitle;
        CD myCD = new CD("Awesomeguy", "AwesomeCDName");
        mainArtist = myCD.getArtist();
        System.out.println(mainArtist);
        mainTitle = myCD.getTitle();
        System.out.println(mainTitle);
        myCD.display();
    }

    public String getArtist(){
        String person;
        person = art;
        return person;
    }

    public String getTitle(){
        String name;
        name = tit;
        return name;
    }

    public boolean addTrack(String trackinfo){
        boolean result = false;
        if (myTracklist.count < 100){
            myTracklist.add(trackinfo);
            result = true;
        }
        return result;
    }

    public int numTracks(){
        int amount;
        amount = myTracklist.count();
        return amount;
    }

    public void display(){
        System.out.println("Artist = "+ art);
        System.out.println("Title = "+ tit);
        tracklist.display();
    }
}

here is my tracklist class
public class tracklist {
    int length;
    int numUsed;
    String[] storage;

    public tracklist(int size){
    length = size;
    numUsed = 0;
    storage = new String[length];
    }

    public int count(){
        return numUsed;
    }
}

A: You've got scope problems in that you're declaring tracklist inside the CD constructor so that it only exists inside of the constructor and nowhere else. You must make it a field that is declared in the class for it to be usable at all the methods of the class.
So instead of
public class CD {
    String art;
    String tit;
    public CD(String artist, String title){
        art = artist;
        tit = title;
        tracklist myTracklist = new tracklist(100);
    }

do
public class CD {
    private String art;
    private String tit;
    private tracklist myTracklist; // declared

    public CD(String artist, String title){
        art = artist;
        tit = title;
        myTracklist = new tracklist(100); // initialized
    }

    // getter and setter methods of course.

It's a subtle but important distinction.
As an aside: you'll want to learn Java naming conventions so that others can more readily understand your code and your questions. Class names begin with an upper case letter.
As a second aside: don't have outside classes directly manipulate class fields. Use private fields and public getters and setters to allow the class to have more control over just what can be seen and what can be done.

A: Keep the declaration of myTrackList outside the constructor. Like this:-
String tit;
tracklist myTracklist;

public CD(String artist, String title){
    art = artist;
    tit = title;
    myTracklist = new tracklist(100);
}

A: it should be myTracklist.count() here:
if (myTracklist.count < 100){

Also:
String tit; // oh I love this object name!
tracklist myTracklist;
public CD(String artist, String title){
    art = artist;
    tit = title;
    myTracklist = new tracklist(100);
}

A: Since you have declared it in your customer the "myTracklist" variable will only be  visible in your constructor. Hence "addTrack" doesnt recognise the myTracklist object.
Declare it globally,
public class CD {
    String art;
    String tit;
    tracklist myTracklist;

And initialize in the constructor as below.
myTracklist = new tracklist(100);


text:
Q: Somar valores de textboxes ao sair do campo Eu tenho um form com três TextBoxes onde o usuário digitará qualquer valor
e um Label onde quero mostrar o resultado da soma desses valores.
Porém, eu gostaria de ir somando o conteúdo dessas TextBoxes sem ter que clicar em um botão. Digo, enquanto eu estiver preenchendo os TextBoxes, os valores vão sendo somados e a soma é mostrada no Label.

A: public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void fazOqVcQuer()
    {
        try
        {
            label1.Text =
            (Convert.ToDecimal(textBox1.Text)
            +
            Convert.ToDecimal(textBox2.Text)
            +
            Convert.ToDecimal(textBox3.Text)).ToString();
        }
        catch (Exception)
        {
        }
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        fazOqVcQuer();
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        fazOqVcQuer();
    }

    private void textBox3_TextChanged(object sender, EventArgs e)
    {
        fazOqVcQuer();
    }
}

Olá amigo. Tem várias formas de se fazer isso. Já que você está iniciando, entenda este código "bem" simples. substitua os valores "textBox1", "textBox2" e "textBox3" pelo nome dos seus, etc


text:
Q: Mi código no funciona de python En el libro me pide "Todo lo que hemos estado haciendo hasta ahora se puede hacer con objetos. Deberíamos probarlo. ¿Qué tal un objeto que tenga un método que retorne
la tabla de multiplicar de un número?". Pero al ponerlo al objeto con su método, no me funciona.
#!C:\python
# -*- coding:utf-8 -*-

class Tabla:
  def __init__(self, numero, nombre):
    self.numero = numero
    self.nombre = nombre

  def tabla1(self):
    print("Tabla de multiplicar del " + str(numero))
    print("Impresa automáticamente por " + nombre)
    i = 0
    while i < 11:
      print(str(numero) + " X " + str(i) + " = " + str(numero * i))
      i += 1

class Tablax(Tabla):
  def resultado(self):
    print("gracias")

tabla_multiplicar = Tablax(1, "Juan")

tabla_multiplicar.tabla1()

input()

A: Dentro del método tabla1, la variable numero no hace referencia a la propiedad del objeto. Para que lo haga simplemente tienes que reemplazar numero por self.numero. Lo mismo con nombre -> self.nombre.
def tabla1(self):
  print("Tabla de multiplicar del " + str(self.numero))
  print("Impresa automáticamente por " + self.nombre))
  i = 0
    while i < 11:
      print(str(self.numero) + " X " + str(i) + " = " + str(self.numero * i))
      i += 1


text:
Q: ng-view does not get the data from href? I tried one product page using AngularJS. This the first time i am creating the page using AngularJS.
ng-view is not working when i click the add to cart page. It does not show any respond.
I am verified the code with all the tutorials. It seems correct.
Can anyone please tell what i did wrong.
Below i mentioned the code. Sorry, cant able to put the code in jsfiddle. It does not bind the normal date.
Code:

var app = angular.module("myApp", ['ngRoute']);

   app.config(function($routeProvider, $locationProvider) {
     $routeProvider
       .when('/red', {
         templateUrl: 'dashboard.html',
         controller: 'myCtrl',
       })
       .when('/green', {
         templateUrl: 'custom_directives.html',
         controller: 'myCtrl'
       })
       .when('/yellow', {
         templateUrl: 'custom_directives.html',
         controller: 'myCtrl'
       })
       .when('/black', {
         templateUrl: 'custom_directives.html',
         controller: 'myCtrl'
       })
       .when('/grey', {
         templateUrl: 'custom_directives.html',
         controller: 'myCtrl'
       })
       .when('/blue', {
         templateUrl: 'custom_directives.html',
         controller: 'myCtrl'
       });

     // configure html5 to get links working on jsfiddle
     $locationProvider.html5Mode({
       enabled: true,
       requireBase: false
     });
   });
   app.controller("myCtrl", function($scope) {
     $scope.records = [{
       "Name": "Alfreds Futterkiste",
       "Country": "Germany",
       "Dollar": "$21.00",
       "URL": "red"
     }, {
       "Name": "Berglunds snabbköp",
       "Country": "Sweden",
       "Dollar": "$21.00",
       "URL": "green"
     }, {
       "Name": "Centro comercial Moctezuma",
       "Country": "Mexico",
       "Dollar": "$21.00",
       "URL": "yellow"
     }, {
       "Name": "Ernst Handel",
       "Country": "Austria",
       "Dollar": "$21.00",
       "URL": "black"

     }, {
       "Name": "Ernst Jubilie",
       "Country": "Canada",
       "Dollar": "$21.00",
       "URL": "grey"
     }, {
       "Name": "Idris_09090",
       "Country": "India",
       "Dollar": "$43.00",
       "URL": "blue"
     }]

   });
li.list-group-item {
  position: relative;
  display: inline-block;
  margin-bottom: -1px;
  background-color: #D38585;
  border: 1px solid #ddd;
  width: 25%;
  height: 210px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Water Products

                            {{x.Name}}

            {{x.Country}}

                {{x.Dollar}}

               Add to cart

Please help on this.

A: remove
$locationProvider.html5Mode({
       enabled: true,
       requireBase: false
 });

change your url to
Add to cart
demo:
https://plnkr.co/edit/5odGEUq0eK8tGR8IxohW?p=preview

A: Change href to ng-href
Add to cart

A: Can you please try this ? , as i can't judge is your app is getting load or not, but your href issue will solved from this.

var app = angular.module("myApp", ['ngRoute']);

   app.config(function($routeProvider, $locationProvider) {
     $routeProvider
       .when('/red', {
         templateUrl: 'dashboard.html',
         controller: 'myCtrl',
       })
       .when('/green', {
         templateUrl: 'custom_directives.html',
         controller: 'myCtrl'
       })
       .when('/yellow', {
         templateUrl: 'custom_directives.html',
         controller: 'myCtrl'
       })
       .when('/black', {
         templateUrl: 'custom_directives.html',
         controller: 'myCtrl'
       })
       .when('/grey', {
         templateUrl: 'custom_directives.html',
         controller: 'myCtrl'
       })
       .when('/blue', {
         templateUrl: 'custom_directives.html',
         controller: 'myCtrl'
       });

     // configure html5 to get links working on jsfiddle
     $locationProvider.html5Mode({
       enabled: true,
       requireBase: false
     });
   });
   app.controller("myCtrl", function($scope) {
     $scope.records = [{
       "Name": "Alfreds Futterkiste",
       "Country": "Germany",
       "Dollar": "$21.00",
       "URL": "red"
     }, {
       "Name": "Berglunds snabbköp",
       "Country": "Sweden",
       "Dollar": "$21.00",
       "URL": "green"
     }, {
       "Name": "Centro comercial Moctezuma",
       "Country": "Mexico",
       "Dollar": "$21.00",
       "URL": "yellow"
     }, {
       "Name": "Ernst Handel",
       "Country": "Austria",
       "Dollar": "$21.00",
       "URL": "black"

     }, {
       "Name": "Ernst Jubilie",
       "Country": "Canada",
       "Dollar": "$21.00",
       "URL": "grey"
     }, {
       "Name": "Idris_09090",
       "Country": "India",
       "Dollar": "$43.00",
       "URL": "blue"
     }]

   });
li.list-group-item {
  position: relative;
  display: inline-block;
  margin-bottom: -1px;
  background-color: #D38585;
  border: 1px solid #ddd;
  width: 25%;
  height: 210px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Water Products

                            {{x.Name}}

            {{x.Country}}

                {{x.Dollar}}

              Add to cart


text:
Q: How to show data from cursor into a listview I'm new to android and I'm stuck in a problem.
This is my main class and simply inserting the data and showing the data in Logcat. I want to show the data in ListView in a new activity. Now I am not getting how to get data from cursor and show it on ListView . I have made a view.xml & view.java to show data but I don't know how to show data on that activity. Should I make an adapter class, cursoradapter or flater, etc. (I want to know the next steps).
Thanks in advance :)
Main Class
  public class main extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        addListenerOnButton();
        database_delete();
        database_add();

    }

    public void database_add() {

     try{
        Database_handler db = new Database_handler(this);

        Log.d("Insert: ", "Inserting ..");

       db.addData(new get_set(131,"A-Lucy")) ;
       db.addData(new get_set(132,"A-kk")) ;
       db.addData(new get_set(133,"A_Tweety")) ;
       db.addData(new get_set(134,"A-Naruto")) ;
       Log.d("Reading: ", "Reading all contacts..");

    List<get_set> getSetList = db.getalldata();
        for(get_set set : getSetList){
            String log = "CODEE: " + set.getCode()  + ", Description: " + set.getDescr();
            Log.d("CODE: ", log);
        }

here is some code of my database handler class having functionality of inserting,retrieving data.
Database handler class
public class Database_handler extends SQLiteOpenHelper {

 private static final int DATABASE_Version = 1;
private static final String DATABASE_Name = "android_db";
private static final String TABLE_Name = "all_data";

private static final String Column_Name_code = "code";
private static final String Column_name_desc = "description";
private SQLiteDatabase db;

Database_handler(Context cont){
    super(cont,DATABASE_Name,null,DATABASE_Version);
}

@Override
public void onCreate(SQLiteDatabase db) {

    String CREATE_TABLE_ANDRO = " CREATE TABLE " +  TABLE_Name + "(" + Column_Name_code + " INTEGER PRIMARY KEY , "
            + Column_name_desc + " TEXT )";
    db.execSQL(CREATE_TABLE_ANDRO);
}

@Override
public void onUpgrade(SQLiteDatabase db, int Older_version, int new_version) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_Name );
    onCreate(db);
}
//    Inserting record
    public void addData (get_set getSet){
        SQLiteDatabase db = this.getReadableDatabase();

        ContentValues cv =   new ContentValues();
        cv.put (Column_Name_code, getSet.getCode());
        cv.put(Column_name_desc, getSet.getDescr());
        db.insert(TABLE_Name,null,cv);
        db.close();
    }

     Retrieving data
    public List<get_set> getalldata(){
         List<get_set> data_list = new ArrayList<get_set>();

         String select_query = "SELECT * FROM " + TABLE_Name;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cur = db.rawQuery(select_query,null);

        if (cur.moveToFirst()){
            do {
                get_set getsetObj = new get_set();
                getsetObj.setCode(Integer.parseInt(cur.getString(0)));
                getsetObj.setDescr(cur.getString(1));
                data_list.add(getsetObj);
            }  while (cur.moveToNext());
        }
        return data_list;
    }

A: In the database_add() function, after insertion of data into the database, Call an intent to the next Activity. In that new activity, call getalldata() function. AS you are already getting returned by a list, use Array adapter List view, with String type of an ArrayList, by following the below tutorial. It will work like a charm.
http://www.vogella.com/articles/AndroidListView/article.html
And also, I'd suggest you to include db.getalldata() function inside AsyncTask, because you dont want heavy database transactions in the main thread.


text:
Q: Viewing / Reloading emacs backup files I am successfully using the code below to cause emacs to save many versions of each file.  But I cannot figure out what commands you use in emacs to actually load those files into a buffer.
I am expecting some kind of a history viewer command!!!  I can find nothing.
(setq backup-directory-alist  '(("." . "~/auto-saves")))
(setq version-control     t
    kept-old-versions   2    kept-new-versions  200
    delete-old-versions t    backup-by-copying  t)

A: You can just open the files in which ever directory you're saving them in (~/autosaves).  But the backup-walker package is way better.

Update: I highly recommend using the no-littering package to keep your ~/.emacs.d (and $HOME) clean.  Here's my backup config (assuming you have use-package and melpa set up):
(use-package no-littering)

(setq make-backup-files t
      vc-make-backup-files t
      version-control t
      kept-new-versions 128
      kept-old-versions 0
      delete-old-versions t
      backup-by-copying t)

(defun force-backup-of-buffer ()
  (setq buffer-backed-up nil))
(add-hook 'before-save-hook #'force-backup-of-buffer)

(use-package backup-walker)

(let ((dir (no-littering-expand-var-file-name "auto-save/")))
  (make-directory dir t)
  (add-to-list 'auto-save-file-name-transforms `(".*" ,dir t) 'append))

If you don't want to use no-littering, set backup-directory-alist, tramp-persistency-file-name, tramp-backup-directory-alist, and tramp-auto-save-directory.
(setq emacs-persistence-directory
  (expand-file-name "var" user-emacs-directory))
(let ((dir (expand-file-name "backup" emacs-persistence-directory)))
  (unless (file-directory-p dir)
    (make-directory dir t))
  (setq backup-directory-alist `(("." . ,dir))))

(let ((backup-dir (concat emacs-persistence-directory "tramp-backup/")))
  (setq tramp-persistency-file-name (concat emacs-persistence-directory
                                            "tramp")
        tramp-backup-directory-alist `(("." . ,backup-dir))
        tramp-auto-save-directory (concat emacs-persistence-directory
                                          "tramp-auto-save/"))
  (dolist (d (list tramp-auto-save-directory backup-dir))
    (unless (file-exists-p d)
      (make-directory d t))))

Side note: auto-save is a different feature than backups.  Backups save a copy the first time you save a buffer (C-x C-s).  Above, I have the function force-backup-of-buffer on before-save-hook to backup on every save.  Autosave saves a copy every time you make a certain number of edits.  For a given file, there can be many backups, but there's only one autosave.

A: I am leaving jpkotta's answer as the selected one, since backup-walker seems to work for others.  For my OSX box, I could not get Backup-Modes to work, and backup walker is more focused on DIFFS rather than just providing access to backup files.
Here is my hacked solution it is a kinda gross, but it works for me.
You will need to edit path names for your environment.
(see https://www.emacswiki.org/emacs/ForceBackups for the original)
I tried, Backup-Modes, and Backup-Directory https://www.emacswiki.org/emacs/BackupDirectory, but this is the first things that kinda worked.)
What this does:
- It fixes emacs so it always does an auto-save (surprisingly this is NOT the default)
- it adds the command   ``M-x history'' to open the backups directory.
Crude, but it works.  So sad to see Emacs die!
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;   FORCE-BACKUP-OF-BUFFER
;;;   (See https://www.emacswiki.org/emacs/ForceBackups)

(defun dao-setup-force-backup-of-buffer()
     (setq vc-make-backup-files t)          ; Do backups even for version controlled files!
     (setq version-control t                ; Use version numbers for backups.
      kept-new-versions 10                  ; Number of newest versions to keep.
      kept-old-versions 0                   ; Number of oldest versions to keep.
      delete-old-versions t                 ; Don't ask to delete excess backup versions.
      backup-by-copying t)                  ; Copy all files, don't rename them.
     (add-hook 'before-save-hook  'force-backup-of-buffer)
)

(defun force-backup-of-buffer ()
    ;; Make a special "per session" backup at the first save of each
    ;; emacs session.
    (when (not buffer-backed-up)
      ;; Override the default parameters for per-session backups.
      '(let ((backup-directory-alist  '(("." . "~/emacs-backups")))
            (kept-new-versions 3))
        (backup-buffer)))
      (backup-buffer)
    ;; Make a "per save" backup on each save.  The first save results in
    ;; both a per-session and a per-save backup, to keep the numbering
    ;; of per-save backups consistent.
    (let ((buffer-backed-up nil))
      (backup-buffer)))

(defun history ()
    (interactive)
    (dired-find-file "/User/oblinger/emacs-backups")
)


text:
Q: How to query for an array of ids from AWS DynamoDB DocumentClient using AWS Lambda Node.js runtime I have a few rows in my dynamoDB table, and I would like to return the id (I guess the primary key in this case), of each of those rows. Currently, I'm able to return everything in the table with
body = await dynamo.scan({ tableName: "table-name" }).promise();
But I was wondering if there was a more efficient or cleaner query that only returns an array of ids. Thank you!


text:
Q: Download application/octet-stream When I'm trying to type wrong URL of my website an application/octet-stream  is downloaded.
for example URL is
www.example.com/example/example
this is right url and works properly but when I write url like
 www.example.com/example/exa or like www.example.com/exa
then an  application/octet-stream is downloaded.
Any one tell me why this is happening and give me solution.
I'm using a PHP website.


text:
Q: simple Previous/Next buttons I'm triying to paginate the response of an API. This API, have 15 items per page.
Actualy, i'm  using something like this:
vm.next = function(currentPage){
$http.get('/api?page='+vm.firstPage++)
.then(function(data){
               vm.chuck = data.data.Response;
               });
          }

vm.previous = function(currentPage){
$http.get('/api?page='+vm.firstPage--)
.then(function(data){
               vm.chuck = data.data.Response;
               });
          }

and
vm.firstPage = 1;

My html view for buttons:
<div class="text-center">
<button type="button" class="btn btn-warning" ng-click="$ctrl.previous()">Previous</button>
<button type="button" class="btn btn-warning" ng-click="$ctrl.next()">Next</button>
</div>

The idea was to had the increment/decrement on every click. It works, but only after the second click. Also, if i change the value of vm.firstPage to 2, it works since the very first click, but when i click Previous, it becomes a mess.
What can i do to have the increment/decrement on the buttons?
I'm using AngularJs and javascript

A: I think it's about the operator precedence. Make vm.firstPage++/vm.firstPage-- before API call
vm.next = function(currentPage){
vm.firstPage++;
$http.get('/api?page='+vm.firstPage)
.then(function(data){
           vm.chuck = data.data.Response;
           });
      }


text:
Q: How Can I produce meta tag strings in PHP I'd like to produce my meta tag lines in php and then echo them in the  of the page.  I seem to be having problems.  When I echo the variable it actually echo's on screen rather than be contained to view source only like the other meta tags.
$ogmeta = '<meta property="og:type" content="Article" />';

then I was just doing
echo $ogmeta;

I also tried
$ogmeta = htmlspecialchars('<meta property="og:type" content="Article" />');

Each time it echos to screen :(
EDIT:
I found this to work
$ogmeta = '<meta property="og:title" content="'.$title.'" />';
echo $ogmeta;

But I need to have multiple entries for $ogmeta like this:
$ogmeta = '';
$ogmeta .= '<meta property="og:title" content="'.$title.'" />';
$ogmeta .= '<meta property="og:site_name" content="some site" />';
$ogmeta .= '<meta property="og:type" content="Article" />';
$ogmeta .= '<meta property="og:url" content="'.$which_article.'" />';

When I tried echoing this it all appeared on a single line.  I tried adding a line break
but that doesnt work.  Any ideas?

A: If you want <something> to be treated as a tag, then represent < and > as < and > (which are the HTML characters for start of tag and end of tag) and not as < and > (which are the HTML entities for less than and greater than).
$ogmeta = '<meta property="og:type" content="Article">';

A: You can also do like this. Inserting your PHP inside the <meta> tags too.
<?php
$metaKeywords="books,cars,bikes";
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<title>SomePage</title>
<meta name="description" content="<?php echo 'somedescription' ?>"></meta>
<meta name="keywords" content="<?php echo $metaKeywords ?>"></meta>
</head>

EDIT:
Solution 1: Make use of HEREDOC, Its pretty easier.
<?php
$metaTag=<<<EOD
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<title>SomePage</title>
<meta name="description" content="my description here"></meta>
<meta name="keywords" content="cars,bikes,books"></meta>
</head>
EOD;
echo $metaTag;
?>

Solution 2: You can also embed variables inside the HEREDOC.
<?php
$metaDesc="this is new";
$metaKeywords="cars,bikes,thrills";
$metaTag=<<<EOD
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
<title>SomePage</title>
<meta name="description" content=$metaDesc></meta>
<meta name="keywords" content=$metaKeywords></meta>
</head>
EOD;
echo $metaTag;//Don't forget to echo
?>

A: $ogmeta = "property='og:type' content='Article'";

<meta <? echo $ogmeta; ?> />

Could do that?
Leave the meta tag always there and just fill in the gaps.
Next best:
$ogmeta = "<meta property='og:type' content='Article' />";

echo "$ogmeta";

This should work.


text:
Q: Имеет ли здесь смысл детерминированная функция? В запросе используется такое условие:
t1.field = replace(t2.field, <Сложная конструкия вычислений по тексту, insrt, substr и т.д.>)

Соответственно, для каждой строки это значение вычисляется.
Планирую эти вычисления перенести в детерминированную функцию вида:
func(p_t2_field) <Сложная конструкия вычислений по тексту, insrt, substr и т.д.> return

Чтобы не вычислять, а сразу же брать из кеша нужный вариант (если он до этого был использован в качестве аргумента функции).
Имеет ли это смысл в этом конкретном случае?
И еще попутный вопрос, можно ли как-то узнать, какие варианты уже содержатся в кеше?

A: Да, имеет смысл, если можно гарантировать, что конструкция:
<Сложная конструкция вычислений по тексту, insrt, substr и т.д.>

всегда вернёт одинаковый результат для одного и того же значения параметра p_t2_field.
То есть, результат вычисления заведомо избавлен от побочных эффектов, например, национальных настроек, именений переменных сессии или её контекста и т.д.
В этой теме один из примеров такoго побочного эффекта.
Простой рабочий пример, вместо ожидаемых 9 сек. получим:
create or replace function slowfun (n number) return number deterministic is
begin
    dbms_lock.sleep (1);
    return n;
end;
/

SQL> set timing on rowprefetch 15
with data (n) as (
    select mod (rownum, 3) n
    from dual connect by level<=9)
select slowfun (n) n from data
/

9 rows selected.

Elapsed: 00:00:03.079

Можно ли как - то узнать, какие варианты уже содержатся в кеше?

Нет такой возможности нет. Этот кеш имеет очень "короткую жизнь" так, что не только последующее выполнение того же запроса, a даже последующий фетч не увидят его.
То есть, снижение колличества записей возвращаемых в фетч может свести эффективность кеширования на нет (во многих инструментах arraysize):
SQL> set arraysize 1 rowprefetch 1
SQL> /

9 rows selected.

Elapsed: 00:00:09.22

A: Ещё до того как детерминированные функции стали начииная с 10g использовать hash table для кеширования результатов функции, это было воможно с SSC (scalar subquery caching). То есть, вызов функции в запросе должен выглядеть так:
--where t1.field = func (t2.field) --no caching
where t1.field = (select func (t2.field) from dual) --caching

Его преимущество, что хеш не сбрасывается для каждого фетч и действителен для всего запроса.
Такой воспроизвидимый пример:
create or replace function slowfun (n number) return number is
begin
    dbms_lock.sleep (1);
    dbms_output.put_line ('n='||n||' at '||to_char (sysdate, 'mi:ss'));
    return n;
end;
/
create table tnum as
    select mod (rownum, 3) n from dual connect by level<=9
/
set timing on serveroutput on arrays 1 rowprefetch 1
select n from tnum where n = slowfun (n)
/
9 rows selected.

n=1 at 59:30
n=2 at 59:31
n=0 at 59:32
n=1 at 59:33
n=2 at 59:34
n=0 at 59:35
n=1 at 59:36
n=2 at 59:37
n=0 at 59:38
Elapsed: 00:00:09.25

select n from tnum where n = (select slowfun (n) from dual)
/
9 rows selected.

n=1 at 01:57
n=2 at 01:58
n=0 at 01:59
Elapsed: 00:00:03.09

Важно:
Kлючевое слово deterministic опущено в декларации функции только для примера. Это не только хинт для SQL интерпретатора, в первую очередь оно служит для документации того, что функция действительно детерминированна и должна остаться такой при при её последующих изменениях. Обязательно включите deterministic в декларацию функции.


text:
Q: Push Notification with Flutter Messaging craches the Flutter App I have been working with Flutter for a year now but its my first time with push notifications. I am trying to add push notifications in an old project. I have wrote the cloud firebase functions to push the notifications from.
But when the notification is sent to the token of the android phone. The android app crashes with the following error message.
2021-01-13 00:49:37.011 6127-6127/com.app.oldProject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.oldProject, PID: 6127
java.lang.RuntimeException: Unable to instantiate receiver com.google.firebase.iid.FirebaseInstanceIdReceiver: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.iid.FirebaseInstanceIdReceiver" on path: DexPathList[[zip file "/data/app/com.app.oldProject-wnxma3Smq-VCUX1eO04_kg==/base.apk"],nativeLibraryDirectories=[/data/app/com.app.oldProject-wnxma3Smq-VCUX1eO04_kg==/lib/arm64, /data/app/com.app.oldProject-wnxma3Smq-VCUX1eO04_kg==/base.apk!/lib/arm64-v8a, /system/lib64]]
    at android.app.ActivityThread.handleReceiver(ActivityThread.java:3633)
    at android.app.ActivityThread.access$1400(ActivityThread.java:237)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1889)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:224)
    at android.app.ActivityThread.main(ActivityThread.java:7081)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:604)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.iid.FirebaseInstanceIdReceiver" on path: DexPathList[[zip file "/data/app/com.app.oldProject-wnxma3Smq-VCUX1eO04_kg==/base.apk"],nativeLibraryDirectories=[/data/app/com.app.oldProject-wnxma3Smq-VCUX1eO04_kg==/lib/arm64, /data/app/com.app.oldProject-wnxma3Smq-VCUX1eO04_kg==/base.apk!/lib/arm64-v8a, /system/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at android.app.AppComponentFactory.instantiateReceiver(AppComponentFactory.java:84)
    at androidx.core.app.CoreComponentFactory.instantiateReceiver(CoreComponentFactory.java:60)
    at android.app.ActivityThread.handleReceiver(ActivityThread.java:3626)
    at android.app.ActivityThread.access$1400(ActivityThread.java:237)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1889)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:224)
    at android.app.ActivityThread.main(ActivityThread.java:7081)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:604)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928)
    Suppressed: java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/legacy/content/WakefulBroadcastReceiver;
    at java.lang.VMClassLoader.findLoadedClass(Native Method)
    at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:738)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:363)
            ... 12 more
 Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.legacy.content.WakefulBroadcastReceiver" on path: DexPathList[[zip file "/data/app/com.app.oldProject-wnxma3Smq-VCUX1eO04_kg==/base.apk"],nativeLibraryDirectories=[/data/app/com.app.oldProject-wnxma3Smq-VCUX1eO04_kg==/lib/arm64, /data/app/com.app.oldProject-wnxma3Smq-VCUX1eO04_kg==/base.apk!/lib/arm64-v8a, /system/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
            ... 15 more

I am sharing the pubspec.yaml and gradles below for my project so you can see the dependencies.
pubspec.yaml:
environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cloud_firestore: ^0.9.7+2
  firebase_storage: ^2.1.0+1
  firebase_core: ^0.3.0
  image_cropper: ^1.2.3
  firebase_auth: ^0.8.3
  image: ^2.0.7
  cupertino_icons: ^1.0.0
  path_provider: ^1.6.21
  firebase_messaging: ^4.0.0+1

these are the dependencies in app\build.gradle
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'com.google.firebase:firebase-core:16.0.1'
}

my flutter code is
 configurePushNotifications() {
    _firebaseMessaging.getToken().then((token) {
      print("Firebase Messaging Token: $token\n");
      usersRef.document(currentUser.id).updateData({"token": token});
    });

    _firebaseMessaging.configure(
      onLaunch: (Map<String, dynamic> message) async {
        print("here in the on Launch");
      },
      onResume: (Map<String, dynamic> message) async {
        print("here in the on Resume ");
      },
      onMessage: (Map<String, dynamic> message) async {
        print("on message: $message\n");
      },
    );
  }


text:
Q: farbtastic PlugIn callback function I'm just setting up a web page with a color picker. I choosed farbtastic.
My problem is, that the callback function doesn't work. Here is the code I used:
$('#colorPicker1').farbtastic('#background-color', function callback() {
    /*commands*/
});

The callback function is not called, when the user chooses a color.
How to solve this?

A: farbtastic called like you did
$('selector').farbtastic(...)

awaits only one optional argument. This can be a DOM Node, jQuery object, jQuery selector or a function. So you should call the function as shown below
$('#colorPicker1').farbtastic(function(color){
   // commands
});

If you want to use #background-color element, you should use it in the callbacks body
$('#colorPicker1').farbtastic(function(color){
   $('#background-color').css({'background-color':color});
   // commands
});

A: Your post is old I know but just in case :
var picker = $.farbtastic('#colorPicker1');  //picker variable
picker.setColor("#b6b6ff"); //set initial color
picker.linkTo(onColorChange); //link to callback

function onColorChange(color) {
  dosomeStuff();
}

A: After doing some search at comes with nothing I after almost 1 years from your question I think that there is no option but manually coding it.
I come with this solution after hacking a little bit farbtastic and colorpicker jquery plugins:
/*
 * ColorPicker.
 */
// Utility functions.
function convertHexToRGB(hex) {
    var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
    return [hex >> 16,(hex & 0x00FF00) >> 8,(hex & 0x0000FF)];
}

function convert_RGB_to_HSL(rgb) {
    var min, max, delta, h, s, l;
    var r = rgb[0], g = rgb[1], b = rgb[2];
    min = Math.min(r, Math.min(g, b));
    max = Math.max(r, Math.max(g, b));
    delta = max - min;
    l = (min + max) / 2;
    s = 0;
    if (l > 0 && l < 1) {
      s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
    }
    h = 0;
    if (delta > 0) {
      if (max == r && max != g) h += (g - b) / delta;
      if (max == g && max != b) h += (2 + (b - r) / delta);
      if (max == b && max != r) h += (4 + (r - g) / delta);
      h /= 6;
    }
    return [h, s, l];
}

$('#footer-text-color-selector').hide();
$.farbtastic('#footer-text-color-selector')
    .setColor('#21759B')
    .linkTo(function(color){
        $('#footer-text-color').css({
            'backgroundColor':color,
            'color': (convert_RGB_to_HSL(convertHexToRGB(color))[2] > 125) ? '#000' : '#FFF'
        });

        $('#footer-preview a').css('color', color);

        // XXX Any other things-to-do when the input change.
    });

// Hide & Show behaviour.
$('#footer-text-color').click(function() {
    $('#footer-text-color-selector').fadeIn();
});

$(document).mousedown(function() {
    $('#footer-text-color-selector').each(function() {
        var display = $(this).css('display');
        if ( display == 'block' )
            $(this).fadeOut();
    });
});

// Initial behaviour.
$('#footer-text-color').css({
    'backgroundColor': $('#footer-text-color').val(),
    'color': (convert_RGB_to_HSL(convertHexToRGB($('#footer-text-color').val()))[2] > 125) ? '#000' : '#FFF'
});

$('#footer-preview a').css('color', $('#footer-text-color').val());


text:
Q: How to emulate datavisualization's clean scientific axes in pgfplots I really like the "clean" scientific axes generated by TikZ' datavisualization library. However, since it provides quite a bit more plotting functionality, I want to give pgfplots a shot. How can i emulate datavisualizations's scientific axes=clean style in pgfplots?

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{datavisualization.formats.functions}

\usepackage{pgfplots}
\pgfmathsetlengthmacro\axisdefaultwidth{5cm}
\pgfmathsetlengthmacro\axisdefaultheight{\axisdefaultwidth * (sqrt(5) - 1) / 2}
\pgfplotsset{
  compat=1.17,
  scale only axis,
}

\begin{document}

With Ti\emph kZ:
\vskip 1ex
\begin{tikzpicture}
  \datavisualization [
      scientific axes=clean,
      visualize as line,
    ]
  data [format=function] {
      var x : interval [-1.5:1.5] samples 7;
      func y = \value x*\value x;
    };
\end{tikzpicture}

\vskip 4ex

With \textsc{pgfplots}:
\vskip 1ex
\begin{tikzpicture}
  \begin{axis}
    \addplot [
        domain=-1.5:1.5,
        samples=7,
      ] {x^2};
  \end{axis}
\end{tikzpicture}

\end{document}

A: It just amounts to adding some keys. Using
    axis lines=left,
    axis x line shift=1em,
    axis y line shift=1em,
    axis line style={-,very thin},
    axis background/.style={draw,ultra thin,gray},
    tick align=outside,
    xtick distance=0.5,
    ytick distance=0.5,

comes very close IMHO.
\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{datavisualization.formats.functions}

\usepackage{pgfplots}
\pgfmathsetlengthmacro\axisdefaultwidth{5cm}
\pgfmathsetlengthmacro\axisdefaultheight{\axisdefaultwidth * (sqrt(5) - 1) / 2}
\pgfplotsset{
  compat=1.17,
  scale only axis,
}

\begin{document}

With Ti\emph kZ:
\vskip 2ex
\begin{tikzpicture}
  \datavisualization [
      scientific axes=clean,
      visualize as line,
    ]
  data [format=function] {
      var x : interval [-1.5:1.5] samples 7;
      func y = \value x*\value x;
    };
\end{tikzpicture}

\vskip 4ex

With \textsc{pgfplots}:
\vskip 2ex
\begin{tikzpicture}
  \begin{axis}[axis lines=left,
        axis x line shift=1em,
        axis y line shift=1em,
        axis line style={-,very thin},
        axis background/.style={draw,ultra thin,gray},
        tick align=outside,
        xtick distance=0.5,
        ytick distance=0.5,
        ]
    \addplot [
        domain=-1.5:1.5,
        samples=7,
      ] {x^2};
  \end{axis}
\end{tikzpicture}

\end{document}

Needless to say that you can change the size of the plot, and combined the above keys to a style.
\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{datavisualization.formats.functions}

\usepackage{pgfplots}
\pgfmathsetlengthmacro\axisdefaultwidth{5cm}
\pgfmathsetlengthmacro\axisdefaultheight{\axisdefaultwidth * (sqrt(5) - 1) / 2}
\pgfplotsset{
  compat=1.17,
  scale only axis,
}

\begin{document}

With Ti\emph kZ:
\vskip 2ex
\begin{tikzpicture}
  \datavisualization [
      scientific axes=clean,
      visualize as line,
    ]
  data [format=function] {
      var x : interval [-1.5:1.5] samples 7;
      func y = \value x*\value x;
    };
\end{tikzpicture}

\vskip 4ex

With \textsc{pgfplots}:
\pgfplotsset{mimick datavisualization/.style={axis lines=left,
        axis x line shift=1em,
        axis y line shift=1em,
        axis line style={-,very thin},
        axis background/.style={draw,ultra thin,gray},
        tick align=outside,
        xtick distance=0.5,
        ytick distance=0.5,
        major tick length=2pt}}
\vskip 2ex
\begin{tikzpicture}
  \begin{axis}[mimick datavisualization,unit vector ratio=1 1 1,
    xmin=-1.5,xmax=1.5,width=5.6cm]
    \addplot [semithick,
        domain=-1.5:1.5,
        samples=7,
      ] {x^2};
  \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Logging errors in Java Spring MVC I'm trying to figure out logging, I want every time logging is called, where is it better to do this? to file? to the command line? I also do not have web.хml, how best to do it? here is the place in the code where I want to paste it
@Controller
public class MyErrorController implements ErrorController {

    @RequestMapping("/error")
    public String handleError() {
        //do something like logging
        return "error404";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

I saw this on the Internet, I don't understand how to connect
@RestController
@ Log4j2
public class LombokLoggingController {

     @RequestMapping ("/ lombok")
     public String index () {
         log.trace ("A TRACE Message");
         log.debug ("A DEBUG Message");
         log.info ("An INFO Message");
         log.warn ("A WARN Message");
         log.error ("An ERROR Message");

         return "Howdy! Check out the Logs to see the output ...";
     }
}

this is my pom.xml file
<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>2.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.0.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.3.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

A: Just annotate your controller with  @Slf4j and use the logger.
log.error("this is an error")
Sl4j is just a facade for logging frameworks. Log4j2 does not work because Spring boot uses Logback as the default logger.
If you want to use Log4j2 instead of Logback. You need to exclude the spring-boot-starter-logging dependency  in the spring-boot-starter-web and add spring-boot-starter-log4j2.
You can use either @Log4j2 or @Slf4j but I would recommend using @Slf4j so you wouldn't have to change the annotation whenever you want to change your logging framework.


text:
Q: How do i append data from process.popen I'm trying to run the next code:
import os
import subprocess
import sys

p = subprocess.Popen(['java', '-mx2g', '-cp', '''*''', 'edu.stanford.nlp.scenegraph.RuleBasedParser', ], stdin=subprocess.PIPE,stdout=subprocess.PIPE)
out, err = p.communicate('the brown cat chased the white fox\n')

Which uses Stanford's core NLP, once the subprocess.Popen() row runs the algorithm waits for an input which i'm sending by using communicate() i expect to get my output in the variable our but it's comes out to be None although when observing the terminal i see the correct output:
Processing from stdin. Enter one sentence per line.
> [main] INFO edu.stanford.nlp.pipeline.StanfordCoreNLP - Adding annotator tokenize
[main] INFO edu.stanford.nlp.pipeline.TokenizerAnnotator - TokenizerAnnotator: No tokenizer type provided. Defaulting to PTBTokenizer.
[main] INFO edu.stanford.nlp.pipeline.StanfordCoreNLP - Adding annotator ssplit
[main] INFO edu.stanford.nlp.pipeline.StanfordCoreNLP - Adding annotator parse
[main] INFO edu.stanford.nlp.parser.common.ParserGrammar - Loading parser from serialized file edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz ...
done [3.3 sec].
[main] INFO edu.stanford.nlp.pipeline.StanfordCoreNLP - Adding annotator lemma
[main] INFO edu.stanford.nlp.pipeline.StanfordCoreNLP - Adding annotator ner
Loading classifier from edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz ... done [5.9 sec].
Loading classifier from edu/stanford/nlp/models/ner/english.muc.7class.distsim.crf.ser.gz ... done [2.0 sec].
Loading classifier from edu/stanford/nlp/models/ner/english.conll.4class.distsim.crf.ser.gz ... done [3.2 sec].
[main] INFO edu.stanford.nlp.time.JollyDayHolidays - Initializing JollyDayHoliday for SUTime from classpath edu/stanford/nlp/models/sutime/jollyday/Holidays_sutime.xml as sutime.binder.1.
Reading TokensRegex rules from edu/stanford/nlp/models/sutime/defs.sutime.txt
Jun 30, 2018 6:11:08 PM edu.stanford.nlp.ling.tokensregex.CoreMapExpressionExtractor appendRules
INFO: Read 83 rules
Reading TokensRegex rules from edu/stanford/nlp/models/sutime/english.sutime.txt
Jun 30, 2018 6:11:11 PM edu.stanford.nlp.ling.tokensregex.CoreMapExpressionExtractor appendRules
INFO: Read 267 rules
Reading TokensRegex rules from edu/stanford/nlp/models/sutime/english.holidays.sutime.txt
Jun 30, 2018 6:11:12 PM edu.stanford.nlp.ling.tokensregex.CoreMapExpressionExtractor appendRules
INFO: Read 25 rules
source              reln                target
---                 ----                ---
cat-3               chase               fox-7

Nodes
---
cat-3
  -brown
fox-7
  -white

------------------------
> Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1540)
    at edu.stanford.nlp.scenegraph.RuleBasedParser.main(RuleBasedParser.java:253)

A: Seems you got this output from standard error stream.
If you want to capture it, you should add stderr=subprocess.PIPE argument to Popen() call, and it will be available in your err variable.