How to make apps use Unity's scrollbar?

Question: How can I make other apps display the same, slender kind of scrollbar that for example Files (the default file browser for Ubuntu) uses?
To be precise I want this scrollbar everywhere, especially in Firefox

rather than this one vaguely reminiscent of Windows 98
Comment: Seem like a bug : https://bugs.launchpad.net/ubuntu/+source/firefox/+bug/767040
Comment: @hg8 And over four years old. Thanks.
Answer: In Ubuntu 16.04 support for the overlay/Unity scrollbars was dropped in favor of the Gnome scrollbars. The relevant bugs concerning the old scrollbars have been closed as won't fix.
Since Firefox didn't use GTK3, however, even those didn't work when 16.04 was released. Firefox 46, however, finally includes GTK3 integration, so the Gnome scrollbars are now displayed.
As for other apps, it depends on their support for GTK3. LibreOffice, for instance, has some support (just download the libreoffice-gtk3 package to see the scrollbars), but it currently looks very broken with any dark theme (e.g. Ubuntu's default Ambiance).

How to make apps use Unity's scrollbar?


Write methods without lambda

Question: In the lesson we went through Spring and I want to understand this code
I have code:
 public class  TopicService {

    List<Topic> topics = new ArrayList<>(Arrays.asList(new Topic("1", "Petya", "Java"),
            new Topic("2", "Vasya", "Javascript"),
            new Topic("3", "Fedya", "Php")));

    public Topic getTopic(String id) {
        return topics.stream().filter(t -> t.getId().equals(id)).findFirst().get();
    }
   }

    public void deleteTopic(String id) {
        topics.removeIf(t -> t.getId().equals(id));
    }
}

I have not studied and am not familiar with lambda yet.
Help me write these methods in a regular format like here:
   public void updateTopic(String id, Topic topic) {
        for (int i = 0; i < topics.size(); i++) {
            Topic t = topics.get(i);
            if (t.getId().equals(id)) {
                topics.set(i, topic);
                return;
            }
        }
    }

Comment: What have you tried? Do you have an IDE? It might help un-lambda-ing the code
Comment: @luk2302 The code is correct and working, I just want to describe it in a more understandable version
Answer: Stream simply prepares your collection for various methods that accept a functional interface as argument (lambda is simply an implementation of a functional interface). Read about Java Stream methods to get the understanding.
public Topic getTopic(String id) {
    for (Topic topic : topics)
        if (topic.getId().equals(id)) return topic;

    return null;
}

public void deleteTopic(String id) {
    for (Topic topic : topics)
        if (topic.getId().equals(id)) topics.remove(topic);
}

I wanted you to figure it out yourself, but since you asked...
Comment: Can you write deleteTopic method and i select you answer bro <3
Comment: public Topic getTopic(String id) {
        for (Topic topic : topics) {
            if (topic.getId().equals(id)) {
                return topic;
            }
        }
    }
Comment: Is not correct or need do:  public Topic getTopic(String id) {
        for (Topic topic : topics) {
            if (topic.getId().equals(id)) {
                return topic;
            }
        }
        return null;
    }
Comment: I've corrected the answer, please accept it again, thanks.
Answer: getTopic:
public Topic getTopic(String id) {
    for(Topic tp : topics) {
       if (tp.getId().equals(id)){
          return tp;
       }
    }
    return null;
 }

deleteTopic:
public void deleteTopic(String id) {
   for(Topic tp : topics) {
      if (tp.getId().equals(id)){
         topics.remove(tp);
      }
   }
}

Answer: Welcome to StackOverFlow :)
Suppose you are passing your list of topics ("topics" instead of "topic")as a parameter you could do :
topics.stream()
  .filter(n -> n.getId().equals(id)equals("Android"))
  .forEach(n -> topics.set(n.getId(), n););

.stream()

is uded to manipulate sequences of elements
.filter(condition)

will give you the elements of this "stream" on which ids are equal to "Android" and then
.forEach

will make your update for these elements.
You'll maybe have to make some modifications to your code to be correct but here is the idea.
Don't hesitate to accept as an answer if it help :)
Answer: Try this for getTopic:
     public Topic getTopic(String id) {
                     for(Topic tp : topics) {
                         if (tp.getId().equals(id)){
                             return tp;
                         }
                     }
                    return null;
                    }

and for deleteTopic :
public void deleteTopic(String id) {
         for(Topic tp : topics) {
             if (tp.getId().equals(id)){
                 topics.remove(tp);
                 break;
             }
         }
        }

Write methods without lambda


Where is the first available house in Skyrim?

