Cannot compile against the mongo C++ driver in Fedora

Question: I have trouble compiling a code which uses mongodb-cxx driver. Everything works fine with C driver but not Cxx. I run Fedora 28 and have already installed following packages from Fedors's official repositories:
mongo-c-driver-1.9.5-1.fc28.x86_64
mongo-c-driver-devel-1.9.5-1.fc28.x86_64
mongo-c-driver-libs-1.9.5-1.fc28.x86_64
mongo-cxx-driver-1.1.2-13.fc28.x86_64
mongo-cxx-driver-devel-1.1.2-13.fc28.x86_64
The code I try to compile does not call any API function to connect to database, but as the first step, uses include files and namespaces needed to connect to a mongodb and run operations. The code I try to compile is:
#include <cstdint>
#include <iostream>
#include <vector>
#include <mongo/db/json.h>
#include <mongocxx/client.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>

using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::open_document;

int main() {
  return 0;
}

I try to compile the code as below:

$ c++ --std=c++11 mongo-cxx.cc -o test $(pkg-config --cflags --libs
  libmongocxx)
Package libmongocxx was not found in the pkg-config search path.
  Perhaps you should add the directory containing `libmongocxx.pc' to
  the PKG_CONFIG_PATH environment variable Package 'libmongocxx',
  required by 'virtual:world', not found In file included from
  /usr/include/mongo/db/json.h:20,
                   from mongo-cxx.cc:4: /usr/include/mongo/bson/bsonobj.h:20:10: fatal error:
  boost/noncopyable.hpp: No such file or directory  #include

            ^~~~~~~~~~~~~~~~~~~~~~~

As said, I used Fedora's package manager to install monogdb's cxx driver and did not compile from the source. Is there any extra step that I need to do?
Thanks for your help,
D.
Answer: You are trying to mix the old C++ driver and the new. The package that you have installed, mongo-cxx-driver-devel-1.1.2-13.fc28.x86_64 is the end-of-life "legacy" C++ driver. It doesn't offer a pkg-config file.
Additionally, it appears that your code is attempting to include headers from both the old driver and the new mongocxx driver, which are completely separate projects.
Finally, you don't seem to have the required boost headers installed.
So, what you need to do is:

Find out if you can get packages of the new C++ driver for fedora. If so, uninstall your legacy driver packages, install the new C++ driver packages, and remove the use of the headers that don't start with bsoncxx or mongocxx.
If you can't get the new C++ driver, you need to use the legacy one, and you should stopusing the bsoncxx and mongocxx headers. You will need to install the boost development headers and libraries, and stop trying to invoke pkg-config, which is only used when finding the new C++ driver.
Comment: Thanks for your tip. I removed mongo-cxx packages that I had installed. Since I had installed mongo-c-driver 1.9.5, therefore I had to checkout mongo-cxx-3.2.x which would be compatible with this version of C driver. I did so and build and installed and now it works fine. Thanks again for your help!
Comment: @Dan - Happy to hear you got it working. Hopefully someday fedora will start packaging the new driver.


How do I remove multiple words from a strting in python

Question: I know that how do I remove a single word. But I can't remove multiple words. Can you help me?
This is my string and I want to remove "Color:", "Ring size:" and "Personalization:".
string = "Color:Silver,Ring size:6 3/4 US,Personalization:J"
I know that how do I remove a single word. But I can't remove multiple words. I want to remove "Color:", "Ring size:" and "Personalization:"
Comment: Did you try creating a list of words to remove and looping over it? Basically each time you want to do something multiple times use loop (and inside it do it one time, which you know).
Comment: Can you show the code ?
Comment: Rather than looking at it as removing the parts you don't want, you could approach it as extracting the parts you do want as a new string.
Comment: Instead of removing words if you just want the values why don't you split the string using : and , and then you take the data from indexes 1,3 and 5?
Answer: Seems like a good job for a regex.
Specific case:
import re

out = re.sub(r'(Color|Ring size|Personalization):', '', string)

Generic case (any word before :):
import re

out = re.sub(r'[^:,]+:', '', string)

Output: 'Silver,6 3/4 US,J'
Regex:
[^:,]+   # any character but , or :
:        # followed by :

replace with empty string (= delete)
Answer: string = "Color:Silver,Ring size:6 3/4 US,Personalization:J"
def remove_words(string: str, words: list[str]) -> str:
    for word in words:
        string = string.replace(word, "")
    return string

new_string = remove_words(string, ["Color:", "Ring size:", "Personalization:"])

Alternative:
string = "Color:Silver,Ring size:6 3/4 US,Personalization:J"
new_string = string.replace("Color:", "").replace("Ring size:", "").replace("Personalization:", "")


how to get full address from latitude,longitude in angular 2

Question: I am using angular 2-google-maps.
how to get Address like country and pin from latitude,longitude in angular2 google maps with typescript ?
Comment: This might help http://stackoverflow.com/a/23344822/217408 If not please add the code that demonstrates what you tried and where you failed (with exact error message)
Answer: this works for me
getCurrentLocation() {
this.mapsAPILoader.load().then(() => {
  let geocoder = new google.maps.Geocoder;
  let latlng = {lat: this.currentBusiness.latitude, lng: this.currentBusiness.longitude};
  let that = this;
  geocoder.geocode({'location': latlng}, function(results) {
      if (results[0]) {
        that.zoom = 11;
        that.currentLocation = results[0].formatted_address;
        //console.log(that.currentLocation);
      } else {
        console.log('No results found');
      }
  });
});

}

you have to reassign 'this' because it lost the reference
I hope this helps you
Answer: Using Angular Google Maps you can do something like:
getGeoLocation(lat: number, lng: number) {
    if (navigator.geolocation) {
        let geocoder = new google.maps.Geocoder();
        let latlng = new google.maps.LatLng(lat, lng);
        let request = {
            latLng: latlng
        };
        geocoder.geocode(request, (results, status) = > {
            if (status == google.maps.GeocoderStatus.OK) {
                let result = results[0];
                let rsltAdrComponent = result.address_components;
                let resultLength = rsltAdrComponent.length;
                if (result != null) {
                    this.marker.buildingNum = rsltAdrComponent.find(x = > x.types == 'street_number').long_name;
                    this.marker.streetName = rsltAdrComponent.find(x = > x.types == 'route').long_name;
                } else {
                    alert("No address available!");
                }
            }
        });
    }
}

*Make sure you globally expose google object: declare var google: any;
And then:
mapClicked($event: MouseEvent) {
    this.marker.lat = $event.coords.lat;
    this.marker.lng = $event.coords.lng;
    this.getGeoLocation(this.marker.lat, this.marker.lng);
    console.log("Lat: " + this.marker.lat + " Long: " + this.marker.lng)
}

Component/HTML:
<agm-map [latitude]="marker.lat || centerLat" [longitude]="marker.lng || centerLng" [zoom]="8" (mapClick)="mapClicked($event)">
    <agm-marker *ngIf="marker.lat" (markerClick)="clickedMarker(marker.label)" [latitude]="marker.lat" [longitude]="marker.lng" [markerDraggable]="marker.draggable" (dragEnd)="markerDragEnd(marker, $event)">
        <agm-info-window [disableAutoPan]="true">
            {{marker.label}}
        </agm-info-window>
    </agm-marker>
</agm-map>

Comment: I am getting this error ERROR ReferenceError: google is not defined, plz help me
Comment: @Anil https://stackoverflow.com/questions/42394697/angular2-cannot-find-namespace-google
Answer: Google maps has an api available to do this: https://developers.google.com/maps/documentation/geocoding/intro
Its free for use for free apps/websites.


Why kubernetes reports "readiness probe failed" along with "liveness probe failed"

Question: I have a working Kubernetes deployment of my application.
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  ...
  template:
    ...
    spec:
      containers:
      - name: my-app
        image: my-image
        ...
        readinessProbe:
          httpGet:
            port: 3000
            path: /
        livenessProbe:
          httpGet:
            port: 3000
            path: /

When I apply my deployment I can see it runs correctly and the application responds to my requests.
$ kubectl describe pod -l app=my-app

...
Events:
  Type    Reason     Age   From                                  Message
  ----    ------     ----  ----                                  -------
  Normal  Scheduled  4m7s  default-scheduler                     Successfully assigned XXX
  Normal  Pulled     4m5s  kubelet, pool-standard-4gb-2cpu-b9vc  Container image "my-app" already present on machine
  Normal  Created    4m5s  kubelet, pool-standard-4gb-2cpu-b9vc  Created container my-app
  Normal  Started    4m5s  kubelet, pool-standard-4gb-2cpu-b9vc  Started container my-app

The application has a defect and crashes under certain circumstances. I "invoke" such a condition and then I see the following in pod events:
$ kubectl describe pod -l app=my-app

...
Events:
  Type     Reason     Age               From                                  Message
  ----     ------     ----              ----                                  -------
  Normal   Scheduled  6m45s             default-scheduler                     Successfully assigned XXX
  Normal   Pulled     6m43s             kubelet, pool-standard-4gb-2cpu-b9vc  Container image "my-app" already present on machine
  Normal   Created    6m43s             kubelet, pool-standard-4gb-2cpu-b9vc  Created container my-app
  Normal   Started    6m43s             kubelet, pool-standard-4gb-2cpu-b9vc  Started container my-app
  Warning  Unhealthy  9s                kubelet, pool-standard-4gb-2cpu-b9vc  Readiness probe failed: Get http://10.244.2.14:3000/: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Warning  Unhealthy  4s (x3 over 14s)  kubelet, pool-standard-4gb-2cpu-b9vc  Liveness probe failed: Get http://10.244.2.14:3000/: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Normal   Killing    4s                kubelet, pool-standard-4gb-2cpu-b9vc  Container crawler failed liveness probe, will be restarted

It is expected the liveness probe fails and the container is restarted. But why do I see Readiness probe failed event?
Comment: You have a simple problem. Either there is nothing serving on port 3000 on path / of your app or kubelet can't reach the port, so it is timing out.
Answer: As @suren wrote in the comment, readiness probe is still executed after container is started. Thus if both liveness and readiness probes are defined (and also fx they are the same), both readiness and liveness probe can fail.
Here is a similar question with a clear in-depth answer.
Answer: The readiness probe is used to determine if the container is ready to serve requests. Your container can be running but not passing the probe. If it doesn't pass the check no service will redirect to this container.
By default the period of the readiness probe is 10 seconds.
You can read more here : https://docs.openshift.com/container-platform/3.9/dev_guide/application_health.html
Comment: Yes, at the beginning the pod is working correctly so both checks are OK, but when you crash the application the port 3000 is not available anymore (I guess), and since both checks are configured to check that port you see both errors in the events.
The readiness probe is called every 10 seconds and not only at startup.
Comment: Thanks for the comment. But I have explicitly illustrated that the pod was running for more than 5 minutes without any readiness probe errors. Only after invoking application crash the readiness probe failure appears in the events.
Answer: You configured the same check for readiness and liveness probe - therefore if the liveness check fails, it can be assumed that the readiness fails as well.
Comment: readiness and liveness probes are executed always, if added to the yaml. You can set an interval, but it always checks.
Comment: But shouldn't readiness probe be used only until the pod is up and running? I mean after the pod passes readiness probe, the readiness probe is not being checked anymore?
Comment: The readiness probe is evaluated continuously to determine if an endpoint for the pod should be created as part of a service ("is the application currently ready for production traffic"). Since a temporary problem can occur any time, the readiness check is performed as long as the pod is running.
Answer: please provide an implementation function/method at backend, you can make /health named uri, and can write a liveness logic here and readiness can be your choice too.
/health uri, shall be associated with a function implementation which will can return 200 status code if everything goes fine, else it can be made to get failed


Titanium/Appcelerator images will not show on Android

Question: I'm back with tales of frustrating adventures. This time concerning images on the android side of titanium.
Long story short, I can't get any images to show up for android whatsoever, whether it be a background image or a plain image in an imageView object.
I will provide code I'm trying and keep it extremely small and simple so that it can be easily replicated for all of our testing purposes.
The Code:
Attempt #1 programatically creating view and image:
index.js
var header = Ti.UI.createImageView({
    width: 300,
    image: '/images/header.png',
    width: 300
});

var win = Ti.UI.createWindow({
    backgroundColor: 'white',
    height: Ti.UI.FILL,
    title: 'test',
    width: Ti.UI.FILL
});

win.add(header);

win.open();

Attempt #2 plain jane .xml and .tss styling:
index.js:
$.index.open();

index.xml:
<Alloy>
    <Window class="container">
        Hello World!!
        <ImageView id='img1'></ImageView>
    </Window>
</Alloy>

index.tss:
".container": {
    backgroundColor: 'white'
}

"#img1": {
    width: 300,
    image: '/header.png',
    width: 300,
    top: 0,
    left: 0
}

file locations (i copied the same image to 3 different locations to try and get something):

app/assets/header.png
app/assets/android/header.png
app/assets/android/images/header.png

IMPORTANT, What I have tried:

using "/images/header.png
using "images/header.png"
using "header.png"
using "/header.png"
Comment: forgot to meantion, the result of executing this is always the white background with my "hello world" label and thats it.
Comment: Have you tried a different image?
Comment: @Shawn good question. Yes I have attempted to use 3 or 4 different images. all of which I have put into the project. I also went out to google and picked a stock png image to try to see if it was me or something. This also didn't work. I have also tried using Ti.FileSystem.getFile to make sure my path is correct, but I'm looking at seeing all my images in the "resources" build folder so I don't think I'm having pathing issues. I also drew a border around the image to see where it would be on the app and I see a border but no image.
Answer: First thing, in the ImageView property you have mentioned the width twice, so you can remove one declaration and put the height of the image, like 300 (you can put Ti.UI.SIZE to maintain the aspect ratio)
Second, put the images inside app/asset/android/images/res-<density> respectively. Replace <density> with for example mdpi / hdpi / xhdpi. (you can put this in res-hdpi for testing)
Do a clean build and then check if it is getting reflected or not.
Comment: Change the TSS to this ==> /images/header_new.png. Remove the portion res-long-land-hdpi. For the moment, I would suggest you to keep the header_new.png inside res-hdpi folder too, just for fallback scenario. The folder is not present by looking in the screenshot, so create one named res-hdpi in the same level where the res-long-land-hdpi is present.
Comment: Also in the screenshot I am seeing View and Label defined in TSS. Can you remove those.
Comment: got this error when I added to res-long-land-hdpi:

Failed to package application:
[ERROR] :
[ERROR] :  libpng error: CgBI: unhandled critical chunk
[ERROR] :  ERROR: Failure processing PNG image /Users/michael.kellogg/Documents/Appcelerator_Studio_Workspace/AndroidStyleTester/build/android/res/drawable-long-land-hdpi/header_271184a1ea.png.....

so I exported the image as .png (some people said re-save in ms paint but im on a mac). The application successfully built this time, but with the same results as shown in this image:
http://s12.postimg.org/ssui2h2cd/image_error.png
Comment: Dude! it worked!! What kinda weird shifty solution was this? haha. I'm going to do some more testing to narrow down what exactly the solution was. I've started by deleting the image from the res-hdpi folder. I think that may have been the key. If it breaks I'll try deleting the image from any other folder and see if it still works with just that one. Thank you so much
Comment: That is good news indeed. Incase you want to understand as to how it works and what is the mapping all about, do let me know, we can discuss.
Comment: how would we discuss it? Also, in your projects do you just have all your images in the res-hdpi folder or something?
Comment: You share your git repro link so that we can discuss there. In my projects I have 4 different set of images for different device densities, mdpi, hdpi, xhdpi, xxhdpi.
Comment: do you replicate all your project images 4 times and put 1 set in each of those 4 folders?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/104667/discussion-between-mike-kellogg-and-soumya).
Comment: could you please edit your answer to reflect that the solution was placing my images in the res-hdpi folder (that i had to create) and using this type of path "/images/filename.png"?
Answer: Very Simple!
Alloy example:
Put your image at app/assets/images for example app/assets/images/header.png .
Now your code is
   <ImageView id='img1' image='/images/header.png'  ></ImageView>

Or in .tss file
"#img1": {
    width: 300,
    image: '/images/header.png',
    width: 300,
    top: 0,
    left: 0
}

End !
Comment: I added an "images" folder under app/assets/ but this did not work. be my witness sir. you can see the file location in the bottom left and my results from this image:
http://s21.postimg.org/j1tbfl3o7/image_error.png
Comment: this seems like such a simple thing that doesn't work at all for me. Is my android configuration like all wrong or something? Did I accidently download a chinese knock-off of appcelerator?? lol
Answer: put your image :
app/assets/images/header.png
then access it with
<ImageView id='img1' image="/images/header.png"></ImageView>

important : try to clean your project first for every changes you made at assets folder before you run the app!
Comment: @Fokke-Appcelerator I've seen these answers all over stackoverflow and it frustrated me greatly. I'm not sure if there is some major difference in my configuration compared to others or something, but this doesn't work and has NEVER worked for me. I spent an entire day trying to resolve this. The ONLY thing that worked for me, was creating a "res-hdpi" folder "assets->android->images->res-hdpi. when i put my images in this then it worked. This also doesn't seem to be documented in Titanium anywhere. always the same simple answer that didn't help.
Comment: @MikeKellogg Could you create a JIRA ticket with an attached Titanium project, the Titanium SDK version, Android Build Tools and API level you build with and the log of your build process? If you drop the link here, I'd love to dive in and solve this frustrating oddity for you.
Comment: @Fokke-Appcelerator https://jira.appcelerator.org/browse/AC-710

Titanium SDK Version: 5.2.0.GA
Android SDK: 5.0.1, API build 21
google nexus 10
Comment: Thanks Mike, let's discuss it further there.


Launching Lightning from command line?

Question: Is there a command that allows me to launch Thunderbird's Lightning from command line? I want to add a command to the Thunderbird launcher that allows me to open to a Lightning page.
Comment: This lack of command-line to start lightning rise up a real integration problem. If I get an "invitation" (or a .ics file) by another way that mail client (Browser for instance), I can't tell "open with". I must save the file, open TB, go to the calendar and open the saved file. A really big regression ! As a consequence, in Ubuntu, the default calendar system is Evolution when the default mail system is Thunderbird. Rather incoherent ..
Answer: There is currently no way, at least not a known easy way, to start lightning directly from command line. There is a bug tracking here: https://bugzilla.mozilla.org/show_bug.cgi?id=359807
You can add yourself to the CC list (as what i did) to get updated about this feature request.
Sunbird is the standalone calendar, but it has been discontinued by Mozilla, so I cannot recommend it for you.
Comment: I figured it'd be worth a shot. Well, thanks anyways fossilet! :)

Launching Lightning from command line?


What is the basic use of calling the private function inside the public function?

Question: What is the perpose of calling privateMethod from the publicMethod?
Can't we just define the content of privateMethod inside the public method and do the same thing ?
var basketModule =  (function() {

      var basket = [];

  function privateMethod() {
      console.log(basket);
  }

  return {
      publicMethod: function(){
              privateMethod();
      }
  };

})());
basketModule.publicMethod();

Comment: If you define it inside the public method then you are recreating the private method every time.
Comment: The example you have is contrived. If you were to write something exactly like that then yes, there'd be no reason to have a private function. But usually you have private functions for performing other kinds of work that the outside world shouldn't care about.
Comment: When you want to do some property updation tasks may be;
Answer: In your simple example, there is not really a reason for privateMethod to exist because all publicMethod does is call it, but in a more real-world example, the private methods would do things that you don't want other modules calling on their own.
For example, this is a snippet of code that I worked on today, reduced to make it a good example:
(function(){

  function _renderTreeLevel() { ... }

  function _backfillAllSelectedStates() { ... }

  function _updateSelectedCount() { ... }

  return {
    render: function() {
      var expandCollapse = new ExpandCollapse();
      expandCollapse.render();

      _renderTreeLevel(0, this.ui.treeRegion, this.treeData);
      _backfillAllSelectedStates();
      _updateSelectedCount((this.options.selected || []).length);

      $('.collapse').collapse();
    }
 };

})();

The 3 "private" function that start with '_' are just functions that I put code into for refactoring and making the code cleaner and more reusable. They are not functions that I want someone to be able to call.
Users of this module should call render() only.
The reasoning is the same as any other language that has public and private members built-in, like C# or Java, but since JavaScript doesn't provide that concept, this is the pattern that people follow to provide a similar behavior.


Android Browser Issue with jQuery Ajax and when appcache is used

Question: we are having a problem with the built in browser on Android 4.0, 4.1 and 4.2 (we haven't got anything lower to test on).
The problem is that the ajax call will work perfectly on first load, you can press the run Ajax button as many times as you like and it will be fine. You can disconnect from the internet and it will work properly.
But if you exit (FULLY, make sure its not just running in the background) the browser then relaunch it, it will fail on load and on button press.  It doesn't matter if you are on-line or off-line.
The error that is been returned from the ajax call is "Error" with status = 0 and readyState = 0.
When its successful you get a message back says "respose from Ajax Call" with a status = 200 and a readyState = 4.
The code works find on every other browser we have tested on Android Chrome, Firefox and Opera. on IOS 5 and 6 it works and every desktop browser we can find.
Is there something that I missing or have we found a bug in the built in browser.  Any help on this would be appreciate especially if it just something stupid I have done.
We have created a test script that demonstrates this problem well I have attached it to the bottom of this message.
Thanks
Tim
test.php
<?php
function displayPage() {
?>
<!DOCTYPE html>

        <meta name="viewport" content="width=device-width, initial-scale=1" >
        <title>test</title>

        <button Name="Run Ajax" onclick="runAjaxGet();">Run Ajax</button>

<?php
}

function processRequests() {
    header("Content-Type: application/json; charset=UTF-8" );
    echo (json_encode("respose from Ajax Call"));
}

date_default_timezone_set ( "UTC" );

if (isset($_REQUEST['test'])) {
    $which = $_REQUEST['test'];
} else {
    $which = '';
}

switch ($which) {
    case "test":
        processRequests();
        break;

    default :
        displayPage();
        break;
}
?>

test.manifest
 CACHE MANIFEST
 test.php
 jquery-1.9.0.min.js
 test.php?test=test

Answer: Just add NETWORK section with asterisk and it will work
 CACHE MANIFEST
 test.php
 jquery-1.9.0.min.js
 test.php?test=test
 NETWORK:
 *

Answer: I hit this same problem and determined that when retrieved from the cache, 0 indicates success. This is likely because there is no actual http request involved since the request is resolved entirely locally.
Appcache manifest file:
CACHE MANIFEST

CACHE:
/config

Javascript:
var request = new XMLHttpRequest();
request.open('GET', '/config', false); // async=false is ok because this file will always come from AppCache
request.send(null);

// Older versions of android return 0 when ajax request retrieved from appcache
if (request.status == 200 || request.status == 0) {
  return JSON.parse(request.responseText);
} else {
  console.log("ERROR: config not retrievable");
  throw "Attempt to retrieve config return http status " + request.status;
}


Why does printing parent node of a node returns parent + child nodes?

Question: Given a start position, I can find a node by passing it to org.eclipse.jdt.core.dom.NodeFinder class.
NodeFinder node = new NodeFinder(root, m.getSourceStart(), m.getSourceEnd() - m.getSourceStart() + 1);
ASTNode n = node.getCoveredNode();

Let assume that this node has a parent and get the node's parent n.getParent(); does anyone know why it prints out the parent node and the node?
For instance we know the starting point of foo() in bar.foo() so if I do System.Out.Println(n.getParent().toString()); it prints bar.foo(). Shouldn't it print only bar?
Thanks in advance for your insight.
Answer: The behavior you are seeing is expected.
In this example:
foo.bar

bar is a SimpleName and its parent is a QualifiedName that contains both foo and bar.  So the parent node will contain more than one AST node and calling toString on it will print out all of this node's children.
Comment: Ok thanks. So is there a way to access the qualified name by itself?
Comment: The qualified name is "foo.bar".  I think you are asking to access only "foo", when you are given "bar".  The answer is yes.  If you start with "bar", you need to get its parent, which is of type QualifiedName.  Then you need to call "getQualifier()" on it.  You will need to call this recursively to handle the case of "foo.bar.baz.bop".
Comment: Thank you for your insight. The getQualifier was really helpful:
ASTNode n = node.getCoveredNode().getParent();
if (n instanceof Expression) {
    Expression exp = (Expression) n;
    if (exp instanceof MethodInvocation) {
        MethodInvocation m = (MethodInvocation) exp;
        System.out.println(Signature.getQualifier(m.toString()));
    }}


Centralized multi-account patching with AWS Systems Manager Automation using Terraform

Question: I am trying to patch and manage the execution of AWS SSM document  from my root account. I am trying to do automation using Terraform version 12. But I dont see the support of multi account in their document.
I am trying to set up this:
https://aws.amazon.com/blogs/mt/centralized-multi-account-and-multi-region-patching-with-aws-systems-manager-automation/
Could someone please help which resource to use
Answer: In order to use the automation document for deploying patches to multiple accounts, we need to ensure the below four steps are accomplished:
<code>1. Create a Resource Group
2. Create an IAM Role for Master Account and an IAM Role for Target(s) account.
3. Create a Document
4. Execute the Automation Document.
</code>
We will be able to create the Resource group using aws_resourcegroups_group [1]. While we can create the IAM roles for both accounts using the aws_iam_role resource [2], we will be able to create the automation document using aws_ssm_document [3]. However, the arguments which need to be specified for executing the automation document by specifying the option for multiple account support aren't available publicly.


Number of real eigenvalues of a matrix function with constant rank.

Question: For each fixed $t\in [0,1]$, let $A(t)$ be a real matrix, so its eigenvalues are always real or conjugate pairs. Assume the entries of $A(t)$ are continuous functions of $t$. Suppose that the rank of $A(t)$ is constant with respect to $t$. Is it true that the number of real eigenvalues of $A(t)$ is also constant with respect to $t$?
My intuition is that, since the eigenvalues are continuous functions of $t$, the only way for the number of real eigenvalues to change is that one real eigenvalue "splits" into a conjugate pair. But this would change the rank so that can't happen. Is this intuition correct?
Answer: The rank of a square matrix isn't connected to the number of distinct eigenvalues. Rank is connected directly to the multiplicity of $0$ as eigenvalue. And two complex conjugate eigenvalues can go together into one (multiple) real eigenvalue without being $0$.
As an example, consider the matrix which rotates the plane $t$ radians:
$$
A(t)=\begin{bmatrix}\cos t&-\sin t\\\sin t&\cos t\end{bmatrix}
$$
For $t=0$, there is only the eigenvalue $1$. For any other $t\in(0,1]$, the two eigenvalues of $A(t)$ are $\cos t\pm i\sin t$. It always has rank $2$.


Building Packages success in My Machine but fails on Launchpad PPA

Question: I'm trying to build budgie-desktop debian packages and upload it to my launchpad ppa.
Building Packages success in My Machine but fails on Launchpad PPA(with the following errors)
make[2]: Entering directory `/build/buildd/budgie-desktop-2.0/session'
Makefile:516: ../data/.deps/budgie_session_dialog-budgie-session-dialog-resources.Po: No such file or directory
make[2]: *** No rule to make target `../data/.deps/budgie_session_dialog-budgie-session-dialog-resources.Po'.  Stop.
make[2]: Leaving directory `/build/buildd/budgie-desktop-2.0/session'
make[1]: *** [distclean-recursive] Error 1
make[1]: Leaving directory `/build/buildd/budgie-desktop-2.0'
dh_auto_clean: make -j1 distclean returned exit code 2
make: *** [clean] Error 2
dpkg-buildpackage: error: /usr/bin/fakeroot debian/rules clean gave error exit status 2

You can check out the full log in the following build status
[Build Status]
amd64 build :
https://launchpad.net/~sukso96100/+archive/budgie-desktop/+build/5924020
i386 build :
https://launchpad.net/~sukso96100/+archive/budgie-desktop/+build/5924021
What should i do to solve this problem?
Answer: By default, the clean target is run first, and then the build and install (or binary, I'm not sure which) are run. In your clean target, you are calling rm -rf ../data/.deps ./.deps applets/.deps common/.deps, which removes the ../data/.deps folder, and so it can't find ../data/.deps/budgie_session_dialog-budgie-session-dialog-resources.Po.
Running debuild before uploading to a PPA can help find these types of errors.


Live USB and Windows - Using Chroot

Question: On Linux you can use the commands below on a Ubuntu live USB to get root access onto the hard drive. Does anyone know if this method works for a Windows hard drive? My guess is that it should, but I've not tried it.
<code>sudo mount /dev/sda1 /mnt
sudo chroot /mnt
</code>
Comment: Possible duplicate of [How do I access an NTFS storage partition?](http://askubuntu.com/questions/35325/how-do-i-access-an-ntfs-storage-partition)
Comment: You dont gain root access to a disk drive - you gain root priviliges to the operating system. As long as the disks are not encrypted you can access all data on all disk as long as you have operting system root priviliges.
Answer: Yes this should work, providing that the windows hard drive is called sda1.
Comment: Well I tried it and I got the error below. Weirdly enough I could just mount the drive onto /mnt and then cd into it. It kinda makes me question what the purpose of using chroot is. It's very confusing. My guess is that code is not executed on the drive, it would be executed on the live USB. It makes me wonder if it's possible to just execute a file on the drive instead?

    chroot: failed to run command /bin/bash

Live USB and Windows - Using Chroot


Convergence of $\sum\limits_{n=1}^{\infty}\frac{\cos{nx}}{n^p}$

Question: Using the $p-$ test $\Rightarrow \sum\limits_{n=1}^{\infty}\frac{1}{n^p}$ is convergent for $p>1$.
Using the comparison test $\Rightarrow$ $$a_n=\frac{\cos{nx}}{n^p},b_n=\frac{1}{n^p}$$
then $a_n$ is convergent if $p>1$ and divergent if $p\le 1$.
Is this the only necessary condition for convergence of $a_n$?
Comment: You can't use comparison test for sequences which aren't everywhere positive, so this doesn't work for $x$ not a multiple of $\pi$. Dirichlet test might be of help here.
Comment: Then you should follow @Wojowu hint, as you don't neccesarily have strict positive $a_n$.
Comment: Do you know anything about $x$?
Comment: @Hirshy  $x\in\mathbb{R}$.
Comment: Notice that when $p>1$, you can show that the series converges absolutely using the Comparison Test.
Comment: If $x=\pi$, for $p=1$ we have the series $-1+1/2-1/3+1/4-1/5+\dotsb$; this is convergent, so your claim about divergence when $p\le1$ is wrong.
Answer: Since
$$
\sum_{n=1}^\infty \left|\frac{\cos nx}{n^p} \right| \leq  \sum_{n=1}^\infty \frac{1}{n^p},
$$
$\displaystyle \sum_{n=1}^\infty \frac{\cos nx}{n^p} $ is absolutely convergent for $p>1$, and hence convergent for $p>1.$


Can a Japanese "Pokemon Gold" Virtual console game be downloaded to an American 3DS/2DS?

Question: As the title states. Is it possible to use a Japanese VC download code on an American new 2DS XL?
I recently bought all Japanese "boxed" releases since they were cheap but  didn't realize there may be a region lock.
Answer: Games are region locked, you will need a code for the region that your 3DS/2DS is from in order to download it.  In other words you'll need a Japanese console to play the region locked Japanese games.
It's the same principle for Pokemon event codes in later games.


If $\phi$ is $\Delta^{0}_{1}$ in the language of arithmetic, does Heyting Arithmetic prove $\forall x [\phi (x) \vee \neg \phi (x)]$?

Question: PA is conservative over HA for $\Pi^{0}_{2}$ sentences. If $\phi$ is $\Delta^{0}_{1}$, then $\forall x [\phi (x) \vee \neg \phi (x)]$ is equivalent to a $\Pi^{0}_{2}$ sentence. Since PA trivially proves that sentence in the language of arithmetic, oughtn't HA to too? What am I missing?
(The usual counterexample offered for $\Pi^{0}_{3}$ sentneces is an instance of the same applied to $\phi$ of $\Sigma^{0}_{2}$ complexity, which made me think...)
Comment: Are you sure about "$\mathsf {PA}$ is conservative over $\mathsf {HA}$ for $\Pi^{0}_{2}$ sentences" ? See Anne Troelstra & Dirk van Dalen, *Constructivism in mathematics An Introduction* (1988), page 128 : "*Proposition* (ii) For $A$ not containing $\lor$ or $\exists$ : $\mathsf {HA} \vdash A$ iff $\mathsf {PA} \vdash A$. [...] The proposition does not cover theorems of the
form $\forall x \exists y A(x, y)$, $A$ quantifier-free (i.e. theorem in $\Pi^{0}_{2}$-form)."
Comment: That's interesting and confusing in equal measure. I'm currently trying to get my head round G\o"del's D-interpretation. A consequence of that, as expounded in Feferman/Avigad (1998) can be found on p. 18 (found on Feferman's website): {\bf Corollary 3.2.5: PA and HA + Markov's principle are conservative over HA for $\Pi^{0}_{2}$ sentences. The proof uses the fact that the functional interpretation proves the $\Pi_{2}$ sentences of PA and can be formalized in HA. Be interested to know why the apparant inconsistency! Thanks for your response
Comment: But what is $\phi(x)$ ? It is of the form $\exists y \psi(x,y)$ ? If so, are we sure that $∀x[ϕ(x) \lor \lnot ϕ(x)]$ i.e.  $∀x[\exists y \psi(x,y) \lor \lnot \exists y \psi(x,y)]$ i.e. $∀x[\exists y \psi(x,y) \lor \forall y \lnot \psi(x,y)]$ is of the "right form" ?
Comment: good question. It might very well turn on intuitionistic logic not proving the required equivalence. I was thinking that since $\phi (x) \leftrightarrow \exists (y) \psi (x,y)$ and $\neg \phi(x) \leftrightarrow \neg \forall z \theta (x,z) \leftrightarrow \exists z \neg \theta (x,z)$ in PA, we can write $\forall x [\phi (x) \vee \neg \phi (x)]$ as $\forall x \exists y,z[ \psi (x,y) \vee \neg \theta (x,z)]$ which is provable in PA (and ex hypothesi in HA). Does HA get us back to the original formula though? The directions of equivalence we need seem intuitionisitcally valid....
Comment: @chris scambler: it is acceptable to delete comments if you no longer think they are useful. I wrote up an argument in an answer that I think answers your question. Could you let me know if it does? One thing that does seem to be a sensitive issue is to represent the "$\Delta^0_1$" nature of the formula correctly, because of course there will be limited ability to handle negations in HA. But if we make the correct assumption, (*) in my answer, then it seems there is no issue.
Answer: If $\phi(x,y)$ and $\psi(x,y)$ are quantifier free formulas of PA such that
$$
\text{HA} \vdash (\forall x)[(\exists z)\phi(x,z) \leftrightarrow \lnot (\exists y)\psi(x,y)] \qquad (*)
$$
then in HA we can prove the following sequence of formulas are all pairwise equivalent:
$$
\begin{split}
&(\forall x)[(\exists y)\psi(x,y) \lor \lnot (\exists y)\psi(x,y)] \\
&(\forall x)[(\exists y)\psi(x,y) \lor (\exists z)\phi(x,z)] \qquad\qquad(\dagger)\\
&(\forall x)(\exists y)(\exists z)[\psi(x,y)\lor \phi(x,z)]
\end{split}
$$
The equivalence of the first two is by assumption. The equivalence of the second and third can be checked (among other ways) by verifying that the equivalence holds in every Kripke model.
Using the standard number theoretic method to combine existential number quantifiers, which can be formalized in HA, the last formula in the list above is equivalent over HA (and thus also over PA) to a formula of the form
$$
(\forall x)(\exists x)\theta(x,w)
$$
where $\theta$ is $\Delta^0_0$, that is, $\theta$ has only bounded quantifiers.
Therefore, by the result that PA is conservative over HA for $\Pi^0_2$ sentences of PA, we have that
$$
\text{PA} \vdash (\forall x)[(\exists y)\psi(x,y) \lor \lnot (\exists z)\psi(x,z)]
$$
if and only if
$$
\text{HA} \vdash (\forall x)[(\exists y)\psi(x,y) \lor \lnot (\exists z)\psi(x,z)]
$$
as long as (*) above holds for $\psi$.
The limitation in this result is that we assumed (*) above at the beginning, and in particular that $\phi$ and $\psi$ are quantifier-free (we could take them to be $\Delta^0_0$ as well).
Comment: Thus, it is right to say that your (*) does not "violate" the principle that $\forall x[\varphi(x) \lor \lnot \varphi(x)]$ is **not** (in general) intuitionistically acceptable ?
Comment: @Mauro ALLEGRANZA: the assumption is that (*) is provable in HA; the result doesn't apply otherwise. For example, if $\phi$ in the language of PA has no quantifiers at all then the formula in your comment is always provable in HA.
Comment: @chris scambler: there is an issue whether the subformula being quantified over is a bounded quantifier formula (which is what Avigad and Feferman call $\Delta^0_0$) or whether it's genuinely quantifier free.
Comment: @Carl Mummert: Thanks very much for your detailed response !! I take it (*) does not in general follow from $\phi$ being $\Delta^{0}_{1}$ in HA due to the failure of classical quantifier equivalences (specifically between a universal and a doubly negated existential)? Also, are you confirming PA's conservativity over HA? Was that a recent(ish) discovery, post 88? Thanks again, C
Comment: @carl: Excellent thanks for the second comment... so the result goes through only with $\Delta^{0}_{1}$ formulas which quantify over formulas with no qfiers at all?
Comment: @chris scambler: there's no such thing as a "$\Delta^0_1$ formula"; the arithmetical hierarchy for formulas does not include any $\Delta$ class except $\Delta^0_0$. What (`*`) says is that a certain *definable set* is $\Delta^0_1$ - namely, $\{z : (\exists x)\phi(x,z)\}$. But it's true there are various ways that the definition of a "$\Delta^0_1$ definable set" could be phrased, that would be classically equivalent through the manipulation of negations, which may not be equivalent in constructive logic. In (*) I could have let $\phi$ and $\psi$ be $\Delta^0_0$, and the argument goes through.
Comment: And none of this is new, since it is all just an application of Goedel's method.
Comment: Sorry about this, but now I'm a little confused: what is the issue concerning the subformula being qfier free/ containing bounded qfiers? Thanks for clearing up the formula/set thing, This stuff is all very new for me, as you can prob. tell.
Comment: @chrisscambler - I think that if the $\phi$ in your formula is *quantifier free* (or with *bounded quantifiers*) the formula is *decidable* (e.g. $x=5 \lor \lnot x=5$ is "checkable" in a finite number of steps, so it is provable in $\mathsf {HA}$). But there are *counterexample* to the "general case"; see AS Troelstra & D.van Dalen; *Constructivism in mathematics* (1988), page 13: whit $\forall n (A(n) \lor \lnot A(n))$, with $A(n)$ decidable but such that $\forall n A(n)$ is unknown, "At the time of [the book] we might take 'Fermat's last theorem' as an example of such $A$".
Comment: @Mauro ALLEGRANZA: I don't think that example, in particular, is a counterexample to what we are trying to prove. Could you explain? I mean, PA proves that each $n$ either is or is not a counterexample to Con(PA), but PA doesn't prove Con(PA). So the issue does not seem related to constructive logic.
Comment: @CarlMummert - I'm referring to *Weak counterexamples* in [Intuitionism in the Philosophy of Mathematics](http://plato.stanford.edu/entries/intuitionism/); apart from the reference to the "supersed" Fermat's last theorem, I think that an Intuitionist can cook up a new example of "$A(n)$ decidable property for which $∀nA(n)$ is not known to be true or false." I'm trying to understand why in this case the above result does not apply : because the $\phi(x)$ is of the form $\forall y A(n,y)$ and not $\exists y \psi(x,y)$ ?
Comment: @Mauro ALLEGRANZA: which result in particular are you claiming does not apply? My answer above does not claim that some general formula of the form $(\forall n)A(n)$ is provable.  In fact, for weak counterexample, we usually do *not* have a proof of $(\forall n)A(n)$.
Comment: @CarlMummert - this is exactly what I'm not still grasping. What is the "stricter" condition in your formula that escape from the intuitionistic critique ?
Comment: @Mauro ALLEGRANZA: it is true that some constructive systems do not prove every instance of the scheme $(\forall n)(A(n) \lor \lnot A(n))$. Usually, a predicate $A$ for which that is provable is called "decidable" (using the same word as computability but with a different meaning).  The point of the question is that, in HA, certain instances of that scheme are provable. For example, HA proves that each $\Delta^0_0$ set of natural numbers is decidable.
Comment: @CarlMummert - Ok thanks!


How do I identify drywall that does not have fiberglass to add strength?

Question: I know from long experience that drywall often (always?) has glass fibers (fiberglass) mixed in with the Gypsum to add strength.  Because of the number of drywall related products that have fiberglass in them, I am having trouble finding good references.
I did find Possible Environmental Concerns with Recycling Gypsum Drywall which says Type X drywall has fiberglass in it. The article also says older drywall may have Asbestos and/or Mercury.
Looking for reliable references that indicate how I can tell that a drywall product only has Gypsum between the paper, or at the very least how to reliably identify drywall that has fiberglass or other hazardous additives.
Answer: Your best source for information about drywall, is going to be the manufacturers.
USG
National Gypsum
Georgia Pacific
CertainTeed
Comment: Actually it does not look like the manufacturers are a good resource [Example Type X](http://www.certainteed.com/products/gypsum/board/standard-gypsum-board/313675) If they call out the presence of fiberglass in their drywall product it is so well hidden that I did not find it.
Answer: Fiberglass is visible in the drywall when you cut the paper face and snap it back. Instead of just the rough powdery plaster, you will see what looks like a fuzzy surface that's the bits of fiberglass that were embedded in the two halves. Type X drywall is used for fire rated applications, which are typically garages, common walls in a multi-dwelling structure, and occasionally around a utility room. A simple way to tell the difference between Type X and other drywall is to measure the thickness, type X will typically be 5/8" thick while other drywall is 1/2" or thinner.
For the hazardous materials you listed, I would check the age of the home or determine the date it was last renovated. And if hazardous materials were used then, have anything suspicious tested.
Comment: [SHEETROCK® Brand FIRECODE® C Core Gypsum Panels](http://www.usg.com/content/usgcom/en/products-solutions/products/interior-panels/panels-&-drywall/sheetrockbrandfirecodeccoregypsumpanels.html) come in 1/2 in. sheets, and I believe they also contain fiberglass (or at least the [MSDS](http://www.usg.com/content/dam/USG_Marketing_Communications/united_states/product_promotional_materials/finished_assets/sheetrock-firecode-c-core-gypsum-panels-msds-en-54020001.pdf) lists *Fibrous Glass*.
Comment: Rules of thumb always seem to have a pesky exception.


As-You-Type-Searching with Core Data / NSFetchedResultsController

Question: I implemented an as-you-type-searching (text search on single attribute) by fetching with performFetch: after each given character by the user. The performFetch: is running in a background thread to avoid keyboard freezes.
But while typing many useless fetches are started. A NSOperationQueue might be an option, but I wonder if there are other approaches for this quite usual search behavior.
What's best practice to notice when fetching is done and the table view is updated with the previous fetch to start a new fetch?
Answer: You don't need to perform a fetch on the Core Data stack after each letter.  You can instead run a NSPredicate against the fetchedObjects that are already in the NSFetchedResultsController instance.  This will remove the need to perform fetches on a background thread because you are simply filtering against the results that are already in memory and it will remove the performance issue.
As each letter is typed you adjust the NSPredcate and the results are filtered further.
Comment: Thanks, I'll try the approach running a NSPredicate on `fetchedObjects`.
Comment: If a delete is detected then the predicate starts over yes.


Hot water heater causing buzzing/grinding sound in circuit breaker panel

Question: I just installed an AO Smith 50 gallon hot water heater in my basement in May of 2021. It has been working great for the past half year or so. Today, I found that I only had luke warm water for my shower. I went to my hot water heater and I did not hear it heating the water in the tank.
I flipped the hot water heater circuit off and on and it still did not heat the water. I then turned the circuit off, took the panel off the hot water heater and hit the reset button. I then flipped the circuit back on and it started to heat the water in the tank. After about a minute of the water being heated, I noticed a very loud grinding/buzzing sound that was coming from my circuit breaker panel. I quickly shut off the circuit and the buzzing immediately stopped.
I checked to see if the wiring was secure in the water heater. I found that it was. I then turned the circuit breaker back on and again it was fine for about a minute and then I heard the loud buzzing sound coming from the circuit breaker again so I shut it off.
I was looking for advice to see if this might be an issue with the hot water heater, or would it be an issue with my circuit breaker panel. I have never heard this buzzing sound on my circuit before today with my old or current water heater. It appears that my water heater is under warranty but did not want to go through the hassle of installing a new one again if that was not what was causing the issue.
Below is a link to google photos showing a video that I took of the grinding sound.
https://photos.app.goo.gl/fEpACVsLGbeVNHEk8
Update 1/5/22
I just replaced the circuit breaker and I will be replacing the thermostat tomorrow. I found that the top of my hot water heater is hot but the bottom is ice cold. I used a multimeter and found that there was no continuity in the bottom heating element. Is that always indicative of a failed heating element and if so, does that mean that my thermostat is probably fine?
Update 1/6/22
I just replaced the top thermostat and the bottom heating element. I think I found the true issue now. The bottom heating element is heating now. The issue is the the bottom heating element is not shutting off. I have the bottom thermostat set to 120 degrees F. When I used an infrared thermometer, I found that the tank next to the heating element is already up to 150 and the water coming out the top is 160. Far above what I set it to.
Would I just need to replace the bottom thermostat and I should be good? How would I make sure the thermostat isn't grounded with a multimeter? I highly doubt this would be an issue since this water heater is less than a year old but I wanted to make sure.
Comment: Buzzing sound from your  panel could mean that a breaker is failing or even sparking. Can you take the cover off the panel and inspect the inside?
Comment: What brand breaker/breaker panel? How old? It's very unusual for a breaker to make that sound.  Most likely a defective/failing breaker.
Comment: Well you tell your friend that *I* think the thermostat is the one electric component in the circuit that is *not* suspect.
Comment: I see several possibilities. First check the breaker rating and be sure it is properly rated for the heater. Some of the older magnetic breakers buzzed when the load was close to there capacity. Replacing the breaker would solve that. It is also possible you have an element that has corroded and is leaking current to ground through the water. This would cause a rise in current. Use a clamp meter and measure the current in each phase and see if it is stable and in rating.
Comment: @JustinTodd -- yeah, that means your bottom heating element is dead as a doornail, probably burned itself out due to excessive sediment
Comment: @JustinTodd -- generally, replacing the heating element itself will fix problems with a heating element "going to ground" as that's caused by moisture contaminating the insulation inside the calrod
Comment: It appears as though I have a lc040pc combo breaker panel. I would assume it is as old as my house which was built in 1988.
 https://photos.app.goo.gl/nHvDW9F8jcH8sYvX9
Comment: Can you get us good quality photos of the panel, including the label on the inside of the door please?
Comment: The link to my previous comment in the photos app is a picture of the inside of my breaker panel. My friend seems to think that it is a faulty thermostat on my hot water heater and that the thermostat should be replaced
Comment: So I just replaced the circuit breaker and I will be replacing the thermostat tomorrow. I found that the top of my hot water heater is hot but the bottom is ice cold. I used a multimeter and found that there was no continuity in the bottom heating element. Is that always indicative of a failed heating element and if so, does that mean that my thermostat is probably fine?
Comment: @ThreePhaseEel So I just replaced the top thermostat and the bottom heating element. I think I found the true issue now. The bottom heating element is not shutting off. I have the bottom thermostat set to 120 degrees F. When I used an infrared thermometer, I found that the tank next to the heating element is already up to 150 and the water coming out the top is 160. Far above what I set it to. So I believe I just need to replace the bottom thermostat and I should be good?
Comment: @JustinTodd yeah -- that'd kill the bottom heating element, so you need to swap the bottom t-stat
Comment: @ThreePhaseEel And if that didn't fix it, would that mean that my heating element is somehow grounded and I would be better off insisting for a new water heater under warranty?
Comment: @ThreePhaseEel replaced the bottom thermostat and it is now working!
Comment: Post your updates as an answer and I'll give you a +1 for it then
Answer: Replaced the buzzing circuit breaker and then also the upper and lower thermostat and burnt out lower heating element which fixed the issue!


How to change navigationState in material tabs react hooks?

Question: Basically, I want to re-render my tab navigator item on state change but it will not re-render, even if the state changes, unless navigationState changes. So, my question is: How can I force my tab navigator to change navigationState when my state updated?
Here is my code:
const [isShow, setIsShow] = useState(false);
useEffect(() => {
    setTimeout(() => {
      AsyncStorage.getItem('user_type').then(response => {
        if (response == 'admin') {
          setIsShow(true)
        }
      })
    }, 5000);
  }, [isShow]);

return (
    <Tab.Navigator>
      <Tab.Screen> ... </Tab.Screen>

  {isShow ? (
   <Tab.Screen> ... </Tab.Screen>
  ) : null}
</Tab.Navigator>

Answer: Try doing it like this
const [isShow, setIsShow] = useState(false);
useEffect(() => {
    setTimeout(() => {
      AsyncStorage.getItem('user_type').then(response => {
        if (response == 'admin') {
          setIsShow(true)
        }
      })
    }, 5000);
  }, []);

return (
    <Tab.Navigator>
      <Tab.Screen> ... </Tab.Screen>

  {isShow ? (
   <Tab.Screen> ... </Tab.Screen>
  ) : null}
</Tab.Navigator>

The second parameter of the useEffect hook is a dependency array. The effect is executed only if a dependency changes. In your case, isShow is initialized with false and stays like this. Specifying an empty array [], means your effect will execute once, when the component is mounted.
Comment: still nothing works
Comment: when I select other tab and then move back to original then i can see the hidden tab
Comment: Do you wait 5 seconds as you have a timeout of 5000 milliseconds? I think that is not necessary. Why don't you try a simple effect like this   ```useEffect(() => {
          setIsShow(true)
  }, []); ```. Then you can figure out the AsyncStorage thing.


The function should return a char from a list of binary, but I get "invalid literal for int() with base 2"

Question: def binToChar(b):

    a=','.join([str(i) for i in b])
    a = int(a, 2)
    if a < 26:
        return chr(ord('A')+a)
    elif a < 52:
        return chr(ord('a')+a-26)
    elif a < 62:
        return chr(ord('0')+a -52)
    else:
        if a == 62 :
            return "+"
        if a == 63:
            return "/"

print(binToChar([1,0,1,0,1,0]))

Traceback (most recent call last):
File "C:/Users/PycharmProjects/assignment1/venv/tester.py", line 46, in
print(binToChar([1,0,1,0,1,0]))
File "C:/Users/PycharmProjects/assignment1/venv/tester.py", line 23, in binToChar
a = int(a, 2)
ValueError: invalid literal for int() with base 2: '1,0,1,0,1,0'
Comment: Why are you stitching the stringified zeroes and ones together with `,`? Seems like you just want `''.join`, not `','.join`.
Comment: What are you trying to do? What type is the parameter `b`? Given a specific input, what output do you expect?
Answer: The message tells you exactly what is wrong: "1,0,1,0,1,0" is not a valid number in base 2.  You want "101010" instead.
To do that, change
a=','.join([str(i) for i in b])

to
a=''.join([str(i) for i in b])


Vlc won't start

Question: Here's the output I get:
$ vlc
VLC media player 2.2.2 Weatherwax (revision 2.2.2-0-g6259d80)

No error message, no nothing.
After forking at least I can see that it crashed:
[1]  + 25287 exit 1     vlc

Where should I begin investigating? Purging and reinstalling didn't help.
EDIT: I tried purging, reinstalling, deleting configs etc. and no solution to be found on stack exchange/vlc forums/other sites helped. Hence I do not expect here any solution suggestions - I'd be glad if I could see some output from vlc telling me this and that library is missing or cannot open some file because it is read-only.
Comment: You can also try resetting the configs using `vlc --reset-config` then try again.
Comment: After a few tries, I got this: `vlc --verbose=3 --file-logging --logfile=log.txt` Edit your question and include the contents of your log.txt file that will be created in your home folder.
Comment: Nope: `$killall -9 vlc` yields `vlc: no process found`
Comment: How about `cvlc`?
Comment: Nothing changes
Comment: How did you install vlc? And what are you trying to play with it? Did you install 'ubuntu-restricted-extras'? - I use vlc 2.2.2-5 installed from the repositories in 16.04.1 LTS and it works. It prints the same message as yours, when started from a command line, and it works.
Comment: `sudo apt install vlc`
Comment: Nah, that doesn't work. Same with `--reset-config`. ```[~] vlc --verbose=3 --file-logging --logfile=log.txt
VLC media player 2.2.2 Weatherwax (revision 2.2.2-0-g6259d80)
vlc: unknown option or missing mandatory argument `--file-logging'
Try `vlc --help' for more information.
```
Comment: Please tag me @parto so that I can receive notifications
Comment: Looks like your VLC is corrupted. Have run out of ideas. Sorry.
Comment: @Parto: Definitely looks like it is :-) But usually when programs cause problems there is a way to find out what is going on. With `vlc` it seems to be otherwise
Comment: Try looking for vlc log files - maybe they will explain more on the issue.
Comment: @Parto That's the thing - there don't seem to be any logs available anywhere
Comment: @sudous I understand that for others it "just works". The question is where do I search for any information on why it is not working on my machine
Comment: Have you tried uninstalling and VLC (with `sudo apt purge vlc`), and deleting the config folder / files (most likely located in `~/.config/vlc`, you'll need to enable "show hidden files" in the file manager to see that folder, Ctrl + h), and then installing it again ?
Comment: @JonasCz. Yes I have
Comment: Just throwing ideas, but maybe there's a "hanged" VLC process still running on the system. Even if you run `apt-get purge vlc`, the process would still be running. If there were, try killing it then restart or re-install vlc.
Comment: Try installing the [latest version](https://launchpad.net/ubuntu/+source/vlc/2.2.4-11). First purge yours, and download, and install the .deb file with `sudo dpkg -i /path/to/file.deb`, and then run `sudo apt-get -f install`.
Comment: @luchonacho Tried that, same result: https://paste.ubuntu.com/23669524/
Comment: since there is not an answer Im moving to MPV
http://www.omgubuntu.co.uk/2017/02/swap-vlc-mpv-ubuntu
Comment: @LuGo Have you tried to install Vlc 3? https://launchpad.net/~videolan/+archive/ubuntu/master-daily
Comment: @LuGo , Which version of Ubuntu are you running? In what computer (please specify brand name and model of the computer, graphics card/chip, audio card/chip)?
Comment: I got a very good answer to a question of mine this morning, perhaps you can follow the second instructions to see where vlc gets stuck: https://askubuntu.com/a/928667/49482
Comment: `killall -9 vlc`  This command resolved my "VLC won't start issue". It basically kills all the VLC running processes. I think due to some problem in VLC, it is not able to close the running VLC processes. Although, above command resolved my issue, but If anybody figures out why VLC is not able to kill the running processes in the background after closing the VLC, then please let me know.
Comment: tried to refer to https://askubuntu.com/questions/1132800/ubuntu-18-04-wont-open-video-players#comment2288021_1132823
Answer: I had a similar problem. I don't know why but using the vlc-wrapper instead of cvlc or vlc running the program as root through gksudo helped. As so:
gksudo vlc-wrapper

also make sure ffmpeg and other related packages are installed:
sudo apt-get install ffmpeg*

Comment: I can't consider running as `root` a solution
Answer: After a lot of frustration with unmet dependencies, this worked:
sudo add-apt-repository ppa:jonathonf/vlc-3
sudo add-apt-repository ppa:jonathonf/ffmpeg-4
sudo add-apt-repository ppa:jonathonf/meson
sudo apt-get update
sudo apt-get install vlc

Answer: I had the same issue using vlc-bin from apt. The snap version (3.0.6 currently) works for me:
sudo snap install vlc

Comment: Didn't work for me on Ubuntu 18.10. It claimed to have installed VLC 3.0.6, but it must not have set up links correctly, because an older version still executes when I invoke it from the command line. I ended up having to use the Ubuntu GUI installer to do it.
Comment: @Dan did you completely uninstall / purge vlc before snap installing?
Comment: no.  I tried it on a virgin VM and it worked, thanks.

Vlc won't start


Angular navigate to same component from 2 different origins and display some different UI elements depending on navigation origin

Question: I want to be able to navigate to the same component (DetailsComponent) from 2 other different components (Home and CategoryAppsComponent), and change a couple UI elements based on a flag/boolean prop, depending on when the navigation is coming from.
I got it working using the state prop of the Router navigate method like so:
On Home.ts and on CategoryAppsComponent.ts where the navigation happens, respectively:
this.router.navigate(["home", "details", id], { state: { categoryAppsHeader: false } });

this.router.navigate(["home", "details", id], { state: { categoryAppsHeader: true } });

And then on the DetailsComponent.ts I assign the value to a prop which I then use an ngIf on the respective HTML to show or hide the headers:
this.categoryAppsHeader = this.router.getCurrentNavigation().extras.state["categoryAppsHeader"]

This is the solution I found because although DetailsComponent is a direct child of HomeComponent on the routes, CategoryAppsComponent is not, so I can't just pass a property through the HTML.
However this created a problem - when I click on one of the cards of DetailsComponent (please refer to the routes.ts file down below), from either the Home page or the CategoryAppsComponent, and I refresh the page, Angular sends me to the Home page instead, as if the route did not exist (example route could be localhost:4200/home/details/123).
I guess this has to do with the state prop because before I implemented it, I had the refresh working.
The last route down below was me attempting to make it work with the data prop but I was unsuccessful, I left it in because maybe someone knows a solve using it.
routes.ts
export const routes: Route = {
path: `home`,
component: HomeComponent,
children: [
    {
        path: "details/:id",
        component: DetailsComponent,
    },
    {
        path: "categories",
        children: [
            {
                path: "",
                pathMatch: "full",
                component: CategoriesComponent,
            },
            {
                path: ":categoryId/apps",
                component: CategoryAppsComponent,
            },
            {
                path: "apps/:appId",
                component: DetailsComponent,
                data: {
                    categoryAppsHeader: true,
                },
        ],
    },
],};

I am sorry if the explanation is a bit confusing or if I haven't provided enough information, please let me know if you have any doubts about the implementation so that hopefully you can help me out. Any help is appreciated, thank you :)
Comment: Frankly speaking, I got confused by the explanation. A StackBlitz would certainly help.
Answer: Answering for future reference and in case anyone has the same doubt and understands my (bad) explanation up top:
I managed to do what I wanted by fixing the last route as such:
{
    path: ":categoryId/apps/:id",
    component: DetailsComponent,
    data: {
        categoryAppsHeader: true
    }
},

And then on DetailsComponent's constructor accessing the true flag and storing it on a variable like such (and using that boolean on the template):
this.categoryAppsHeader = this.activatedRoute.snapshot.data["categoryAppsHeader"];

P.S: Some bonus info, I managed to implement the "Go back" button by accessing the URL, splitting it into an array and removing the unwanted strings:
this.router.navigate(window.location.pathname.split("/").slice(1, -1))

Thank you


database in restore state

Question: I tired to restore my database but I saw that I am restoring a wrong one, so I immediately kill the process. Unfortunately the database was in restoring state and is not accessible anymore.
Can anyone help me to return back to normal state?
Thanks in advance
Comment: [SQL Server: Database stuck in "Restoring" state](https://stackoverflow.com/questions/520967/sql-server-database-stuck-in-restoring-state) but if you restored with overwrite your unlikely to be able to return to the state prior to the aborted restore (without another restore)
Comment: Possible duplicate of [SQL Server: Database stuck in "Restoring" state](https://stackoverflow.com/questions/520967/sql-server-database-stuck-in-restoring-state)
Answer: Try using the following query to return your database online
RESTORE DATABASE MyDatabase
WITH RECOVERY

If it throws an exception so you need to restore from a latest backup
RESTORE DATABASE MyDatabase
FROM DISK = 'C:\MyDatabase.bak'
WITH REPLACE,RECOVERY

database in restore state


angular-file-upload - how to get URL of uploaded file

Question: Im trying to create a form that a user can select an image and upload as part of the entry.
I have the upload function working. When the user selects the image and presses upload it uploads to the folder on the server.
However what i need to do is somehow get the URL and use it as a parameter in the form.
Button simply calls the upload function
<button class="btn btn-primary" ng-click="uploadProductPicture();">Upload</button>

Client.Controller Method
// Change user profile picture
    $scope.uploadProductPicture = function () {

        // Clear messages
        $scope.success = $scope.error = null;

        // Start upload
        $scope.uploaderProduct.uploadAll();

   };

When the user uploads the file where do i get the URL?
Added server logic
exports.changeProductPicture = function (req, res) {

        fs.writeFile('./modules/deals/client/img/uploads/' + req.files.file.name, req.files.file.buffer, function (uploadError) {
            if (uploadError) {
                return res.status(400).send({
                    message: 'Error occurred while uploading profile picture'
                });
            } else {

                res.json({ file: req.files.file.name });

                // Set variable to file location

            }
        });

};

And Route
  app.route('/api/deals/picture')
  .post(deals.changeProductPicture);

Comment: Use the same server logic that writes the file to directory to return the url
Comment: Im not really sure how. Ive added the function that is called by the route but im fairly sure i have that setup wrong.
Answer: You need to decide how do you serve the image files uploaded in your server at first.
If you use express in your node server, you could use express.static module to serve the images uploaded like a normal static images.
I think the code is something like this.
In node
var upload_image_dir = './modules/deals/client/img/uploads/';

// route setting
app.use('/upload-images', express.static(upload_image_dir));

// image upload handler
exports.changeProductPicture = function (req, res) {

    fs.writeFile(upload_image_dir + req.files.file.name, req.files.file.buffer, function (uploadError) {
        if (uploadError) {
            return res.status(400).send({
                message: 'Error occurred while uploading profile picture'
            });
        } else {
            res.json({ file: req.files.file.name,
                url_image: upload_image_dir + req.files.file.name
            });
        }
    });
};

Now that the client could use the url of image uploaded by extracting the json response.
I hope this example could give you some idea.


Combatting moisture in crawl space after venting window is sprayed with insulation?

Question: I had a crawl space (top left) in my house which had a 12"x6" venting window. There is a room above the crawl space, so I decided to spray the walls of the space with closed-cell foam insulation which also closed off the venting window. The room above the crawl space is now warm in the winter so I'm happy with the insulation.
However, in the summer months, the crawl space (and, as a result, the entire basement) has a big moisture and mold problem. To alleviate the issue, I cut a small hole in the insulation where the venting window used to be and put a small 12V fan in which I leave on at all times. This helped the moisture problem a great deal - I would say that about 75% of the smell is gone.
My question is: what is the best approach to solving the problem completely? A larger fan? Spraying the floor of the crawl space? Something else?
Many thanks in advance!
Answer: When you bring a crawlspace into the building envelope by insulating it like this, you need to treat it like any other room and condition it.
Putting a fan in the wall that exhausts to the exterior defeats the whole point by circulating outside air through the crawlspace--which is now a part of the interior of the house. There's no point in insulating a space that has free air movement between the inside and the outside. The only reason why the fan makes a difference is because it's moving air, which is good. But it's also bringing in outside air which in the summer is humid; you're replacing very humid air with slightly-less-humid air. That's why the problem hasn't completely gone away. If you wouldn't open the windows to dehumidify the rest of your house, you shouldn't do it to your now inside-the-building-envelope crawlspace. Think of your crawlspace as now a room, not a crawlspace. Maybe it's a crawlroom.
Put HVAC supply and return vents in the crawlroom and the problem will disappear. During the summer, your AC unit will circulate air through it just like the fan is currently doing, but also dehumidify it, which is what you're currently missing. This will be much cheaper than running a separate dehumidifier. The very last thing you want to do is run a dehumidifier in a room with a ventilation fan like the one you have rigged up: you'd be trying to dehumidify the whole neighborhood.
Edit: if the floor doesn't have a vapor barrier of some sort, that also needs to be addressed. When you bring a crawlspace into the building envelope, you can't do a half job and forget about the floor. If the floor slab doesn't have insulation or a vapor barrier underneath it, then you need to add one on top of it, and seal it to the foamed walls with more foam.
Comment: resealing the hole in the insulation and leaving the access hatch open (or replacing it with a large grate) should be more than sufficient to get this crawlroom (great term!) inside the HVAC envelope. It doesn't have to be perfectly heated/cooled, just enough airflow to get the air here dried out. which it will do over time.
Answer: The fan is the right idea, but it should probably be a stronger 120v unit. Look at bathroom fans and how they're rated for square footage. Some can be mounted in-wall and may fit your opening well.
Comment: Thanks. Why are you saying that the fan isn't *circulating* air? It's blowing air out the window throw a snug opening - that means that air is entering the crawl space through the door.
Comment: You didn't mention an open door now, did you? :)
Comment: I did not!  But when I do close the doors, I'll make sure they are louvered somehow.
Comment: This is the wrong approach. With the new insulation, the crawlspace is now inside the house. You don't want to bring in a ton of humid outside air in if your problem is excessive humidity.
Comment: Actually, if the humidity level in the crawl space is higher than outside, as it can be due to ground moisture, it is the right approach in the summer months.
Comment: Then there hasn't been enough sealing work. The floor should have been done, too, with a poly vapor barrier at the minimum. If you're going to bring a crawlspace into the building envelope, you can't do a half-job and forget about the floor.
Answer: use a dehumidifier.
The temperature in the crawl space is significantly lower than in the house above, right? This is a common problem with dirt floor cellars/stone foundations that have been insulated, and is easily alleviated by running a dehumidifier in the summer.
The low height of the ceiling makes for a fairly small volume, so it should work very efficiently and quickly. Make sure the fan you currently are using is turned off - with the dehumidified air it will be unnecessary to bring in fresh air from the exterior (and make it impossible to efficiently dehumidify your space!). it can drain to a condensate pump, which you can then plumb to an existing drain or the exterior.
Comment: Of course, that'll use quite a bit of power compared to even a robust fan. I've recently learned that it can cost as much as $20-30 per month or more.
Comment: It can, sure, but that depends on frequency of use. Again, based on the relatively small volume of the space and the fact that it is already partially sealed by foam, I don't think it will be near the $30/month. Also, that is only in summer months. Finally, the fan will not really work on getting moisture down unless you have a place for dry air to enter and wet air to leave. In the summer time, you don't really want hot+wet air to be circulated down into the crawlspace, because it will condense on the relatively cooler surfaces. The only alternative is to heat the crawlspace in the winter :)
Comment: I hesitate to use a dehumidifier since there is no place to drain the water.
Comment: the water from the dehumidifier can drain to a condensate pump which can then be run anywhere convenient for you. the actual volume of water will be very small, so it can safely be dumped even close to your foundation. Alternatively, it could be plumbed to an existing sewage/drain line like that for a washing machine, etc. There are also some dehumidifiers with built-in condensate pumps, although the options are very limited.
Comment: yes, I assumed this was obvious. I'll edit the post to clarify.
Comment: This will work, but is less efficient than simply adding HVAC supply and return vents. Your air conditioner also dehumidifies, and presumably you have it on during the summer. No need for a second dehumidifier when your AC unit is already dehumidifying the rest of the house. Let it service the crawlspace, too.
Comment: that depends... on the dewpoint of the ambient air and the temperatures of the AC and crawlspace walls/floor.
Answer: I suspect your original approach was incorrect.  the only thing that should have been insulated was the crawl-space ceiling under the room you wanted to insulate. The walls of the crawl space should have been left alone - including, of course, the vent.
Contrary to what one might think, a crawl space is best kept fully ventilated, just as is the case in some houses which are built a couple feet off the ground. This does not lead to massive heat loss due to the "magic" of convective air flow.  Yes, insulate under the floor of the house, but nowhere else.
So, if you can, rip out the insulation and start again.
Comment: I wanted to store some things in the crawlspace like lumber and paint. That's why I wanted to bring it in inside the envelope.
Comment: What was incorrect was not insulating the walls, but rather adding the fan. Crawlspaces should be ventilated, or insulated and sealed, but not both.
Comment: I disagree, @iLikeDirt. In my part of the world, summer and winter are *very* different scenarios. A fan certainly is appropriate during the summer, insulation or not.
Comment: @iLikeDirt If the entire crawlspace is going to be sealed, then you must install Prop-A-Vents or equivalent to allow airlflow from the soffits up to the remainder of the open space above the rooms.
Comment: @isherwood summer ventilation to reduce humidity doesn't make sense. If the outside air was dry enough to reduce the interior humidity, there wouldn't be an interior humidity problem in the first place. The only reason why this helps at all is the *air movement*, which can be accomplished by adding HVAC vents into the sealed crawlspace.
Comment: @Carl Witthoft That's why you add supply and return HVAC vents to the crawlspace.
Comment: And if ground moisture is the problem, then the crawlspace needs to be sealed off from that moisture source.


How to create a requirements.txt file for OpenShift Online Next Gen Developer Preview?

Question: tl;dr
I am trying to create a requirements.txt file for an existing application that is running locally.
I want to know what contents should go in the requirements.txt file.
I'm doing this in order to get the local application running on:
OpenShift Online (Next Gen) Developer Preview
Detail
myapplication.py has a number of standard import statements, eg:
#  from python standard library

import os
import re
import StringIO
import json
import ast
import struct
import time
import collections

It also contains import statements in the format from X import X, eg:
#  additional modules

from bottle import route, post, default_app, template, view, TEMPLATE_PATH, response, request, static_file, install, redirect
# BEGIN pymongo
import pymongo
from bson.json_util import dumps
import gridfs
# END pymongo
import requests
from bs4 import BeautifulSoup
import lxml
import base64
import tldextract
from PIL import Image
import serial

from beaker.middleware import SessionMiddleware
from cork import Cork
from cork.cork import AuthException
from cork.cork import AAAException
from cork.backends import MongoDBBackend

import user_settings (a local .py file)

When setting up the app locally, I also had to install these from the Ubuntu Software Centre:
apache2
virtualenv
mod_wsgi

And these packages were required for pip installs in virtualenv to work:
python2.7-dev
libxml2-dev
libxslt1-dev
apache2-dev
zlib1g-dev
libjpeg8-dev

These were installed in pip whilst virtualenv was activated:
pip install bottle
pip install https://github.com/FedericoCeratto/bottle-cork/archive/master.zip
pip install requests
pip install pymongo==2.8
pip install beautifulsoup4
pip install lxml
pip install Beaker
pip install pillow
pip install tldextract
pip install serial

Questions
01)  Will the contents of my requirements.txt file just need to look like this:
pymongo
requests
lxml
tldextract
pyserial
bottle
git+git://github.com/FedericoCeratto/bottle-cork.git#egg=bottle-cork
beautifulsoup4
Beaker
pillow

02)  Will myapplication.py still need to have the import statements as defined above?
03)  The following were required for pip installs to work in virtualenv, are these already in the OpenShift environment and, if not, how do I add them?
python2.7-dev
libxml2-dev
libxslt1-dev
apache2-dev
zlib1g-dev
libjpeg8-dev

04)  Does requirements.txt live in the top directory of the repo directory?
For reference and further information, these are the results of running pip freeze locally in the virtualenv:
(ENV) me@my-computer:/var/www/html/site-name/ENV$ pip freeze
-markerlib==0.0.0
Beaker==1.8.0
beautifulsoup4==4.4.1
bottle==0.12.9
bottle-cork==0.12.0a2
funcsigs==1.0.0
idna==2.1
lxml==3.6.0
ordereddict==1.1
Pillow==3.2.0
pkg-resources==0.0.0
pycrypto==2.6.1
pymongo==2.8
pyserial==3.0.1
requests==2.9.1
tldextract==1.7.5

Comment: If you want various Python examples for OpenShift 3, go to https://gitlab.com/groups/osevg and Look for all the python-framework-server repositories.
Answer: 1) This is what I ended up using for requirements.txt:
pymongo
requests
lxml
tldextract
pyserial
bottle
# git repo at specific commit - bottle-cork==0.12.0a2
git+git://github.com/FedericoCeratto/bottle-cork.git@557bc6cc249ea8dcb7b76d85bde116527eb41223#egg=bottle-cork
beautifulsoup4
Beaker
pillow

And the build seems to work.
In answer to my other questions:
2) Yes, keep the import statements as is in the Python application.
3) All installs of packages in requirements.txt seem to go ahead without requiring explicit installation of:
python2.7-dev
libxml2-dev
libxslt1-dev
apache2-dev
zlib1g-dev
libjpeg8-dev

4) Yes, requirements.txt lives in the top directory of the repo.


WSL1804 (universe enabled): Can't install p7zip-full

Question: I need to use 7z on wsl-ub1804, so I try to install it through sudo apt-get install p7zip-full but it failed.
I've check ubuntu packages so I'm sure that it's there.
I've check other question, and my universe repo is enabled
here is my console log if needed.
What is problem and how could I fix it?
longwsl@DESKTOP-3NGNNKU:~$ sudo apt-get install p7zip-full
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package p7zip-full is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'p7zip-full' has no installation candidate
longwsl@DESKTOP-3NGNNKU:~$ sudo add-apt-repository universe
'universe' distribution component is already enabled for all sources.
longwsl@DESKTOP-3NGNNKU:~$ sudo apt-get install p7zip-full
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package p7zip-full is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'p7zip-full' has no installation candidate
longwsl@DESKTOP-3NGNNKU:~$

Comment: I've just `sudo apt-get update` and it works now, thanks, can you reply in answer so I could mark it as `Answer`?
Answer: Try: sudo apt-get update OR sudo apt update
After you make any change to your sources (like adding the Universe repository), you must update apt's database of available packages.


WebAPI 2 routing areas

Question: I have an area called "Location" in which there is a controller called "CountryController". I would like to call the GET action using api/location/country. Is there any way to specify Areas in the default route?
Ideally something like
<code>routeTemplate: "api/{area}/{controller}/{action}/{id}"
</code>
Comment: You can directly define it in your WebApiConfig as long as your controller exists in the corresponding namespace. Area is more of a concept for MVC to define it's search range of views, and since APIController doesn't need views, it won't be a problem. If you have issues like two controllers has same name in different area, attribute routing can make your life easier IMO
Comment: Neither api/location/country nor api/country are getting to the resource. I just assumed that it's an area routing issue.
Comment: You have to first create a route and define the `{area}` in your WebApiConfig although you are not going to use that for anything. Otherwise the route will assume your "country" as controller name.
Answer: You will need to write a custom action selector to achieve selection based on namespaces.
Since it's tough to get right (and get the performance and caching after you do it).
I'd recommend going with attribute routing instead.
Comment: Attribute routing. Thanks for the tip!
Answer: Area functionality not available in Asp.Net Web API project, and its harder to maintain with custom way like Namespace based controller.Please visit https://stackoverflow.com/a/34452395/1365663 to get your solution

WebAPI 2 routing areas


represent $\cos(x^{1/2})$ by Maclaurin series

Question: I need to represent $\cos(x^{1/2})$ by Maclaurin series.
I'm not sure that what I have done is correct. We know Maclaurin series for $$\cos(x) = 1-  {x^2 \over 2!} +{x^4\over  4!}+\cdots$$  So I substitue $x^{1/2}$, and I got $$\cos(x^{1/2})= 1 - {x\over 2!} + {x^2\over4!}+\cdots$$
But when I check it, with $x=16$, I don't get the correct answer. Where is the problem? Thanks.
Comment: The problem is that the derivative of $\sqrt{x}$ is not defined in 0.
Comment: You probably aren't taking enough terms. "check" $x=16$, with more terms in the expansion.
Comment: I suspect you have rounding problems: what do you get with $x=4$ in the first formula?
Comment: If "check" means to numerically compare $\cos(x^{1/2})$ with a partial sum of the series for $x=16$, you'll probably want to go up to $x^8$ or so.
Comment: @Jon's comment is potentially very important. It might mean that the two current answers are incorrect, including the 'accepted' answer.
Comment: Doh! Ignore my last comment. The function can be made to behave itself nicely at 0. $\sqrt{x}$ would not work, but $\text{cos}(\sqrt{x})$ does work.
Answer: What you did is perfectly valid. But note the equality is obtained using the infinite series.
$$
\cos(x^{1/2})= 1 - {x\over 2!} + {x^2\over4!}+\cdots
$$
If you just take a few terms of the series, you get an approximation:
$$
\cos(x^{1/2})\approx 1 - {x\over 2!} + {x^2\over4!}.
$$
And the larger $x$ is, for a fixed partial sum, the worse the approximation becomes.
Using the first three terms, with   $x=16$, you have:
$$
\cos(16^{1/2})-( 1 - {16\over 2!} + {16^2\over4!})\approx -4.32.
$$
But if you go out to the $8$th term, the error is small:
$$
\cos(16^{1/2})-( 1 - {16\over 2!} + {16^2\over4!} +\cdots- {16^7\over 14!})\approx.000195.
$$
Using even more terms will give you even smaller errors.
Comment: This is not valid. $cos(x^\frac12)$ is not even continuous at 0, and it needs to be infinitely differentiable in order to define a Maclaurin series. (Thanks to @Jon for pointing me 99% of the way to the answer.)
Comment: @Aaron McDaid Formally making the substitution produces a valid result. I'm not saying that $\cos\sqrt x$ has a Taylor series at $a=0$; just that the identity holds for $x\ge 0$ (since it holds for any argument of the $\cos$).
Answer: This is correct, how did you check it?
I obtain :

$\cos(4) =-0.6536$
$1 - 16/2 + 16^2/4! = 3,67$
$1 - 16/2 + 16^2/4! - 16^3/6! = -2.022$
$1 - 16/2 + 16^2/4! - 16^3/6! + 16^4/8! = - 0.39$
$\vdots$
$1 - 16/2 + 16^2/4! + \cdots - 16^7/14! = - 0.6538$

For $x$ as big as 16, the convergence is not as fast as you may think. It is much faster with small values of $x$.
Comment: @AaronMcDaid: The power series in OP's answer converges for all $x$ (even complex). Thus the sum of the series defines a function $f(x)$ with the properties: 1) it is infinitely differentiable everywhere, 2) for all $x\ge0$ we have $f(x)=\cos(\sqrt{x})$. What more can you ask?
Comment: This is not valid. $cos(x^\frac12)$ is not even continuous at 0, and it needs to be infinitely differentiable in order to define a Maclaurin series. (Thanks to @Jon for pointing me 99% of the way to the answer.)
Answer: (Update: It can be answered after all. Please ignore this answer. For negative x, the identity $\text{cos}\sqrt{x} =  \text{cosh}\sqrt{-x}$ behaves nicely and it's possible to fill in the singularity.)
This question cannot be answered. The function $\text{cos}(x^\frac12)$ is not continuous at 0 and hence it is not meaningful to think about a Maclaurin series.
You would be attempting to take a square root of a negative number. And complex analysis won't help here either, as a Maclaurin it needs to be infinitely differentiable at 0, and it is not.
You could take the Taylor series at any positive value.
Comment: Hmm, let me think... since $\cos\,ix=\cosh\,x$, the function still ought to make sense for $x < 0$. The first derivative is $-\frac12\mathrm{sinc}(\sqrt x)$, and a similar hyperbolic representation can be derived for $x < 0$. Hmm...
Comment: @J.M. , cool observation! (**Update**, I'm tempted to delete the rest of this comment, I was getting ahead of myself) So it's defined nicely for x<0 , and for x>0, but what happens at x=0? Can the two sides be joined together? (I'm going to quickly do some plots now)
Comment: Sure looks like it to me. You're familiar with $\lim\limits_{x\to 0}\frac{\sin\,x}{x}=1$, yes?
Comment: But when you take the derivatives you get also the contributions coming from sine and cosine functions that are able to compensate the singular behavior of $\sqrt{x}$. So, e.g. $\left.(\cos(\sqrt{x}))'\right|_{x=0}=\frac{1}{2}$. David's answer is correct and OP problem is just a matter of slowness of convergence of the series. The latter is the only effect of the singular behavior of the argument of the cosine.
Comment: Yep. I'm familiar with that.
Comment: OK, That all makes sense now. +1 to David


JSF 2.1.X validation behaves differently on Glassfish 3.1.2 vs. Tomcat 6 & 7

Question: I'm experiencing what I think is odd behavior with the JSF validation between Tomcat and Glassfish.  Previously we were using Tomcat, but now have requirements to run a full Java EE App Server.
During testing, I noticed when submitting empty fields to the server, that simply have a length validator and no required attribute, Glassfish is outputting the validation message whereas, Tomcat would simply skip the validation on these elements.
If a value is submitted and fails validation everything works fine, it is simply when no value is entered and the page is submitted.
Environment Specifics

JSF Mojarra 2.1.12
Richfaces 4.1
Target server Glassfis 3.1.2
Moving from Tomcat 7.0.27

Here is a snippet of code that contains the described behavior:
<h:inputText id="phoneAreaCode"
             maxlength="3"
             size="2"
             value="#{bean.phoneArea}"
             style="margin-left: 8px;">
    <f:validateLength minimum="3"/>
    <f:validator validatorId="phoneValidator"/>
    <a4j:ajax/>
</h:inputText>

Use Case (Tomcat):

If a value is provided, validation occurs.  If value passes validation, page is allowed to submit, if it fails, error message is outputted to page.
If no value is provided, no validation occurs, and page is allowed to submit

Use Case (Glassfish):

Same as above
If no value is provided, validation still occurs, and obviously fails.

I am seeing this behavior for custom validators via <f:validator/> tags as well as the built in ones like <f:validateLength/>.
No code difference, just the server the code is running on.  I've searched Google and I'm not really finding anything to help.  Am I not understanding something about validation?  Do you see anything wrong?
This Stackoverflow question sounds like the same issue, I just don't see the solution to prevent my environment from behaving in this manner or how to disable the validation when the field is not required.
Thank you to anyone for helping me out on this.
Comment: What JSF implementation are you using? Mojarra or MyFaces?
Comment: I've updated the question body with implementation specifics.
Answer: I had a very similar issue a few days ago and I assume that the property phoneArea might be an Integer or Long. If so, you may take a look at this topic and additionally at this one.
Comment: Thank you MarkusR for your time on this, unfortunately all my fields are bound to String values.  Also, I'm not sure (still looking into it), but the links you provided seem to be issues if I was trying to target Tomcat.  We are trying to migrate to Glassfish and from what I read, @BalusC seemed to indicate the specific issue referenced was only an issue with Tomcat and not Glassfish. Please let me know, however; if I have misinterpreted what you referenced.  Thank you again!
Comment: Using the second reference you, [provided](http://stackoverflow.com/questions/7545231/notnull-notblank-and-notempty-bean-validation-does-not-work-in-jsf/7548821#7548821) ,enabled me to get over this problem.  I added the `javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL` to the web.xml and now all is functioning as desired.  Thank you!
Comment: this seemed to work at first, however; if I add the above to my web.xml -- any component that has the required="true" attribute will not show the validation error message.  The page will not post, but still user is left wondering why because no message displays.


How to create a global rewrite rule to redirect all root domain request to www?

Question: The target IIS serves multiple domains via multiple sites and host header binding.
So far when a new site (domain) was added I could create a specific rule for that domain to redirect example.com requests to www.example.com.
<rule name="Redirect to www" stopProcessing="true">
  <match url="(.*)" />
  <conditions >
    <add input="{HTTP_HOST}" pattern="^example.com" />
  </conditions>
  <action type="Redirect"
    <-- it is OK to hardcode https, because http->https rewrite rule also in effect --!>,
    url="https://www.example./{R:1}" />
</rule>

Question
Besides I am not sure the rule/condition/action above is entirely correct, now I would like to improve the solution to one universal rewrite rule.
How can I add an universal global rule what will apply to all (future) domains, and redirects anysld.anytld/anyremainingpathandqueryandwhoknowswhat to www.anysld.anytld/anyremainingpathandqueryandwhoknowswhat?
Answer: If you need to use global rules to redirect requests to www in all root domain, you can try the following global rule:
<rewrite>
    <globalRules>
         <rule name="Add www" stopProcessing="true">
                <match url="^(.*)$" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="^(?!www\.)(.*)$" />
                </conditions>
                <action type="Redirect" url="https://www.{C:0}" appendQueryString="false" />
          </rule>
    </globalRules>
</rewrite>

Answer: If I understood your question correctly code from another SO question should help you. Take a look at IIS7 URL Rewrite - Add "www" prefix. Is this what you are looking for?


Create a function in R with multi outputs like matlab

Question: I'm not familiar with R, just a newbie. So I want to translate some code from matlab to R. But I have the problem about the output of function. I want to create a function give output to two specify variable, like this:
list[a,b]<-function(var1,var2){
a<-var1 + var2
b<-var1 - var2
return list(a,b)
}

But my code is not working, please help me to solve this problem.
Comment: Not sure what you're trying to achieve here but assigning a function to the indices of a list is strange to say the least.
Answer: You seem to have some fundamental misunderstanding about functions in R. Read "An Introduction to R". Also, return is a function in R.
myfun <- function(var1, var2){
  a <- var1 + var2
  b <- var1 - var2
  return(list(a, b))
}

myfun(1:5, 10:6)
#[[1]]
#[1] 11 11 11 11 11
#
#[[2]]
#[1] -9 -7 -5 -3 -1

Comment: Each function in R should have just one return value. There are ways to circumvent this rule, but that's bad programming and I won't show you how. It's not necessary anyway, because working with a list is more convenient.
Comment: If you want your output to be named you can `return(list(a=a, b=b))`. That way you can reference the result by name like `result$a`...
Comment: I know this way but I want return result on two outputs with different name, not one list variable.