Question: As I grabbed everything that wasn't nailed down so far and as I don't want to throw away any ingredients I could use later I though it would be time to look for a house to store all my stuff. My inventory is getting fuller and I'd like to deposit all my crafting ingredients in a safe place.
How can I get a house to store all my stuff the easiest way at the beginning of the game?
Comment: Do you want to ask where to buy a house, or where you can find a safe container? Two slightly different questions...
Comment: I've clarified that I want a house
Answer: Following the main quest a bit further, I stumbled upon an opportunity to buy a house in Whiterun. You have to complete the Dragonstone quest (Bleak Falls Barrow), then you'll be granted the right to buy a house in the city.
To  buy the house you have to speak to Proventus Avenicci, he's near the Jarl in the keep. Unfortunately the house is pretty expensive for a starting character, it costs 5000 gold.
The house itself is called Breezehome, it is the second house on the right when you enter Whiterun.
Comment: Where is the house placed in the first town? I can't seem to find it.
Comment: @Andy — Breezehome (the purchasable house) is the second building on the right as you enter the city (next door to Warmaiden's).
Answer: The first house available in the game is in White run. It's a great house to have, cheapest and actually probably the most useful.
White run is by far the best town for selling, crafting, etc, in other words a place to quickly pop over to in between dungeons, quests, or anytime you get a full load of loot.
The house is literally like 15 steps from the fast travel location.  And next door on either side are the blacksmith and general goods store, as well as the potion shop.
This blacksmith (war maidens) is fully stocked with smelter, tanning rack, workbench, grindstone, and of course the forge.  Shopkeeper restocks with more than a thousand gold each day.
It's perfect, you travel in, stop at shops very quickly to offload loot and your house for anything you wish to keep.  Then whenever you need to you can do all your crafting very conveniently.
Also travelling to dragons reach keep allows you to conveniently use an enchanter, and the wizard there is stocked with all sorts of spells and soul gems as well.
I'm pretty far in the game, having completed many major quest lines and visited all the cities, and I can say that this house is by far the most useful.
That being said, it's nothing to look at and for aesthetic reasons it's probably the worst! But as a storage location it's the best.
Although I do wish there were more chests to store things in, to keep them sorted better.
Comment: I would agree this is a great house... not quite run out of "chests" yet... (there are containers that can be used). And having a chest with just smithing mats is great... just pop in take all and go next door :)
Comment: Everyone says Whiterun is the most convenient, but I've become quite comfortable with Riften.  I only jump over to Whiterun when I need a Smelter.  Maybe it has something to do with being a mage and wanting easy access to an Arcane Enchanter.
Answer: If you're referring to the house in Whiterun, it's called Breezehome, and it's right next to the smithy when you enter town. (Zoning in from the main Skyrim map, it's the second building on the right.)
Answer: You can get a free house with more storage available than any house you can purchase in the game(not sure how it compares to the amount of storage you can create in certain configurations by building with the Hearthfire DLC).
If you start the quest House of Horrors( just start it, you don't have to finish the quest right away or at all) you gain access to the Abandoned House in Markarth. Just talk to Vigilant Tyranus outside the house to start the quest.
Like Breezehome, you have access to all smithing stations(except a wood chopping block if you have Dawnguard and want to make arrows or crossbow bolts), 2 pre existing alchemy labs(apothecary and court mage) and an arcane enchanter(again next to the court mage). It even has a second smith in town like Whiterun( Moth Gro-Bogol in Understone Keep), but you cannot invest in either him or his sister Ghorza Gra-Bagol who runs the forge in town. There is also no fletcher in Markarth like there is in Whiterun(Drunken Huntsman) but the house is free.
If you have the Dragonborn DLC, you can earn a free house(Severin Manor) by completing a couple quests. It has all crafting stations inside(save a wood chopping block of which there is at least one in town next to the smelter by Raven Rock Mine). It is however somewhat lacking in the storage department.
If you intend to make full use of all you crafting skills(including the frequent changing of powers from the black book Sallow Regent and wearing the Relics of Ahzidal while enchanting) it can be handy to have this house as a place to store crafting supplies(mostly alchemy and enchanting for me, as I keep Seeker of Might active most of the time and do most of my tempering at Lakeview Manor on a hill overlooking Lake Illinalta in Skyrim).
Comment: If someone downvotes my answer, could you please explain to me why? Maybe there is something I can do to make it better. I appreciate constructive criticism but don't appreciate downvotes for no reason. Thanks


What is a good approach for warning user on leaving a modal or side flyout panel with unsaved changes?

Question: The user is editing a form element on the RHS flyout panel and the editing is not completed. In the middle of the process, the user decides to undertake the following actions:

Click outside the flyout panel.
Click in the search bar.
Click on one of the tabs inside the flyout
Clicks on the flyout close button.

What is the best way to notify the user that their changes will not be saved? Here are some of my iterations:
Answer: I would recommend having a pop-up modal asking the user that there is unsaved information that he will lose.
It's weird to click somewhere on the platform and have a warning somewhere else. Don't make the user chase warning messages on the platform. Make messaging contextual.
Facebook has a good example of this interaction here if you try to navigate to another page without posting your comment or status.

And here is a default browser warning triggered by StackExchange:
Comment: Thanks for the answer! I have read a lot of posts saying that modals are distracting and annoying for the users if they come up too often, and I anticipate that in this interaction this could be the case. Could there be a 'softer' way of notifying users without popping a modal?
Comment: True! that's a good way of looking at it!
Comment: I totally agree. Here is the tradeoff that you need to do as a designer between:

1. User will lose information and be super annoyed
2. Annoy user with a modal to save the information and not be super annoyed


UI5 Tooling command "ui5 serve" does start local server in SAP BAS but why can't I connect to it?

Question: I have SAP BTP trial account in which Im trying to run a SAPUI5 application via the SAP Business Application Studio (BAS). I have added nothing fancy to it. Just created one from the one of the many UI5 templates and tried running it from the terminal via the command ui5 serve.
The command does execute without any problems and also provides me with the standard localhost:8080 URL. Im using Firefox since BAS doesn't seem to work with Edge as well as Chrome.

I even get a message popping on the right bottom corner telling me a service is listening to port 8080 with a button that says "open in New Tab" pressing it however does nothing.

Im new to SAP BTP and BAS. Are there more things to configure before running the application? Or perhaps I have to configurate the browser itself? The error message:
Answer: I have also had some experience with the Business Application Studio.
You don't work locally here like in VS Code, for example. That's why you can't access it via localhost:8080, but have to use the link that provides the BAS. In this case, something like
port8080-workspaces-....applicationstudio.cloud.sap.
The best thing you can do is to press "Open in new tab" on the screenshot with "A service is listening to port 8080", then you will be redirected to the working link.
Kind regards
Sebastian


Can I attach heavy glass enclosure to plastic shower

Question: The shower surround is attached to studs but where the heavy glass enclosure should attach there are no studs. Is there some kind of anchor I can use to attach to the plastic only?
Thank you!
Comment: Hello, and welcome to Home Improvement. If an answer is helpful, please click the large check mark next to it to accept. And, please [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Answer: Glass shower enclosures are typically supported by the walls and specifically studs in the walls. Often they will be attached through the shower surface (tile, granite, etc.) if it's structurally sound. Glass is heavy. The biggest issue is typically with the door because it is hinged (suspended) on one side. Some of the weight of the door can be offset with metal framing around the glass enclosure and the door. However, the door must be fastened into a supporting wall stud and preferably a double stud.
The short answer here is No! You don't want to try to mount glass directly to a plastic shower enclosure. You need to get a professional involved here if you haven't worked with this before. If it's not mounted properly it can be dangerous.
Comment: I agree, normally a few holes are drilled through the surround. To attach the framework for the enclosure. I have seen 1 that was supposed to expand and hold itself in place (diy).  I was there to clean up and install a new enclosure after the owner got 4-6 stitches and it was tempered glass.+


AngularJS : Custom filters and ng-repeat

Question: I'm an AngularJS newbie and I'm building up a small proof-of-concept car hire listings app that pulls in some JSON and renders out various bits of that data via an ng-repeat, with a couple of filters:

{{result.carType.name}}, {{result.carDetails.doors}} door, £{{result.price.value}} - {{ result.company.name }}

{{result.carDetails.hireDuration}} day hire

Air conditioning

Unlimited Mileage

Theft Protection

Filters

Doors:

    <select data-ng-model="search.carDetails">
        <option value="">All</option>
        <option value="2">2</option>
        <option value="4">4</option>
        <option value="9">9</option>
    </select>

Provider:

    Atlas Choice <input type="checkbox"  data-ng-model="search.company" ng-true-value="Atlas Choice" ng-false-value="" value="Atlas Choice" />

    Holiday Autos <input type="checkbox"  data-ng-model="search.company" ng-true-value="Holiday Autos" ng-false-value="" value="Holiday Autos" />

    Avis <input type="checkbox"  data-ng-model="search.company" ng-true-value="Avis" ng-false-value="" value="Avis" />

Now I want to create a custom filter in my controller, that can iterate over the items in my ng-repeat and return only the items that meet certain criteria - for example, I might create an array of values based on which 'provider' checkboxes are checked, then evaluate each ng-repeat item against that. I just can't work out how I'd do that though, in terms of the syntax - can anyone help?
Here's my Plunker:
http://plnkr.co/edit/lNJNYagMC2rszbSOF95k?p=preview
Answer: If you want to run some custom filter logic you can create a function which takes the array element as an argument and returns true or false based on whether it should be in the search results. Then pass it to the filter instruction just like you do with the search object, for example:
JS:
$scope.filterFn = function(car)
{
    // Do some tests

    if(car.carDetails.doors > 2)
    {
        return true; // this will be listed in the results
    }

    return false; // otherwise it won't be within the results
};

HTML:
...

...

As you can see you can chain many filters together, so adding your custom filter function doesn't force you to remove the previous filter using the search object (they will work together seamlessly).
Comment: Of course it can. I've decided for a more verbose version, however, to make it more clear as a learning example.
Comment: Very interesting! The filter can be simplified to `return car.carDetails.doors > 2;` though.
Comment: In case you need more sophisticated filters, you can also [pass your filters more than one argument](http://stackoverflow.com/questions/16227325/how-do-i-call-an-angular-js-filter-with-multiple-arguments).
Comment: I like `return (car.carDetails.doors > 2);`
Comment: @mirrimx i didnt get when this function will be called ?
Comment: @nh2 is there any way to pass more then one argument into a filter defined as a controller function, rather then a filter defined as en explicit $filter?
Comment: @AbrahamP Unfortunately I don't know that.
Comment: Is there a way to match one filter or another.  IE if you had 2 custom filters could you match customFilter1 OR customFilter2?
Comment: When you are working directly with $scope then you can access the search criteria directly through $scope. What is the solution when you are working with the "as vm" option ? in that case 'this' is not the controller.
Comment: Heck, if we're flexing, function could be inlined as data-ng-repeat="r in results | filter:search | filter:function(r){return r.carDetails.doors>2;}" or smth. But if you want to get called again for future contracts, prefer the readable answer above. There's zero performance gain.
Answer: If you still want a custom filter you can pass in the search model to the filter:

Where definition for the cartypefilter can look like this:
app.filter('cartypefilter', function() {
  return function(items, search) {
    if (!search) {
      return items;
    }

    var carType = search.carType;
    if (!carType || '' === carType) {
      return items;
    }

    return items.filter(function(element, index, array) {
      return element.carType.name === search.carType;
    });

  };
});

http://plnkr.co/edit/kBcUIayO8tQsTTjTA2vO?p=preview
Comment: can you give more than one parameter to a custom filter?
Answer: You can call more of 1 function filters in the same ng-repeat filter

Comment: possible to OR filters instead of AND?
Comment: mmm... i think the best option is a function to do that, here is an example (not work)

http://plnkr.co/edit/PNwyDKXk9RQcur8Tpp8w?p=preview

best
Answer: One of the easiest ways to fix this is to use the $ which is the search all.
Here is a plunker that shows it working. I have changed the checkboxes to radio ( because I thought they should be complementary )..
http://plnkr.co/edit/dHzvm6hR5P8G4wPuTxoi?p=preview
If you want a very specific way of doing this ( instead of doing a generic search ) you need work with functions in the search.
The documentation is here
http://docs.angularjs.org/api/ng.filter:filter


Xamarin WKWebView not opening email and tel links

Question: Please excuse my newbie question, I am a very new Xamarin developer, and I don't know Swift, so answers in Swift have been usless, as I haven't been able to translate it to C#. I found some resources in Swift that were similar to this issue, but I do not know Swift, so was unable to translate the code into a xamarin solution. I was unable to get any link to work in a webpage viewed within the WKWebView that my app uses. Now, I can open links that have the "target=_blank" attribute, but I am unable to open any other link, specifically, links that open within the current window, and links that have the "mailto:" and "tel" attributes in the URL. I got the target=_blank links to work by adding the following class to the WebViewController, and a line to the ViewDidLoad method:
public class NavDelegate : WKUIDelegate
    {

        public override WKWebView CreateWebView(WKWebView webView, WKWebViewConfiguration configuration, WKNavigationAction navigationAction, WKWindowFeatures windowFeatures)
        {
            var url = navigationAction.Request.Url;
            if (navigationAction.TargetFrame == null)
            {
                webView.LoadRequest(navigationAction.Request);
            }

            return null;
        }
    }

Here is the line added to the ViewDidLoad() method:
    WebAppView.UIDelegate = new NavDelegate();
And the complete ViewDidLoad method:
public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            WebViewLogo.Owner = this;

            //Check System Version and set WebView accordingly
            //WKWebView only supported on iOS Versions 11+
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
                View.Frame = new CoreGraphics.CGRect(0, 108, 1024, 611);
                View.AddConstraint(NSLayoutConstraint.Create(View, NSLayoutAttribute.Height, NSLayoutRelation.Equal, View, NSLayoutAttribute.Height, 1.0f, 0.0f));
                View.AddConstraint(NSLayoutConstraint.Create(View, NSLayoutAttribute.Width, NSLayoutRelation.Equal, View, NSLayoutAttribute.Width, 1.0f, 0.0f));
                View.AddConstraint(NSLayoutConstraint.Create(View, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, View, NSLayoutAttribute.Trailing, 1.0f, 0.0f));
                View.AddConstraint(NSLayoutConstraint.Create(View, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, View, NSLayoutAttribute.Bottom, 1.0f, 43.0f));

                var WebAppView = new WKWebView(View.Frame, new WKWebViewConfiguration());
                WebAppView.UIDelegate = new NavDelegate();
                View.AddSubview(WebAppView);
                //set the margins and constraints

                // Add a tap recognizer to reset timer
                var actionGestureRecognizer = new UITapGestureRecognizer(this, new ObjCRuntime.Selector("HandleActionEvent:"));
                actionGestureRecognizer.NumberOfTapsRequired = 1;
                actionGestureRecognizer.Delegate = new GestureDelegate();
                WebAppView.AddGestureRecognizer(actionGestureRecognizer);

                // Load the quote
                //Attempt to get the current quote if active
                var storedQuoteDataAsJson = QuoteManager.FetchQuote();

                // If quote is empty or expired pop to the contact screen
                if (String.IsNullOrEmpty(storedQuoteDataAsJson) || !QuoteManager.IsQuoteActive((int)NSUserDefaults.StandardUserDefaults.IntForKey("QuoteExpireTimeInSeconds")))
                {
                    AppDelegate.Self.PopToTarget(ControllerScreen.ContactController);
                }

                // Load the quote
                Quote currentQuote = QuoteManager.DeserializeQuote(storedQuoteDataAsJson);
                if (currentQuote != null)
                {
                    // NOTE: https required for iOS 9 ATS
                    var url = String.Format("{0}{1}", NSUserDefaults.StandardUserDefaults.StringForKey("WebURL"), currentQuote.QuoteID);
                    WebAppView.LoadRequest(new NSUrlRequest(new NSUrl(url)));
                }
            }
            else //UIWebView is not supported on iOS versions less than 11, so must use UIWebView
            {

                View.Frame = new CoreGraphics.CGRect(0, 108, 1024, 611);
                View.AddConstraint(NSLayoutConstraint.Create(View, NSLayoutAttribute.Height, NSLayoutRelation.Equal, View, NSLayoutAttribute.Height, 1.0f, 0.0f));
                View.AddConstraint(NSLayoutConstraint.Create(View, NSLayoutAttribute.Width, NSLayoutRelation.Equal, View, NSLayoutAttribute.Width, 1.0f, 0.0f));
                View.AddConstraint(NSLayoutConstraint.Create(View, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, View, NSLayoutAttribute.Trailing, 1.0f, 0.0f));
                View.AddConstraint(NSLayoutConstraint.Create(View, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, View, NSLayoutAttribute.Bottom, 1.0f, 43.0f));
                var WebAppView = new UIWebView(View.Frame);
                View.AddSubview(WebAppView);
                //set the margins and constraints

                // Add a tap recognizer to reset timer
                var actionGestureRecognizer = new UITapGestureRecognizer(this, new ObjCRuntime.Selector("HandleActionEvent:"));
                actionGestureRecognizer.NumberOfTapsRequired = 1;
                actionGestureRecognizer.Delegate = new GestureDelegate();
                WebAppView.AddGestureRecognizer(actionGestureRecognizer);

                // Load the quote
                //Attempt to get the current quote if active
                var storedQuoteDataAsJson = QuoteManager.FetchQuote();

                // If quote is empty or expired pop to the contact screen
                if (String.IsNullOrEmpty(storedQuoteDataAsJson) || !QuoteManager.IsQuoteActive((int)NSUserDefaults.StandardUserDefaults.IntForKey("QuoteExpireTimeInSeconds")))
                {
                    AppDelegate.Self.PopToTarget(ControllerScreen.ContactController);
                }

                // Load the quote
                Quote currentQuote = QuoteManager.DeserializeQuote(storedQuoteDataAsJson);
                if (currentQuote != null)
                {
                    // NOTE: https required for iOS 9 ATS
                    var url = String.Format("{0}{1}", NSUserDefaults.StandardUserDefaults.StringForKey("WebURL"), currentQuote.QuoteID);
                    WebAppView.LoadRequest(new NSUrlRequest(new NSUrl(url)));

                }
            }
        }

Any help would be much appreciated. Thanks in advance.
Comment: Did you ever find a solution to this?
Comment: How did you solve the target _blank?
Answer: This should be possible by using WKNavigationDelegate
class AllowAllDelegate : WKNavigationDelegate
{
    public override void DecidePolicy(WKWebView webview, WKNavigationAction action, Action<WKNavigationActionPolicy> actionCallback)
    {
        // do some checks if you want to filter actions
        actionCallback(WKNavigationActionPolicy.Allow);
    }
}

use it
WebAppView.NavigationDelegate = new AllowAllDelegate();

Same for UIWebView with UIWebViewDelegate
class AllowAllOldDelegate : UIWebViewDelegate
{
    public override bool ShouldStartLoad (UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
    {
        // do some checks if you want to filter actions
        return true;
    }
}

use it
WebAppView.Delegate = new AllowAllOldDelegate();

You can also avoid creating new classes, if you use the Weak Delegate mechanism.
Answer: I got the following to work.  Keep in mind my entire project is based off of Xamarin's "HybridWebView" sample with custom HybridWebViewRenderer classes for iOS and Android.  I also used the information in the original post of this question.  I did not run into the same issue that this user had though.
New class:
public class MyWKUIDelegate : WKUIDelegate
{
    public override WKWebView CreateWebView(WKWebView webView, WKWebViewConfiguration configuration, WKNavigationAction navigationAction, WKWindowFeatures windowFeatures)
    {
        var url = navigationAction.Request.Url;
        if (navigationAction.TargetFrame == null)
        {
            webView.LoadRequest(navigationAction.Request);
        }

        return null;
    }
}

Assigned my new MyWKUIDelegate to the UIDelegate property of my WKWebView instance:
var config = new WKWebViewConfiguration { UserContentController = userController };

userController.AddScriptMessageHandler(this, "native");
WKWebView webView = new WKWebView(Frame, config);
webView.UIDelegate = new MyWKUIDelegate();


To convert datatype of a vector

Question: Please guide me how i can convert a vector of string
std::vector<string> strVect; --> std::vector<float or double> flVect;

(e.g. strVect contains values like { "0.1111", "0.234", "0.4556"})
into a vector of floats using c++.
Thanks in advance.
Comment: @user986789: "Thanks can you me the codez". FTFY.
Comment: I can't tell what you're trying to do but I bet `std::transform` combined with `boost::lexical_cast` would do the job.
Comment: @user986789: http://bit.ly/SWseKZ
Comment: Thanks can you give me its syntax.
Answer: In addition to the existing answers, a very easy way is to use C++11 string conversion functions and C++11 lambdas:
std::vector<string> strVect = ...;
std::vector<float> flVect(strVect.size());
std::transform(strVect.begin(), strVect.end(), flVect.begin(),
               [](const std::string &arg) { return std::stof(arg); });

And analogous for double, just with std::stod, of course.
Comment: The first wont work. `stof` is overload and you have to cast it to the correct type. And `flVect(strVect.size())` probably has no overhead here, but I prefer `vector::reserve`. That way you don't end up with an unexpected performance hit if this ever becomes a generic context.
Comment: @pmr Indeed, cppreference.com was lying to me (I should have realized myself that nothing working on `std::string` is really working on `std::string` alone).
Answer: Here's a solution without using boost:
std::vector<string> strVect;
//...
std::ostringstream ss;
std::vector<double> flVect( strVect.size() );
for( size_t i = 0; i < strVect.size(); ++i )
{
    ss.str(strVect[i]);
    ss >> flVect[i];
}

Comment: You have to clear the string stream in every iteration. Otherwise this won't generate the desired output.
Comment: What about the even simpler `ss.str(strVect[i])` instead of `ss << strVect[i]`, which would make the clearing unneccessary and the use of a `std::ostringstream` more appropriate (and in the end would be worth an up-vote).
Comment: @ChristianRau I fixed that too, although I'm not sure this makes the example easier to grasp :)

To convert datatype of a vector


Why am I getting a syntax error on offset_adjusted_list variable?

Question: My code is showing a syntax error over offset adjusted list variable.  Why is this happening and how can I go about fixing this?
Comment: Hint: count your `(`-s and `)`-s.
Comment: You are missing a closing bracket (`)`) on the end of the line `offset = list(int(range(1, 27))`.
Comment: ruakh and jono2906 that worked.  Thank you so much :)
Answer: you are missing a ")" in the line 3
offset = list(int(range(1,27)))

also range(1,27) gives you a list of numbers from 1..27 excluding 27.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]

also you can on use a int() on a list input. It should be either number or a string.
there is no ascii attribute in string module. it should be ascii_lowercase
string.ascii_lowercase

((offset//2)+2)

above line should be like this
(len(offset) // 2) + 2)

Answer: Error Statement -1: list(int(range(1,27))
You have missed one closing bracket ')' in line offset = list(int(range(1,27))
Even after correction, there is error in code: range will return list of values, while int takes single numeral value, So int should not be use in this case.
After correction:  list(range(1,27))
String Library

String library does not have attribute ascii, instead use ascii_lowercase
Use dir(module) to get list of all the functions supported by module

Error Statement -2: offset//2
Arithmetic operations can be applied in value of List, not on List as container
Comment: Thank you that was a good way of looking at it :)


Inserting element in [String] array changes its type

Question: struct Numbers {
    var list: [String] = [
        "one",
        "two",
        "three"
    ]

    func returnList() -> [String] {
        var sortedList: [String] = self.list.sorted()
        var finalList: [String] = sortedList.insert("four", at: 0)
        return finalList
    }
}

finalList is inferred to be a () instead of [String]. If I specify the type [String] I get the message:

Cannot convert value of type '()' to specified type '[String]'

Why on earth?
Comment: Because `insert` returns `Void` aka `()` and modifies the array inplace? Just remove the `finalList` variable and return `sortedList`.
Comment: See [this very similar question](https://stackoverflow.com/q/66452912/5133585) about `append` rather than `insert`, or [this question](https://stackoverflow.com/q/66649002/5133585) about `subtract`.
Answer: You've misunderstood the error message.
The problem is that sortedList.insert does not return a value. (We express this by saying it returns ().) Hence it cannot be assigned to finalList: [String], for the simple reason that it is not a [String].
So just change
var sortedList: [String] = self.list.sorted()
var finalList: [String] = sortedList.insert("four", at: 0)
return finalList

To
var sortedList: [String] = self.list.sorted()
sortedList.insert("four", at: 0)
return sortedList

Comment: I grant that it can be a little confusing knowing which Swift methods return a value and which ones operate directly on a mutable target. Your code exemplifies both.


GCM Android Push Notification: send OK but not delivered

Question: I'm trying to send push notification to android devices. I have not problem to register the ID of the emulator or the devices, but it's impossibile to receive messages also if the send status is 200 OK.
I also try to look to firewall settings, but it's already turned off.
I tried also to use PushBots service from web: same thing. Device registered correctly, message sent, but not delivered to emulator or devices.
Comment: Can you post your code
Answer: It was my mistake. I didn't notice the app was giving me exception when sending push from web for an error in the manifest Receiver.
Implemented the NotificationManager now I receive the push messagge into device.
<code> public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

 @Override
      public void onReceive(Context context, Intent intent) {

    // Explicitly specify that GcmMessageHandler will handle the intent.
    ComponentName comp = new ComponentName(context.getPackageName(),
            GcmMessageHandler.class.getName());

    // Start the service, keeping the device awake while it is launching.
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);
}

 }

 @Override
        protected void onHandleIntent(Intent intent) {

              Bundle extras = intent.getExtras();

    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

    String messageType = gcm.getMessageType(intent);

   mes = extras.getString("title");

   sendNotification(mes);
   sendAlert(mes);
   Log.i("GCM", "Received : (" +messageType+")  "+extras.getString("title"));

    GcmBroadcastReceiver.completeWakefulIntent(intent);

}
</code>


`curl` from a Docker container's network namespace produces different results than `curl` from the container itself

Question: I've set up a Docker container with the ubuntu image. I get different results when I curl from the Docker container than when I enter the container's network namespace and try the same command. What's taking place here?
# Set up the container
docker run -d -it --name mycontainer ubuntu
docker exec mycontainer apt update
docker exec mycontainer apt install -y curl

# Run curl but get two different outputs
docker exec mycontainer curl http://yahoo.com
    # => redirect
PID=$(docker inspect -f '{{.State.Pid}}' mycontainer)
sudo nsenter -n -t $PID curl http://yahoo.com
    # => curl: (6) Could not resolve host: yahoo.com

Why is dns not working from the network namespace when it appears to work from the container? Likewise, I fail to get dns info when I nslookup or dig from the namespace but succeed when I do it from the container.
When in the network namespace, I can check the dns, and I get the same values as I do when checking from my host:
sudo nsenter -n -t $PID nmcli dev show | grep DNS
# => IP4.DNS[1]:                             18.104.22.168
# => IP4.DNS[2]:                             184.108.40.206
# => IP4.DNS[3]:                             192.168.68.1

Answer: When you run :
sudo nsenter -n -t $PID ...

You use the container's network namespace, but you use host's DNS resolution mechanism.
Try to put (one by one) following entries in your host's /etc/resolv.conf
nameserver 192.168.68.1
nameserver 18.104.22.168
nameserver 126.96.36.199

to see if it improves.
Comment: What are `nameserver`s in your host's /etc/resolv.conf ?  You can also try to put `nameserver 127.0.0.11` in your host's /etc/resolv.conf.
Comment: If you can paste the result of `docker inspect mycontainer`, I'll take a further look.
Comment: It produces no change in behaviour. I don't find that surprising, though, because in my initial experiments, I get those nameserver values when checking my DNS from the host.
Comment: In the container, `/etc/resolv.conf` holds only 2 lines: `nameserver 127.0.0.11` and
`options edns0 trust-ad ndots:0`. I'm not sure what it's doing for dns resolution.
Comment: Thanks for asking. Here's my host's `/etc/resolv.conf`: https://pastebin.com/DEbEFDij. It looks rather similar to the container's. I find that adding `nameserver 127.0.0.11` to my host's `/etc/resolv.conf` does indeed make my curl command work. But trying public nameservers `220.127.116.11` or `22.214.171.124` does not. Have you any idea why this is?
Comment: `188.8.131.52` works in my host, container and nsenter. What do you get when you do `ping 22.214.171.124` ?
Comment: `ping 220.127.116.11` succeeds (0% packet loss) from my host, the container, and the namespace. From the latter two, the output specifies the IP address of the gateway (another container at 172.19.0.2): `From 172.19.0.2: icmp_seq=2 Redirect Host(New nexthop: 172.19.0.1)`. Still, adding it as a nameserver doesn't appear to curl executions from the namespace.
Comment: Thanks, Philippe. Here's my `docker inspect` for this container: https://pastebin.com/Run4zUpE. And here's `docker inspect` for the mitmproxy which I've set as the default gateway for that container: https://pastebin.com/Uw9RnJHq.


incompatible types with type variables

Question: Can anyone tell me why the following fails to compile?
class A<K> {

    public <K> A() {
    }

    public static <K> A<K> create(Class<K> k) {
        return new A<K>();
    }
}

public class B<K, V> {

    A<K> ak;

    public <K, V> B(Class<K> klass, V v) {
         ak = A.create(klass);
    }
}

It fails with:
[javac] /home/.../src/B.java:17: error: incompatible types
[javac]         ak = A.create(klass);
[javac]                      ^
[javac]   required: A<K#2>
[javac]   found:    A<K#1>
[javac]   where K#1,V,K#2 are type-variables:
[javac]     K#1 extends Object declared in constructor <K#1,V>B(Class<K#1>,V)
[javac]     V extends Object declared in constructor <K#1,V>B(Class<K#1>,V)
[javac]     K#2 extends Object declared in class B
[javac] 1 error

This is an SSCCE so please don't ask what I am trying to accomplish.
Comment: Related: http://stackoverflow.com/questions/18688882/what-is-the-purpose-of-type-arguments-in-constructor-call-following-new/18688969#18688969
Comment: by the way, the `k` parameter in `create` is useless. `create` can be declared as `public static  A create()`
Comment: @newacct the idiom is described here: http://docs.oracle.com/javase/tutorial/extra/generics/literals.html but I grant it may not make sense in this example since it is only an SSCCE. TBH it's not entirely clear to me when using that idiom is not necessary but sometimes adding the class literal explicitly silences xlint compiler warnings.
Comment: @MarcusJuniusBrutus: you pass a class object when you need to use it at runtime. You don't need it here. After you remove it, you may have to explicitly specify the type argument when calling it because the compiler cannot infer it from the arguments.
Answer:
get rid of <K> in the constructor of A
get rid of <K, V> in the constructor of B

Constructors do not need to redefine the type parameters of the class. If you do that, they are defined as new type parameters which hide the ones in the class (Eclipse warns you about that).
Comment: It's interesting though that only the  in B's constructor needs to to removed, the  in A's constructor can remain. I suppose that's because A's constructor signature does not use K so it's not hiding anything.
Comment: it can remain, in order for the above code to work, but it is still wrong ;)

incompatible types with type variables


Issue in dynamic form list when using useState in ReactJS

Question: here is my code.
The code:
    const [isRent, setIsRent] = useState(null);

      const residentialSituation = [
        { value: 'rent', label: 'I rent' },
        { value: 'owned', label: 'I owned' },
      ];

    <Form>
      <Form.List name="users">
        {(fields, { add }) => {
          return (
            <>
              <Button
                type="dashed"
                onClick={() => {
                  add();
                }}
                block
              >
                Add
              </Button>
              {fields.map((field, i) => (
                <Collapse key={i} accordion>
                  <Panel header={i}>
                    <Form.Item
                      name={[field.name, 'residentialSituation']}
                      fieldKey={[field.fieldKey, 'residentialSituation']}
                    >
                      <Select
                        autoComplete="new-password"
                        showSearch={true}
                        onChange={(value) => setIsRent(value)}
                      >
                        {residentialSituation.map((el) => (
                          <Select.Option value={el.value} key={el.value}>
                            {el.label}
                          </Select.Option>
                        ))}
                      </Select>
                    </Form.Item>

                    {isRent === 'rent' && (
                      <Form.Item
                        label="price"
                        name={[field.name, 'rent']}
                        fieldKey={[field.fieldKey, 'rent']}
                      >
                        <Input />
                      </Form.Item>
                    )}
                  </Panel>
                </Collapse>
              ))}
            </>
          );
        }}
      </Form.List>
    </Form>

When I am clicking on add button new collapse was successfully adding.
Now I have two options in my select component choose I rent or I owned. When I am choosing I rent I am setting that value in useState and checking if isRent === 'rent' then render second input.
The problem is when I am adding a second collapse the select component is also reading from the state.
How can I set the different states for the different collapses?
Answer: I updated your code.
So you need to do following.

Your useState state should be an object.

    const [inputState, setInputState] = useState({});

In select you should pass 2 arguments, select value and id.

    <Select onChange={(value) => handleChange(value, i)}>
       ...
    </Select>

In handleChange function do following. For every id set appropriate value.

    const handleChange = (e, i) => {
        setinputState({
          ...inputState,
          [i]: e,
        });
      };

With following condition check and render your component

    {inputState[i] === 'rent' && (<Form.Item> ... </Form.Item>}


Issue with updating list in snake game

Question: So I've been programming a snake game using python mode for processing, but I have been having an issue with the list I have set up for keeping track of the body of the snake itself.
My current implementation uses a list of vectors to keep track of the location of each segment of the snake. I then loop through this list to display the squares for each segment. At the beginning of the game, the list only has 1 entry (the head), but upon eating a piece of food, I insert a new vector to the front of the list with the same value as the current head. I then update the list but looping through it and finally, I update the head by using a velocity vector.
scl = 10
dim = 20

def setup():
    global s
    global f
    size(dim * scl, dim * scl)
    s = Snake()
    f = Food()

def draw():
    background(201)
    global s
    global f
    if s.eat(f):
        f.location()
    s.update()
    s.display()
    f.display()
    delay(50)

class Snake:
    def __init__(self):
        self.body = [PVector(0, 0)]
        self.v = PVector(1, 0)
        self.total = 1

    def update(self):
        for i in range(self.total - 1):
            self.body[self.total - 1 - i] = self.body[self.total - 2 - i]
        print("Position")
        print(self.body)
        self.body[0].x += self.v.x * scl
        print(self.body)
        self.body[0].y += self.v.y * scl
        print(self.body)

    def display(self):
        fill(101)
        for i in range(self.total):
            rect(self.body[i].x + 1, self.body[i].y + 1, scl - 2, scl - 2)

    def eat(self, p):
        tmp = self.body[:]
        dis = dist(self.body[0].x, self.body[0].y, p.pos.x, p.pos.y)
        if dis < 1:
            self.total += 1
            self.body.insert(0, tmp[0])
            return True
        else:
            return False

I expect the output to be a list of differing vectors, each that draw a square next to the previous and next entries. Instead, after eating food, all the vectors are the same within the body list. Does anyone know how I can fix this?
Comment: Why don't you install [pudb](https://github.com/inducer/pudb) and debug your code to find out?
Answer: You seem to misunderstood, how python's list handles it's values.
tmp = self.body[:]

makes shallow copy, not deep copy. And:
self.body[...] = self.body[...]

doesn't copy the value. It just passes the value from one place, to another. So when you move your values in self.body by one offset, the first and the second element will end pointing to the same value.
Try something like this:
def update(self):
    for i in range(self.total - 1):
        self.body[self.total - 1 - i] = self.body[self.total - 2 - i]
    print("Position")
    print(self.body)
    self.body[0] = PVector(self.body[0].x + self.v.x * scl, self.body[0].y + self.v.y * scl)
    print(self.body)

and in eat function:
self.body.insert(0, PVector(tmp[0].x, tmp[0].y))

Issue with updating list in snake game


How to show y axis text labels instead of the count in power bi

Question: I am fairly new to power bi and I am trying to create a stacked bar chart of two columns ( one column contains type: individual, Business and government. a second column contains new connections, complaints , etc) I want to create a stacked bar chart with the type on the x-axis and the reason on the y axis. so what I did is this:

the x axis shows the 3 types: government, individual and business but the y axis shows 0,50,100 and not the actual labels ( new connections, complaints,...). is there a way to show the text ( new connections, complaints, etc) on the y-axis instead of 0,50,100
this is the columns:

I tried to change the count in the y-axis but there was no button for it, I need to change the y axis labels to the text inside the actual column instead of the current numbers, is there a way to do this?
Comment: You can't. Y-axis has to be numbers. Btw., you are using a 100% stacked column chart, hence the numbers 0%, 50% and 100%.
Answer: Hello there should be a button for it as in the image below.

Like the red arrow shows, and you can change it there
Comment: Did you even read the question?
Comment: Change to what? call_reason is not a numerical field, so the only available aggregation is Count.
Comment: i see now, then what you can do is create a measure with count distinct for each type of the call_reason


Qt application: Failed to load platform plugin "windows" on Windows 8 but no issues on Windows 7

Question: A lot of similar questions has been posted, but noone has worked for me.
On Windows 7, i am able to run my program standalone with the appropriate dll's in the executables folder.
At Windows 8.1, I am not able to run my project either with Qt Creator nor standalone. I am getting the error

This application failed to start because it could not find or load the
  Qt platform plugin "windows". Available platform plugins are: minimal,
  offscreen.

I put my platform dll's in ./platforms and ./ as suggested here and here amongst other places. Still, my application won't launch and gives me the same error.
I've included all dll's from my C:\Qt\Qt5.2.0-mingw\5.2.0\mingw48_32\plugins\platforms directory.
How can I solve this problem?
Comment: Try platformS folder in the same path as your executable (there is an 's' at the end), on my Windows 7 system the MinGW Qt build runs without platforms/qwindows.dll, probably that is needed on Windows 8.
Comment: Edited that, I had actually used platform**s**
Answer: For me, with installed Qt 5.2.0 and MSVC 2012, the following dll's were needed to execute app (Release version) on Windows 7 and 8.1 :
-example.exe //My application
-icudt51.dll
-icuin51.dll
-icuuc51.dll
-libEGL.dll
-libGLESv2.dll
-Qt5Core.dll
-Qt5Gui.dll
-Qt5Widgets.dll
-platforms // Folder
 --qminimal.dll
 --qoffscreen.dll
 --qwindows.dll

Comment: Somewhat irrelevant I think since I am using the mingw compiler
Comment: @Wilhelmsen Since you don't provide list of dll's that you used, I didn't know if it only qt creator+mingw problem or it's problem in included dll's. However, I must admit that I did not carefully read the question and missed the fact that your app not executes in QtCreator.

Qt application: Failed to load platform plugin “windows" on Windows 8 but no issues on Windows 7


How can I remove a screw broken off in a fan-rated junction box?

Question:
It's a new house and this how the contractor employees left it
Comment: A newly built house, I would be talking to the builder.  It should be his problem if his contractors left it like that.
Comment: My first attempt would be unscrewing it with a pair of Vice Grips.
Comment: it sure looks like that was installed from the other side. (and is not actually broken)
Comment: Are you sure those aren't the fan mounting crews??  Looks weird but don't wreck them until you're sure.
Comment: Are you certain that it is a broken-off screw, and not an intact screw which some bright spark screwed in from the top of the box (like the other one to the left)?
Comment: which one, the left or the right screw
Comment: Those look like studs in stand-offs (sleeve nuts or whatever). Doesn't look broken to me.
Answer: I would use pliers or mole grips, while hoping that the part it is in does not snap.
Also have a pair of pointed pliers on hand just in case it rotates.


"Application not installed on phone " Error for Wallpaper

Question: I made a live wallpaper which was working fine until I did the following changes:

added admob integration.
Changed package name
changed sdk version from 2.1 to 4.1.2

Problem : Whenever I click on Settings button I get error application not installed on phone, even if the application is installed and live wallpaper is set.I'm unable to open setting screen now after doing the above changes.
Note: I'm using unsigned apk (simpling running project through eclipse)
Android Manifiest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.fireworks.nightskylivewallpaper"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="17" />

    <uses-feature android:name="android.software.live_wallpaper" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.fireworks.nightskylivewallpaper.AppLauncher"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.fireworks.nightskylivewallpaper.Gallery_Activity" >
        </activity>
        <activity
            android:name="com.fireworks.nightskylivewallpaper.SettingActivity"
            android:exported="true" >
        </activity>

        <activity
            android:name="com.google.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />

        <receiver android:name="com.fireworks.nightskylivewallpaper.BootReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <service
            android:name="com.fireworks.nightskylivewallpaper.FlareLiveWallpaper"
            android:label="@string/app_name"
            android:permission="android.permission.BIND_WALLPAPER" >
            <intent-filter>
                <action android:name="android.service.wallpaper.WallpaperService" />
            </intent-filter>

            <meta-data
                android:name="android.service.wallpaper"
                android:resource="@xml/flare_lwp" />
        </service>
    </application>

</manifest>

I have referred the following links but no luck on finding the solution:
"Application not installed" for Live Wallpaper, on some phones
Android error: Application is not installed on your phone?
Application not Installed' Error on Android 2.3.4
Android application not installed error
EDIT
flare_lwp.xml
 <?xml version="1.0" encoding="utf-8"?>
    <wallpaper xmlns:android="http://schemas.android.com/apk/res/android"
        android:settingsActivity="com.fireworks.happylivewallpaper.SettingActivity"
        android:thumbnail="@drawable/ic_launcher" />

Please help. Thanks!
Comment: Post your `flare_lwp` XML
Comment: @Apoorv I have added flare_lwp .Now I realised that the refractor doest not change the package name in xmls! Thanks !
Answer: Change the line
android:settingsActivity="com.fireworks.happylivewallpaper.SettingActivity"

to
android:settingsActivity="com.fireworks.nightskylivewallpaper.SettingActivity"

in your flare_lwp XML file. Your package name hasn't been changed there.

“Application not installed on phone ” Error for Wallpaper


Angular directive works on an element in the first page but stop working after navigation (probably a scope issue)

Question: the directive code
directive('stFloatBar', function($log,$window){
        return{
            restrict:'A',
            replace:true,
            transclude:true,
            templateUrl:'partials/directives/topfloatnav.html',
//            scope: {target:'=stFloatBar'},
            link:function(scope,element,attrs){
                var oldvalue;
                $window = angular.element($window);

                        $window.on('scroll',function(ev){
                            scrollShow(attrs.stFloatBar);
                        });

               var back = element.find('.scrollBack');

                var scrollBack = function(){
                  scope.$apply($window[0].scrollTo(0));
                };

                back.bind('click',scrollBack);
                scope.shower = false;
                var scrollShow = function(dest){
                    var trigger =$(dest)[0].getBoundingClientRect().bottom;
                    var triggerPoint = attrs.stFloatTriggerpoint;

                    if (trigger < triggerPoint && scope.shower==false){
                        scope.shower = true;
                        scope.$apply(attrs.stSetfloat);
                    }
                    if(trigger > triggerPoint && scope.shower==true){
                        scope.shower=false
                        scope.$apply(attrs.stSetfloat);
                    }
                };
        }
        };
    })

and the html calling the directive:

basically the directives need to calculate some data from the Html target element (Its bottom)
this work on the first page showing and hiding the floating bar correctly and listening to the scrolling event(doesn't matter if I start with page1 or page2) But when I navigate to the second page I get a console error:
Uncaught TypeError: Cannot call method 'getBoundingClientRect' of undefined

So I guess the problem is that the binding doesn't change, But I can figure how?
Thanks for the help!
Comment: Could it be just that the `template` has not been rendered when `$(dest)[0]` tries to access it while `scroll` event is being fired? In that case, just testing whether `$(dest)` found any elements at all should be enough.
Comment: @musically_ut - thanks! How would I do that
Comment: @musically_ut DONE! solved the problem, you can write this as an answer so I can reward you the points
Answer: In angular, the template is not rendered in the same $digest loop which runs the link function. Hence, the template of the element is empty on page change while the window's scroll event fires irrespective.
Solution is to check whether $(dest) found any elements at all and if it didn't, then not to take any action at all.
Sidenote: It is always best if a directive cleans up after itself by unregistering all event listeners when $destroy event is called on the $scope. Otherwise, the application runs a risk of running into a memory leak.
Comment: how do I do that? register the destroy?
Comment: The `demo` on the link has an example of how to do that: `scope.$on('$destroy', function () { /* unregister listeners */ })`.


An algorithm to find the area of intersection between a convex polygon and a 3D polyhedron?

Question: Suppose I have a set of points in 3D which are all co-planar, and which describe the vertices of a convex polygon. I know the coordinates of all of these vertices, I know the unit normal to the plane of the polygon, and I know the order (in a right-hand sense with respect to the normal) in which the vertices go around the polygon.
I also have a polyhedron, which is in general non-convex, and the surface of which is made of triangles. It is a triangle mesh like the one shown here. It describes a completely enclosed volume (no holes in the surface). I know the coordinates of all the vertices of all the triangles that make up the polyhedron. For a given vertex, I know the list of which triangles it is a vertex of.
One other thing I know, which may or may not be useful, is that the polygon lies "in the vicinity of" a particular pair of vertices of the polyhedron, say the ones with indices $i$ and $j$. So if there were to some kind of a search of the surface of the polyhedron, that would be the place to start.
My task is to find the area of the intersection between the polygon and the polyhedron. I believe this is a well-defined quantity. I need an algorithm to calculate this, hopefully efficiently but at this point I'll take anything.
My thoughts:
I can classify each polygon vertex as either inside or outside the polyhedron. I've written a ray-casting algorithm that computes this fairly accurately and efficiently. That means that each edge of the polygon can be classified as either "both vertices inside", "both vertices outside", or "one in, one out." I can calculate the point of intersection between a given polygon edge and the polyhedron by checking a bunch of nearby triangles.
But that's not enough. For instance, just because both vertices of an edge are inside doesn't mean the whole edge is inside. A "finger" of the polyhedron might intersect an edge without touching either of its endpoints. Furthermore, the polyhedron might intersect the polygon in such a way that it doesn't touch any of the edges at all. Clearly, one must also calculate the intersections between the triangles' edges and the polygon as well.
It gets a bit too complicated for me at that point, and I'm wondering if there is some established algorithm for this?
Perhaps something like: Project the polyhedron onto the plane containing the polygon and then... I don't know.
Comment: If you already have the ray-casting algorithm, why not cast a ray from a vertex along its edge and find whether the first intersection is before the distance to the opposite vertex? Then you can find the intersections on each edge.
Comment: That doesn't help you where a finger of the mesh pokes through the polygon, though. Perhaps you're better off starting by classifying the mesh's vertices by which side of the plane of the polygon they're on.
Comment: @DanHulme Once I've determined which mesh vertices are on which side of the plane, what would I do with that information?
Comment: Use it to find mesh edges that cross the plane and intersect *them* with the plane to find all the crossing points. You can use the crossing points to make a new polygon which is the section of the plane and the polyhedron. (You need to use the topology of the polyhedron to know what order to connect the edges together, because this new polygon is non-convex.) Now just intersect the two polygons in the usual way. I'm making this up as I go along but it sounds plausible.
Comment: @DanHulme So it seems to me that there are two kinds of crossing points: Where an edge of the polygon crosses a triangle, and where an edge of a triangle crosses a polygon. Both kinds can be found by some kind of exhaustive search. I guess the next step would be to throw away vertices of the original polygon that were known to be outside the polyhedron. How do I use the topology of the polyhedron to order the resulting bunch of points?
Comment: If I knew that off the top of my head I'd have posted an answer instead of drip-feeding suggestions one at a time!
Answer: There are different numerical approximations you could use:
A simple solution is to use brute-force Monte Carlo integration. Distribute $N$ random points on the polygon and calculate the number of points inside the 3D polyhedron $N_i$ using ray tracing. The area inside the polyhedron is $A_i=A\frac{N_i}{N}$, where $A$ is the area of the polygon.
To improve convergence of the above algorithm, you can distribute the points on grid on the polygon and jitter the sample positions within each grid cell. This is called stratified sampling.
Further improvement would be to perform the MC integration in 1D instead of 2D. Pick a sample line $L$ that's on the polygon plane and a sample direction $D$ that's on the plane perpendicular to $L$. Select sample line segment $L_s$ that bounds the polygon within $D$-directed lines (min & max of the polygon projection on $L$ for tight fit). For each sample on $L_s$ first calculate the line segment $S$ that intersects the polygon in direction $D$. Next calculate the length of $S$ that's inside the polyhedron $S_i$. You can calculate $S_i$ using ray tracing, by starting from one end of $S$ and marching along $S$ to intersection points of the segment with the polyhedron, summing up the segments of $S$ inside the polyhedron. More specifically, you need to first check if the start point on $S$ is within polyhedron and set the "inside" state accordingly. Then for each intersection flip the state and add the length from previous intersection to $S_i$ if the state changes from inside to outside. The approximation of the polygon area inside the 3D polyhedron is:
$$A_i=\frac{|L_s|}{N}\sum_{i=1}^N S_i$$
Answer: If you have GL (or equivalent) available, the easiest way is probably to set up your projection matrix so that the plane of the polygon is the near clipping plane, draw the polygon into the stencil buffer, and then draw the polyhedron such that inside faces output a 1 fragment. (You could do this by flipping the winding of the polyhedron and turning on back-face culling, or you could check the normal in the fragment shader.) Then the sum of the white pixels in your framebuffer is the intersection area.
Comment: I'm afraid I don't what any of what you just said means. I have almost no background in computer graphics. I'm learning this as I go over the last year or so. I'm writing this code from scratch in C++ for a computational physics application. For reasons I won't go into, this has to run in an environment with almost nothing available. Imagine that this has to be done on a non-network-connected machine in 1997. So straight up from scratch with no special libraries.
Comment: It comes down to the idea you suggested about projecting the mesh into the plane of the polygon. The near clipping plane part cuts off the parts of the mesh "in front of" the plane. Only drawing the inside faces means you'll only see the inside of the mesh where this cut has made a hole, giving you an image of the inside of the polyhedron. Finally, the stencil buffer intersects that image with your polygon. If you had a 3D library available it would be easy to write (because you don't need to do all the maths yourself) and fast (run on the GPU).
Comment: What is "the near clipping plane part"? What do you mean when you say "inside faces"? Does that mean triangles which partially overlap the polygon in projection? What is the "stencil buffer"? As to using a 3D library... no can do. Some networks are VERY selective about what code can and can't be stored on it. I don't mind doing the math of implementing an algorithm. I've had a lot of practice at that. I just need to understand the geometry of the algorithm.


Use DB other than SQL Server with .NET FB app?

Question: Have people had good experiences with solutions other than SQL Server? My host is pretty expensive for adding on SQL Server storage so I'm curious about people's success with other means, especially with scalability in mind.
Thanks...
-Ben
Answer: Maybe time for a different host?  Most shared hosting providers I've worked with have pretty inexpensive shared SQL Server hosting offerings, on the order of $10/month or less.  They also seem to throw in a few SQL Server db's with some of their shared hosting plans.  I just checked one of my current hosting providers and they offer add-ons for $1.50/month for one database.  So it doesn't have to be expensive.
SQL Azure is only $10/month for a 1 GB database if you want high availability.
And what about SQL Server Compact Edition?  It's free and not just for desktop and mobile apps any more.  Check out this blog post:  http://erikej.blogspot.com/2010/07/getting-started-with-sql-server-compact.html
Comment: +1 for *Maybe time for a different host?* Having different hosting options to negotiate with never hurts.
Answer: If your host is going to charge a hefty cost to adding SqlServer, the expense is most likely for licensing, setup, maintenance, etc. You may have better luck (read, a lesser fee) for setup and monthly maintenance with MySql.
Depending on your data, you also have the option of uploading Open Office Calc files to your host and using MySql data connector. Maybe not very scalable, but if your web app is just starting up, and you don't have the means to pay for the scalability of SqlServer, MySql offers some viable options.


Nodejs callback value return

Question: I have calling a method to get datas and trying to return its datas however the get variable is coming as 'false'. Are there any way to return the datas from the get function?
    function GetDatas(key) {
  return new Promise((resolve, reject) => {
    var get = Client.get(key, (err, result) => {
      if (err || !result) {
        return 'no data';
      }
      return result;
    });
    console.log(get);
    resolve(get);
  });
}

Answer: Because Client.get has a callback, you can not return data with the return call. Do it like this:
function GetDatas(key) {
  return new Promise((resolve, reject) => {

    var get = function( callback ) {

        Client.get(key, function( err, result ) {
          if (err || !result) {
            callback( "No data" );

            return false;

          }

            callback( false, result );

        });

    };

    get(function( error, data ) {

        console.log(data);

        resolve( data );

    });

}

Comment: Thanks for your reply, that helped!
Comment: No problem! Happy to help.
Comment: Why mix in the callback rather than just calling resolve in the the original function??
Comment: Because I tried to follow his original design. I dont see what changing the overall design does other than confuse him even more

Nodejs callback value return


db2 - How to get the min date and the next from the same table

Question: I have a table with date attribute and i need to do a query that gets the MIN date and the next of the MIN date
And I tried that :
select min(SC.TIMESTAMP) as minDate, result.TIMESTAMP
from Event SC
INNER JOIN
(SELECT TIMESTAMP from Event
 HAVING  TIMESTAMP > min(SC.TIMESTAMP)
) as result  on  result.BUSINESSID1 = SC.BUSINESSID1
where SC.BUSINESSSTEP = 'CONTAINER_PLACING_EVENT'
and SC.LOCATIONCODE = '1';

Could you please advice how to do that ?
Thanks in Advance
Comment: Please define "next of the MIN date". Does that mean `MIN(SC.TIMESTAMP) + 1 DAY`? Or does it mean the next table date newer than `MIN(SC.TIMESTAMP)`?
Answer: You can use the ROW_NUMBER() OLAP Function:
SELECT *
FROM (
    SELECT
         TIMESTAMP
        ,ROW_NUMBER() OVER (
                 PARTITION BY BUSINESSSTEP, LOCATIONCODE
                 ORDER BY TIMESTAMP ASC
             ) AS RN
    FROM EVENT
    WHERE BUSINESSSTEP = 'CONTAINER_PLACING_EVENT'
      AND LOCATIONCODE = '1'
) A
WHERE RN < 3

This will return as rows instead of columns, but it should get you what you want. If you think your original query would have returned multiple rows (for multiple entities), you can change the PARTITION BY clause to include the column that makes them distinct.
Answer: Perhaps you can rearrange your query into this form:
select
    min(TS), min(TS2)
from
    event,
    (select TS as TS2 from event where TS > (select min(TS) from event))

Add extra criteria as desired. I would try to rewrite yours, but it isn't entirely clear what the criteria for the count are supposed to be. If you are expecting more than one row (for example, the min and min2 of each LOCATIONCODE) then you will probably want a GROUP BY in there.
Also, I wouldn't call a column TIMESTAMP as it is a reserved word.


How to resolve the FileNotFound when using os.execv()?

Question: I am having trouble using os.execv() in Python.
I have a file called test-exec.py that should call another file called helloworld.py (this file should just print hello world). I want the test-exec.py to run helloworld.py
test-exec.py looks like the below:
import sys
import os
if __name__ == '__main__':
   os.execv("usr/bin/python3", ['helloworld.py'])

when running the terminal with the command python3 test-exec.py helloworld.py (the helloworld.py is unnecessary right now) I get this error:
FileNotFoundError:[Errno 2] No such file or directory

but the file helloworld.py is in the directory:
here
I'm using a virtual machine if that helps any.
Comment: Does this answer your question? [How can I make one python file run another?](https://stackoverflow.com/questions/7974849/how-can-i-make-one-python-file-run-another)
Comment: Shouldn't it be `/usr/bin/python3`? (missing one slash in the start...)
Answer: You can just go with the os.system() command. Try using something like this:
If they are in the same directory:
os.system("python3 helloworld.py")

Or if they are not in the same directory:
os.system("python3 path/to/the/file.py")


Will it harm a fridge w R600a refrigerant to set unplugged through winter months?

Question: I purchased a new Samsung Refrigerator. I learned it is charged with R600a and that the life span is not very long due to the inability to recharge the dangerous explosive gas.
I was hoping to expand the life of mine by unplugging it over the winter months when the lake house is not used. Will it harm or help or neither?
Comment: Will the fridge be inside at room temperature during the winter month or will it be exposed to the outside winter temperatures?
Comment: You need to make sure that if a child crawls into the fridge when it's empty that he/she can get out (or, provide a way to keep the child out, or prevent the door from closing).  You may want to remove the door.  Check your local municipal code to see what the rules are.
Answer: R600a is iso-butane. It's flammable, yes, but hardly excessively dangerous. Billions of people carry some around in their pockets or have it lying around the house, as it's one of the most common fuels in lighters.

Image source https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fimages.bonanzastatic.com%2Fafu%2Fimages%2Fec5b%2F2f20%2Fdf25_5296324495%2F__57.jpg&f=1&nofb=1&ipt=909cf9d6dff1fe523535af2e224fa1a6f97f95941095a2df0b5ce4322d450eac&ipo=images no endorsement implied

Image source https://cdnimg.webstaurantstore.com/images/products/large/26462/118551.jpg no endorsement implied
If handled with proper precautions (not mixing with oxygen/air) as any competent refrigeration tech should well be able to do, (they normally evacuate refrigerant vessels completely, and are trained not to vent CFC refrigerants to the atmosphere) it's not particularly dangerous. On the other hand, the odds that Samsung has made their refrigerator economically viable to service are approximately zero, regardless of refrigerant type. Those days are long past, for almost any manufacturer of a household refrigerator. Serviceability is almost entirely restricted to commercial refrigeration equipment at this point in time.
I doubt that turning it off for the winter will particularly extend its life, but it will save on the power bill (and may be required anyway if the "lake house" is not heated in the off-season - my R600a fridge specifies a minimum operating temperature of 55°F/12.8°C - attempting to compress refrigerant that has not evaporated is definitely bad for your compressor and will drastically shorten its life.) As others have already mentioned, keeping the doors open (and ideally cleaning up any meltwater from defrosting before leaving it) is vital to prevent mold problems.
Comment: Isobutane (R600a) is not the same as the butane (i.e. n-butane) which is used a lighter fuel. They are chemically different, such that R600a will have a higher vapor pressure at room temperature than butane lighter fuel, which may make a marginal difference in its flammability.
Comment: The difference is, indeed, marginal.
Comment: The amount of refrigerant needed for a domestic refrigerator is pretty small and self contained, so the risk is considered low. It's why R600a has found its way into your fridge but not your air conditioning unit.
Comment: @Crazymoomin However, in the event of a evaporator coil leak where the refrigerant flows into the well-sealed fridge compartment, there is enough oxygen to cause an explosion. That's why interior electricals, lights, fans and thermostats, are specially designed and sealed (potted) in R600a fridges. Leaving the door open to allow any leak to dissipate into the larger room volume is a good idea.
Comment: @user71659 Leaving the door open for an unplugged fridge is a good idea anyway to prevent mold growth and nasty smells and whatnot
Answer: Unlike e.g. car A/C systems that generally always leak some refrigerant and inevitably need topping up, a domestic fridge or freezer has pretty much a sealed refrigerant path so they work their 20 or 40 years without any dealing with the refrigerant.
In short, don't expect shorter lifespan just because the fridge uses R600a.
R600a is not that much new so most technicians should have been already prepared for working with it, should a need arise. This will only get better when the warranty term expires.
Unplugging is good - as long as you leave the fridge dry, clean and with an open door (1cm or 1/2" gap is enough).
Be sure to keep the fridge door open when it is unplugged, at least for the first month or so. Otherwise you will get a bad smell inside. This is hard when the fridge is in an inhabitated room because people learn from early age that the fridge must be closed. You can tape some object at the door edge in order to prevent closing.
Comment: @Sean either the fridge open, or desiccant, not both. And one would need kilograms of it for an used fridge.
Comment: It may also be worth putting a desiccant in the fridge/freezer to be sure no moisture collects in there. It can be purchased from many home center type stores.
Answer: Unplugging will reduce mechanical wear on the fridge. And keep it from burning energy when not in use. Those seem like good things.
See standard advice about how to prep a fridge that's going to be unused for a long time to avoid mold.
(What I've seen so far suggests you are overestimating the issues associated with R600a.)


How do we ensure that Skyrim SE doesn't update so we don't have to reinstall SKSE?

Question: I bought Skyrim SE a month ago, and installed the Skyrim Script Extender (SKSE) to play with certain mods, but noticed that the game gets updated and breaks my SKSE installation.
Is there any way to prevent this from happening?
Answer: Two things you can do:
Firsty, you can just launch Steam in offline mode so there's no way for anything to update
Secondly you can try this:

Go to where Steam is installed (if you have multiple install spots on separate HDDs you need to go to the drive where Skyrim is installed)
Under steam\steamapps you'll see a bunch of .acf files, open appmanifest_489830.acf (this is the Skyrim .acf file) in notepad (right click .acf > open with > notepad)
Find AutoUpdateBehavior and change it to -1 and make sure BytestoDownload is set to 0
Save and close the notepad document, right click the same .acf (appmanifest_489830.acf) > properties > read-only > press OK

This should fix this issue. If not, may have to use Steam offline.
If in future you want to update the game, revert all these settings, default values for AutoUpdateBehavior is 0 and BytesToDownload is also 0 and make sure you deselect read-only.


Do I have to secure an IKEA TV stand to the wall?

Question: I'm a young adult preparing to move out into an apartment the first time, and I'm trying to fill out some gaps in terms of furniture before I get going.
I found this IKEA tv stand that's perfectly small and cheap, but there's this business about anchoring it to the wall? I've never seen furniture anchored like that in my life!
Do you think it's really necessary to drill holes and all that fuss over such a small stand? (I'm looking at the MOSJO if that helps).
Edit: People keep mentioning kids. I'm moving out for the first time! I don't have a kid or pets! It's just me and a little apartment.
Comment: Don't buy furniture if you don't have a place to put it yet. And don't move assembled IKEA furniture. - So it's going to sit in the box until you move, and then you'll find out it doesn't fit in the nook where you want it anyway. *build to suit*. Not, *buy in preparation*; plenty of time for that later. - Try not to get too excited; 3 months from now you'll wish it was a bag of rice.
Comment: Pictures are always a big help in answering questions.
Comment: For what it's worth, anchoring it to the wall should be a fairly trivial procedure (one that this site no doubt can advise you on), and at least in my experience (many, many different apartments up and down the East Coast of the US over the past several years), landlords have no problem with tenants putting holes that size in walls (and if yours actually does, it's also trivial to fix the hole after). So as you do the cost–benefit analysis, keep in mind that "anchoring it to the wall" should be evaluated a pretty minor cost.
Comment: Do you live in an earthquake zone?  I didn't either, until one happened.  Securing things makes sense.
Comment: @UuDdLrLrSs - If you're living in a rented apartment anchoring to the wall may violate the terms of the lease.
Comment: I'm looking through the assembly instructions for the MOSJÖ (https://www.ikea.com/nl/nl/assembly_instructions/mosjo-tv-meubel__AA-338391-3_pub.pdf), and I'm not seeing anything about anchoring it to the wall. And given the low height and adjustable feet, I don't think it's necessary to anchor it.
Comment: Depends very much on the specific stand.  Some would represent very little hazards, while others would be a much greater hazard.
Comment: I bought a cheap wire shelving unit from a large online retailer and it came with a wall anchor and anchor instructions. I generally plan to anchor all furniture if it is taller than it is wide or deep and I would be sad if it fell over.
Comment: Anchoring to the wall is generally very simple so I consider there to be no reason NOT to do it.
Comment: Regarding recent edit: Are you sure there will be no friend of yours visiting you with their kid(s) or pet(s)? And are you sure you and your guests will be sober all the time?
Comment: @HotLicks It certainly *may*, but in my experience, it *doesn't*. You'll have to check with your lease/landlord, but every place I have been (and as I mentioned before, I've been moving around a lot), it's been no problem. In fact, most places have **strongly** preferred hanging things on the wall with a nail or screw over attaching them to the wall with adhesive, e.g. Command Strips (not that you'd use adhesive for this).
Comment: Not a duplicate, but on the same topic - and one of my highest voted and favorite (because it is about safety and actually means something!) answers: https://diy.stackexchange.com/questions/145348/should-i-tilt-my-diy-self-standing-bookshelf-backwards-to-prevent-it-falling-dow/145354#145354
Answer: No, nothing to do.
If you download the assembly instructions for MOSJÖ you won't see anything about a bracket for attaching the item to the wall, and there isn't one included in the package.
Comment: While all the other answers are sound advice, this answer actually answers OP's question about his specific piece of furniture he wants to buy. The MOSJO is so low to the ground and quite wide so its almost as wide as it is tall that for it to topple over would require physical lifting of the unit. Would you mount a coffee table to the wall ?            As Robin mentioned it doesnt have wall mounts built it nor does it call for them to be added in the insutructions.
Comment: MOSJÖ is 15" tall. It's hard to imagine it falling in any direction.
Comment: Wall anchors aren't included with IKEA furniture because it depends on the type of wall.
Comment: @FreeMan While true that could literally happen to any unit imaginable regardless of whether it is mounted to the wall. The only way to avoid that would be to wall mount the TV, which makes the unit useless.
Comment: I would also add that any improvement of the MOSJÖ like attaching doors etc. needs to rethink the stability and probably add the wall mounts.
Comment: Sorry, I meant the typical bracket you get. I'll edit my answer.
Comment: The one caveat to this - If you've put a large TV on the stand, even though the stand itself is low, a knock what would only wobble the stand could be enough to knock over the TV breaking a device that's far more expensive than the stand.
Answer: "Why do I have to attach IKEA furniture to the wall specifically?  No other furniture seller requires this."
This is because of IKEA's iconography in the minds of the public.
If you buy a locally made TV stand from George Utrecht Family Furniture down on Mill Road, and a child climbs on it and it falls over, you'd never dream of suing old George.  You probably don't even know whose furniture that is.
The idea that furniture toppling was a dangerous threat wasn't really coming together, because it was 1000 worldwide accidents from furniture built by a thousand sellers, suits were rare, and no defendant ever had the marketing "punch" to get the message out.
Needless to say, with IKEA,  lawyers and bereaved saw an opportunity to do some good.  The bereaved were happy to trade away some settlement $, and IKEA was happy to participate.  And IKEA got the word out.
Unfortunately, people misconstrued this message to think "only IKEA furniture needs to be anchored to the wall.  No no!  What Ikea says about anchoring furniture applies to all furniture.
Comment: [Ikea Will Pay $46 Million to Parents of Toddler Crushed to Death by a Dresser](https://www.nytimes.com/2020/01/06/us/ikea-dresser-lawsuit-settlement.html) (nytimes). "The Swedish furniture retailer Ikea agreed to pay a $46 million settlement in a wrongful-death lawsuit brought by the parents of a California toddler who was crushed to death by a popular dresser model that had been recalled after at least five other children were killed." That's why.
Comment: I wholeheartedly disagree with this assessment.   No downvote but this simply isn't true.   The idea of fastening everything to a wall is ridiculous.   Each piece is its own assessment.   It is based on how the piece is made, center of gravity, extraneous forces (doors opening, drawers opening), who is in the house and has access to the furniture, the slope of the floor around the furniture and so on.   I have a TV stand that is pure metal with shelves made of tempered glass - at 70lbs+.   No way in world I need to anchor it... because it isn't cheap IKEA crap.   My IKEA crap is anchored.
Comment: @DMoore: You've apparently never lived in California.
Comment: @RobertHarvey - that would be part of the extraneous factors.  Also in my example my TV stand is 16 inches off the ground.  An NFL player can come at it will full force and hit it (not lift it up) and it wouldn't fall over and would probably barely move.   If I lived in California. I would definitely not be buying IKEA furniture  that stood greater than two feet high with kids in the house.
Answer: Perhaps not, but recognize the risks.
A few years ago, there were several tragic accidents where young children were crushed by Ikea furniture. Since then, Ikea has issued recalls and safety warnings, instructing people to attach their furniture to the wall to avoid such incidents.
The piece you mention is only 30lbs (14 kg) and 15" (40 cm) tall, so it's unlikely to tip over, and unlikely to cause severe harm if it did, so it's a pretty low-risk piece of furniture even if you don't attach it to the wall. But do recognize that it can be a safety hazard, especially if you have rambunctious young children or pets.
As an adult with no kids who normally operates their furniture within the design parameters, however, I have never felt unsafe near an unsecured piece of Ikea furniture. The Ikea police won't track you down if you don't use the wall bracket, but you'll bear the full responsibility if there is an accident.
https://www.thesun.co.uk/living/2021262/why-does-ikea-furniture-fixed-wall/
Comment: Yes, but a child climbing the thing will pull out *all* the drawers, and then stand on them.
Comment: The simple way that toppling can occur is when drawers are pulled out and provide leverage against the center of mass, either by heavy contents or children's weight on them.
Comment: For a lot of my furniture (bookcases, drawers, wardrobes) I place wedges under the front legs, to cause it to tip *back* against the wall slightly. This probably helps it toppling (and may need to be done anyone depending on how flat your floor is)
Comment: @DaveM yep, and customers tend to be outraged, if a drawer breaks off, stressed just barely (read: significantly) over its design load. (Which could have been a safety measure, though...) - So, probably, drawers are sturdier than they should (safely) be.
Comment: @I'mwithMonica but a single drawer needs to survive being pulled all the way out; and yet a single drawer probably won't topple the thing over.
Answer: I have put a lot of these IKEA TV stands together for people  and always suggest that they let me secure them to a wall. The old style TVs were so heavy that the stands were absolutely going no where but the flat screen TVs are light and high and can be positioned toward the front of the stand, making it easy to topple over. I know of adults that have toppled them over trying to get behind the stands to mess around with the cables. You might not have small children but you could have friends over that do. Play it safe and sink in a toggle bolt. Enjoy your new, first apartment and stay safe.
Comment: This is probably the right advice.   It is a safety issue... for the TV.   Why is no one worried about the TV?
Comment: Not just adults messing with the cables. Small kids being foolish. Cats being cats.
Comment: @DMoore the TV was my first thought, I just got here late...
Comment: @FreeMan - I have an 85" TV that is pretty high end... no way in the f'ing world would I put that on an IKEA TV stand.
Comment: @DMoore  You mean you don't think those little half turn bolts are good enough for your TV .. LOL?
Comment: @JACK - I put a full stop to IKEA crap after wife snuck in a dresser (which could easily kill a small child).   You shouldn't be able to nudge a piece of furniture and it wiggles.   That's my limit.
Comment: Reasonable-size TVs are $100 these days and not heavy enough to hurt anyone or be damaged if they fall. Just don't buy that 60" nonsense. Much less 85"
Answer: If you have young children in your house I'd fasten it to the wall. Ikea started providing this as a standard after a child died after tipping over a piece of their furniture. If you don't have children it's not really necessary, just a thing Ikea's lawyers are telling them to include in all their furniture sets now.
https://www.usatoday.com/story/news/investigations/2020/01/06/ikea-settles-46-million-after-dresser-kills-child/2821182001/
Answer: The IKEA piece in question would have come with a small metal bracket with screws. One arm of the bracket attaches to your furniture and the other arm has a largish hole in it which you have to figure out how to attach to your wall, the details of which depend very much on what your wall happens to be made of and how far away from it the piece is. People who don't live in earthquake zones will likely put these brackets in their junk drawers and forget about them.
As others have said, the risk of harm of the thing tipping over scales with (a) whether you live in an earthquake zone (b) whether you have toddlers in the home and (c) the weight of the thing that's resting on it. If the answers are No, No and Light, then you might well just not fret about it. If (a) is true then any local hardware store will advise you on how to secure furniture and if (b) is true then any of the dozen books your family has given you will have chapters on making your house child-safe (which involves strapping the tv to the stand, in addition to hooking the stand to the wall). If (c) is "heavy" then you've been suckered into taking your uncle's 36" trinitron that he doesn't know how to get rid of, and you should leave it at the curb and find a sale on a flat-panel.
As furniture goes, the Mosjo looks pretty ... can I say, "squat"? Not something that's going to flop over when a truck rumbles by. If it was a full-height Billy looming next to your futon, I'd say, yeah, tie that big boy to a stud. I had a room lined with Stens when I lived in San Francisco and you're damn right I hooked them to the walls (lag thread screw hooks into the studs, with short lengths of light chain around every second upright). In the absence of kids, I wouldn't worry about a low TV stand.
Answer: As Robin Whittleton correctly pointed out, MOSJÖ does not need to be anchored to walls, there's no such instruction in the manual and there are no anchoring parts provided.
Considering we're on Home Improvement site, you can add doors, shelves etc. to it on your own. From now on true common sense must work.
There are two modes of failure of the furniture one must take care of. It can either collapse unter the load or it can flip over. Anchoring addresses the second option.
Old furniture used to address the flipping by using heavy frame structure, light doors and few drawers close to floor. Those wont flip because the centre of mass is always in the furniture.
Younger pieces were proteced by screwing together building one big solid body that is heavy enough to be flipped easily.
New pieces are "design" and optimized for price. The result is lighter body structure and heavier doors, taller drawers etc. Glass, which is much heavier than wood, is used more and more. Such pieces must be anchored because even opening door or drawer can move the centre of mass too forward to flip it over.
Another point of view is stability of the whole setup. Older equpment is either smaller or heavier than today's equipment. TV sets were more like boxes (with all three dimensions simillar), new LCD/OLED/plasma screens are more like sheets (one dimension negligible to the other two). Speakers were rather heavy wooden boxes, now they are "design" tall tubes, shells etc.
Now imagine something hitting the MOSJÖ with 20" TV screen on it. It is light, so is the screen so the supports will skid slightly which will put the screen out of ballance, which is, unlike the MOSJÖ, thin and tall...
So, the answer is: "No, you don't need to secure IKEA TV stand to the wall" but if you do secure it properly, the security gain overcome the drawbacks with high margin.
Answer: You should probably anchor most furniture to walls. Almost all furniture has a non neglible toppling hazard, and toppling is mesyy - you do not want your furniture and its contents damaged.
And this can happen easily, especially if your furniture has drawers or e.g. is top heavy.
You will need only very few equipment to secure your furniture and you probably need equipment anyway. E.g. a good cordless drill, screwdrivers, screws, etc. are mandatory for any househould. Otherwise you have to go borrow everything when you want to anything.


Telegram bot API: Can I mix a custom keyboard and a force_reply?

Question: I have a custom keyboard but to process the answer i need a force reply so i get the question back in the next message. I have done this:
var opts = {
    reply_markup: JSON.stringify({
        keyboard: [['OK','Cancel']],
        one_time_keyboard: true,
        resize_keyboard: true,
        force_reply: true
    })
};

The keyboard works but not the force_reply.
Force reply on its own works? Can i not use it in combination with a custom keyboard?
Comment: according to:
https://stackoverflow.com/a/41841237/5320087
its not possible
Answer: It may be late to help you, but here it goes.
Currently only one reply_markup field is allow and this field must contain only one of the following types: ReplyKeyboardMarkup or ReplyKeyboardHide or ForceReply (see docs)
In any case, you can use ReplyKeyboardMarkup that will pop up a custom keyboard in the user app directly and code your bot so it only accept one of the answer in your own custom keyboards.
Furthermore, if you really want to force that the user reply, you can keep sending the same ReplyKeyboardMarkup after each user's invalid answer.
Answer: You need to specify your markup like this :
$replyMarkup = array(
  'force_reply' => true,
  'selective' => true
);

If you need to have custom keyboard you can follow this :
$keyboradsValue = array(
   array("button 1","button 2"),
   array("button 3","button 4"),
);
$replyMarkup = array(
  'keyboard' => $keyboradsValue,
  'force_reply' => true,
  'selective' => true
);

After that you need to encode your object using json_encode
$encodedMarkup = json_encode($replyMarkup, true);

Finally you just put above code at your query string at the rest of sendMessage.
Comment: Did you actually try this?
Comment: If you want to do something you have to call a function. After clicking keyboard by user, That function should be called, After that, The result return to user by another keyboard or display something to user by the URL query which Telegram gave to you.


General Solution to Nonlinear ODE

Question: The functions $f(x) = \tanh(x/2)$ and $f(x) = \coth(x/2)$ satisfy the nonlinear differential equation:
$$-f'' + \textstyle\frac{1}{2}(f^2 - 1)f = 0$$
Is there any way I can find the more general solution to this differential equation knowing the example tanh and coth solutions?
Comment: I do not think that $f(x) = \tanh(x/2)$ or $f(x) = \coth(x/2)$ satisfy $-f'' + \textstyle\frac{1}{2}(f^2 + 1)f = 0$
Comment: The solution is given by $$\left\{\left\{y(x)\to -i \sqrt{\sqrt{1-4 c_1}+1} \text{sn}\left(\frac{1}{2} \sqrt{\sqrt{1-4
   c_1} x^2-x^2+2 \sqrt{1-4 c_1} c_2 x-2 c_2 x+\sqrt{1-4 c_1}
   c_2{}^2-c_2{}^2}|\frac{\sqrt{1-4 c_1}+1}{1-\sqrt{1-4 c_1}}\right)\right\},\left\{y(x)\to
   i \sqrt{\sqrt{1-4 c_1}+1} \text{sn}\left(\frac{1}{2} \sqrt{\sqrt{1-4 c_1} x^2-x^2+2
   \sqrt{1-4 c_1} c_2 x-2 c_2 x+\sqrt{1-4 c_1} c_2{}^2-c_2{}^2}|\frac{\sqrt{1-4
   c_1}+1}{1-\sqrt{1-4 c_1}}\right)\right\}\right\}$$
Comment: The correct version of the equation appears to be $-f''+\frac12(f^2-1)f=0$.
Comment: @ClaudeLeibovici Yes, you're right.  Semiclassical is correct too -- have made typo which I just fixed.
Comment: WolframAlpha does report the (awful) general solution ([link](https://www.wolframalpha.com/input/?i=-y%27%27%2B%28y%5E2-1%29y%2F2%3D0)). Whether that can be placed in more useful form remains to be seen.
Answer: First integral
As usual with a kinetic equation in a potential field, multiply with $2f'$ and integrate
$$
-f'(x)^2+\frac14(f(x)^2-1)^2=C
$$

Reparametrization of the level curve
This has the general form $A^2-B^2=C$ and can thus be parametrized by hyperbolic functions.

Case $C=R^2>0$, $R\ne0$: $f'(x)=R\sinh(g(x))$, $f(x)^2-1=2R\cosh(g(x))$, so that also $$
f(x)f'(x)=  R\sinh(g(x))g'(x)= f'(x)g'(x).
$$
Consequently $g'(x)= f(x)$, so $$g''(x) = R\sinh(g(x)),$$ which has no simple solution, WA gives solutions in terms of the Jacobi amplitude function.

Case $C=-R^2<0$, $R\ne0$: $f'(x)=R\cosh(g(x))$, $f(x)^2-1=2R\sinh(g(x))$, again $g'(x)=f(x)$, $$g''(x)=R\cosh(g(x))$$ follows. Again WA gives solutions in terms of the Jacobi amplitude function.

Case $C=0$: Now $f'(x)=\pm\frac12(f(x)^2-1)$. This results in the two functions that were the point of departure for this question, the form
$$
f(x)=\pm \frac{e^x-K}{e^x+K}
$$
contains all the variants.

General Solution to Nonlinear ODE