How to leverage compiler-generated copy/move ctors when using unique_ptr as a data member?

Question: Say I have a class with a unique_ptr data member, and I want the class to support copying, by deep-cloning the object the smart pointer is pointing at:
#include <iostream>
#include <memory>

using namespace std;

class Bar {
public:
    Bar() { cout << "Bar::ctor " << this << '\n'; }
    ~Bar() { cout << "~Bar" << this << '\n'; }
    std::unique_ptr<Bar> clone() const {
        auto p = std::make_unique<Bar>(*this);
        cout << "Bar::clone() " << this << " to " << p << '\n';
        return p;
    }
};

class Foo {
public:
    Foo() = default;
    ~Foo() = default;
    Foo(Foo const & other) : p_{other.p_->clone()} {
        cout << "Foo::copy-ctor " << p_ << ", other.p_ " << other.p_ << '\n';
    }
    Foo(Foo && other) : p_{std::move(other.p_)} {
        cout << "Foo::move-ctor " << p_ << ", other.p_ " << other.p_ << '\n';
    }
    Foo & operator=(Foo const & other) {
        cout << "Foo::copy-assign " << p_ << ", other._p " << other.p_ << '\n';
        p_ = other.p_->clone(); return *this;
    }
    Foo & operator=(Foo && other) {
        cout << "Foo::move-assign " << p_ << '\n';
        p_ = std::move(other.p_); return *this;
    }

    void store(std::unique_ptr<Bar> p) {
        cout << "Foo::store() " << p << '\n';
        p_ = std::move(p);
    }

public:  // so we can print out p_ later
    std::unique_ptr<Bar> p_;
};

std::unique_ptr<Bar> bar() {
    return std::make_unique<Bar>();
}

int main() {
    Foo f;

    auto b = bar();
    cout << "b " << b << '\n';

    f.store(std::move(b));

    cout << "copy" << '\n';
    auto g {f};
    cout << "assign" << '\n';
    Foo h;
    h = f;
    cout << "move" << '\n';
    auto i = std::move(f);

    cout << "f.p_ " << f.p_ << '\n';
    cout << "g.p_ " << g.p_ << '\n';
    cout << "h.p_ " << h.p_ << '\n';
}

https://godbolt.org/z/qjf8MoKsE
Output:
Bar::ctor 0x2314eb0
b 0x2314eb0
Foo::store() 0x2314eb0
copy
Bar::clone() 0x2314eb0 to 0x2315ee0
Foo::copy-ctor 0x2315ee0, other.p_ 0x2314eb0
assign
Foo::copy-assign 0, other._p 0x2314eb0
Bar::clone() 0x2314eb0 to 0x2315f00
move
Foo::move-ctor 0x2314eb0, other.p_ 0
f.p_ 0
g.p_ 0x2315ee0
h.p_ 0x2315f00
~Bar0x2314eb0
~Bar0x2315f00
~Bar0x2315ee0

It's a bit verbose but the point is that = default; doesn't work because of the unique_ptr data member and its deleted copy-constructor, so I have to manually define these functions to obtain the deep-copy semantics that I seek.
For a single unique_ptr data member, this isn't too bad. But if I add additional data members to the Foo class, it seems to me that I will have to explicitly copy/assign them in each of the four copy/move ctors/assignment operators, because the default member functions have not been generated.
This makes me wonder if there's a standard-library wrapper for unique_ptr that enables automatic deep-copy, as well as maintaining things like const correctness, that would allow me to reduce Foo to something like:
class Foo {
public:
    Foo() = default;
    ~Foo() = default;
    Foo(Foo const & other) = default;
    Foo(Foo && other) = default;
    Foo & operator=(Foo const & other) = default;
    Foo & operator=(Foo && other) = default;

    // ...

public:
    DeepCopyUniquePtr p_;  // what is this?
    int a;
    float b;
    // lots...
    char z;
};

Thereby falling back on the default copy/move ctors and assignment operators.
I also found that when I have multiple unique_ptr data members, these functions can also get messy quickly.
Comment: No, there's no such "wrapper" in the C++ library. But it's not a big deal to write one yourself.
Comment: Long story short: no, there is not, but writing one's own decorators should not be that hard. As for const-correctness you may have a look at [propagate_const](https://en.cppreference.com/w/cpp/experimental/propagate_const) but again, it's trivial enough to be written while the coffee's getting ready ;)
Comment: You can look for keywords as "deep_ptr", "clone_ptr", or "value_ptr" to get some implementations.
Comment: You can still make the move members `=default`. What you need define is the copy versions. And the `clone` member is not actually required, unless there are special design considerations. `p_{std::make_unique(*other.p_)}` does the deep copy. Then you can copy/move combo to define copy assignment:`return (*this)=Foo{other};`; move-assign the copy-constructed version. Or you can unify the assignments in one by-value assignment with copy/swap idiom.
Comment: @Red.Wave good point on `clone` - it's actually a hang-over from `Bar` being a derived class in my real code, so it's there as (what would be) a virtual function to prevent slicing when copying `other.p_`, when `p_` is a pointer to the base class. I appreciate that this isn't shown in my example code and I probably should have removed it. Is that a valid example of the "special design considerations" you are alluding to?
Comment: @davidA if it's legacy, then it is there. As long as you can identify the actual type at compile time, using a such a virtual function doesn't help much. Using templates usually (not always, but most often) means the type is known at compile-time, unless some type-erasure design removes that information.
Answer: As mentioned in the comments, you could write your own decorator.
template <typename Ptr>
struct Clonable
{
    Clonable() = default;

    Clonable(Ptr&& ptr) : p(std::move(ptr)) {}

    Clonable(Clonable const& other)
     : p{other.p->clone()}
    {}

    Clonable(Clonable&& other)
     : p{std::move(other.p)}
    {
        other.p = nullptr;
    }

    Clonable& operator=(Clonable const & other)
    {
        p = other.p->clone();
        return *this;
    }

    Clonable& operator=(Clonable&& other){
        p = std::move(other.p);
        other.p = nullptr;
        return *this;
    }

    auto operator*() {
        return *p;
    }

    auto operator*() const {
        return *p;
    }

    auto operator->() {
        return p.operator->();
    }

    auto operator->() const {
        return p.operator->();
    }

    Ptr p;
};

template <typename T>
using DeepCopyUniquePtr = Clonable<std::unique_ptr<T>>;

https://godbolt.org/z/eTqTEncfa
Comment: If you have c++20 you would probably want to constrain `Clonable` for pointer arithmetics and the `clone` member function using appropriate concepts.


Drupal 7 in subfolder behind reverse proxy, login not working

Question: I'm trying to run a Drupal 7.12 site behind an nginx reverse proxy, so that it shows up in a sub-folder to the primary domain (company.com).
Nginx is handling all incoming traffic to http://company.com, and Drupal is installed on another server with Apache. We want the content from Drupal to show up under http://company.com/drupal/.
For nginx, there is a proxy_pass specified like this:
  location /drupal/ {
    proxy_pass http://drupal.company.com/;
  }

For Drupal, I have set
$base_url = http://company.com/drupal;

This works fine to browse the content, Drupal is generating correct links, etc.
But when I try to login /drupal/user, I get the login form, but the action parameter for the form is set to "/user" - it seems that Drupal is forgetting to apply the base_url here.
Any ideas how to solve this issue? Help appreciated...
Answer: As I understood, the #action on the page /user is generated by request_uri, the default action of each form, except for few form that are block (check if the user_login block has the same problem).
I can advise you, to check your PHP config in Report -> Status report and then click on the PHP version an try to find the REQUEST_URI information, this can be different from what you are expecting (I guess /drupal/user).
To fixe it, I see only two solutions, submit an issue (or check if that issue already exists) or the second its to use the hook_form_alter and replace the #action by something like that.
$form['#action'] = url(current_path(), array('external' => FALSE));

Answer: You can find the solution at https://drupal.org/node/244593
In essence you rewrite $_SERVER['REQUEST_URI'] in settings.php.


Find order of given factor group

Question:
I'm trying to find the order of this factor group:
  $$(\mathbb Z_{12}\times\mathbb Z_{18}) / \langle (4,3)\rangle.$$

The order of the factor group is just the number of elements in it (aka the number of cosets).  Let $H = \langle(4,3)\rangle, G = Z_{12}\times Z_{18}$.
$$H = \{(4,3), (8,6), (0,9), (4,12), (8,15), (0,0)\}$$
So a coset of $H$ in $G$ is of the form $aH$, where $a \in G$
Let $a = (0,0)$.  Then $aH = H$.  From above, we know this coset has 6 elements.  Further, each coset must have the same number of elements.
So now we just take the order of G and divide by 6 to get the order of $G$ / $H$.
There are 12 choices for $Z_{12}$ and 18 choices for $Z_{18}$ so order of $G = 12 \cdot 18 = 216$.
$216 \div 6 = 36$.  So the order of $G / H$ is 36.
Does this look right?
Thanks for the help,
Mariogs
Comment: Yep. All correct. :)
Comment: Thanks @IlikeSerena, I will find all elements right now!!! hahahahaha
Comment: @Salvattore, I think that should be aHaHaHaHaH. :D
Comment: @IlikeSerena hello, how can I get the elements of the factor group?
Comment: Hi @Salvattore. They are the elements $aH$ for the different values of $a$. That is (0,0)H, (1,0)H, (2,0)H, (3,0)H, etcetera. We can skip e.g. (4,0)H now, because that is the same as (0,0)H.
Comment: I am confused, how you expanded H? :)
Answer: Yaaa.
Using Lagrange's thm Which states that if G is a finite group and H is a subgroup of G then no of left (right) cosets of H in G is |G|/|H|

Find order of given factor group


Add Child View Controllers to parent View Controller with gestures programmatically

Question: I am trying to make a hamburger menu programmatically. So far I have managed to build something that works (minus a few bugs) when using UIViews and attaching gestures to them.
Now I want to swap my UIViews for UIViewControllers that are named:
jobListController // This is the root controller
sideBarController // This is the side bar

How do I add my UIViewControllers to my hamburger menu class and apply the gestures I have created that seem to work fine on my UIViews.
I have tried adding them using: addChildViewController(jobListController), but that doesnt seem to work.
I have tried to add the gesture recognizer to the viewcontrollers in my hamburger menu class but I get this error:

Type 'jobListController' has no member 'addGestureRecognizer'

I realise this is because I am not parenting the viewcontrollers to the class but I was just trying things out.
I have been tearing my hair out for a few days now and can't work out how to do this, any help would be great!
Here is my hamburger menu code (I have left the UIViews in so you can see what I am trying to do:
    class hamburgerMenu: UIViewController, UIGestureRecognizerDelegate {

    let screenHeight = UIScreen.main.bounds.height
    let screenWidth = UIScreen.main.bounds.width
    let statusBarWindow = UIApplication.shared.value(forKey: "statusBarWindow") as? UIWindow

    var sideBarOriginalCenter: CGPoint!
    var mainViewOriginalCenter: CGPoint!
    var navBarOriginalCenter: CGPoint!
    var statusBarShouldBeHidden = false

    var mainView: UIView! = {
        let mainView = UIView()
        mainView.backgroundColor = UIColor(red:1.0, green:1.0, blue:1.0, alpha:1.0)
        mainView.translatesAutoresizingMaskIntoConstraints = false
        return mainView
    }()
    var overlayView: UIView! = {
        let overlayView = UIView()
        overlayView.backgroundColor = UIColor(red:0.0, green:0.0, blue:0.0, alpha:0.0)
        overlayView.translatesAutoresizingMaskIntoConstraints = false
        return overlayView
    }()
    var sideBarUIView: UIView! = {
        let sideBarUIView = UIView()
        sideBarUIView.backgroundColor = UIColor(red:0.18, green:0.20, blue:0.21, alpha:1.0)
        sideBarUIView.translatesAutoresizingMaskIntoConstraints = false
        return sideBarUIView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        navigationItem.title = "JOBS"
        let settingsButton = UIBarButtonItem(image: #imageLiteral(resourceName: "settingsImage"), style: .plain, target: self, action: #selector(HandleSettings))
        settingsButton.tintColor = UIColor(red:0.63, green:0.63, blue:0.63, alpha:1.0)
        settingsButton.width = 25
        navigationItem.leftBarButtonItem = settingsButton

        view.addSubview(mainView)
        view.addSubview(sideBarUIView)
        view.addSubview(overlayView)

        overlayView.isHidden = true

        configureGestures()
        setupLayout()

    }

    override var prefersStatusBarHidden: Bool {
        return statusBarShouldBeHidden
    }

    override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
        return .fade
    }

    fileprivate func configureGestures() {

        let swipeMainViewGesture = UIPanGestureRecognizer(target: self, action: #selector(didPanMainView))
        mainView.addGestureRecognizer(swipeMainViewGesture)

        let swipeOverlayViewGesture = UIPanGestureRecognizer(target: self, action: #selector(didPanOverlayView))
        overlayView.addGestureRecognizer(swipeOverlayViewGesture)

        let swipeSideBarGesture = UIPanGestureRecognizer(target: self, action: #selector(didPanSideBar(sender:)))
        sideBarUIView.addGestureRecognizer(swipeSideBarGesture)

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapOverlay))
        overlayView.addGestureRecognizer(tapGesture)
    }

    @IBAction func didPanMainView(sender: UIPanGestureRecognizer) {

        let translation = sender.translation(in: view)

        if sender.state == .began {

            sideBarOriginalCenter = sideBarUIView.center
            mainViewOriginalCenter = overlayView.center
            navBarOriginalCenter = navigationController?.navigationBar.center
            overlayView.isHidden = false

            UIView.animate(withDuration: 0.25) {
                self.setNeedsStatusBarAppearanceUpdate()
            }

        } else if sender.state == .changed {

            sideBarUIView.center = CGPoint(x: sideBarOriginalCenter.x + translation.x, y: sideBarUIView.center.y)
            overlayView.center = CGPoint(x: mainViewOriginalCenter.x + translation.x, y: sideBarUIView.center.y)
            mainView.center = CGPoint(x: mainViewOriginalCenter.x + translation.x, y: sideBarUIView.center.y)
            navigationController?.navigationBar.center = CGPoint(x: navBarOriginalCenter.x + translation.x, y: navBarOriginalCenter.y)

        } else if sender.state == .ended {

            let negHalfScreenWidth = ((self.screenWidth/2) * -1) / 2 // This should make -187.5 on iphoneX

            if sideBarUIView.center.x > negHalfScreenWidth {
                UIView.animate(withDuration: 0.3) {

                    if self.sideBarUIView.center.x > negHalfScreenWidth {

                        let leftSideOfScreen = self.screenWidth - self.screenWidth

                        self.sideBarUIView.center = CGPoint(x: leftSideOfScreen ,y: self.sideBarUIView.center.y)
                        self.overlayView.center = CGPoint(x: self.screenWidth ,y: self.sideBarUIView.center.y)
                        self.mainView.center = CGPoint(x: self.screenWidth ,y: self.sideBarUIView.center.y)
                        self.navigationController?.navigationBar.center = CGPoint(x: self.screenWidth ,y: self.navBarOriginalCenter.y)
                    }
                }
            } else {
                UIView.animate(withDuration: 0.3) {

                    let leftSideOfScreen = (self.screenWidth / 2) * -1

                    self.sideBarUIView.center = CGPoint(x: leftSideOfScreen ,y: self.sideBarUIView.center.y)
                    self.overlayView.center = CGPoint(x: self.screenWidth/2 ,y: self.sideBarUIView.center.y)
                    self.mainView.center = CGPoint(x: self.screenWidth/2 ,y: self.sideBarUIView.center.y)
                    self.navigationController?.navigationBar.center = CGPoint(x: self.screenWidth/2 ,y: self.navBarOriginalCenter.y)
                    self.overlayView.isHidden = true

                    // Hide the status bar
                    self.statusBarShouldBeHidden = false
                    self.setNeedsStatusBarAppearanceUpdate()
                }
            }
        }
    }

    @IBAction func didPanOverlayView(sender: UIPanGestureRecognizer) {

        let translation = sender.translation(in: view)

        if sender.state == .began {

            sideBarOriginalCenter = sideBarUIView.center
            mainViewOriginalCenter = overlayView.center
            navBarOriginalCenter = navigationController?.navigationBar.center
            overlayView.isHidden = false

            UIView.animate(withDuration: 0.25) {
                self.setNeedsStatusBarAppearanceUpdate()
            }

        } else if sender.state == .changed {

            sideBarUIView.center = CGPoint(x: sideBarOriginalCenter.x + translation.x, y: sideBarUIView.center.y)
            overlayView.center = CGPoint(x: mainViewOriginalCenter.x + translation.x, y: sideBarUIView.center.y)
            mainView.center = CGPoint(x: mainViewOriginalCenter.x + translation.x, y: sideBarUIView.center.y)
            navigationController?.navigationBar.center = CGPoint(x: navBarOriginalCenter.x + translation.x, y: navBarOriginalCenter.y)

        } else if sender.state == .ended {

            let negHalfScreenWidth = ((self.screenWidth/2) * -1) / 2 // This should make -187.5 on iphoneX

            if sideBarUIView.center.x > negHalfScreenWidth {
                UIView.animate(withDuration: 0.3) {

                    if self.sideBarUIView.center.x > negHalfScreenWidth {

                        let leftSideOfScreen = self.screenWidth - self.screenWidth

                        self.sideBarUIView.center = CGPoint(x: leftSideOfScreen ,y: self.sideBarUIView.center.y)
                        self.overlayView.center = CGPoint(x: self.screenWidth ,y: self.sideBarUIView.center.y)
                        self.mainView.center = CGPoint(x: self.screenWidth ,y: self.sideBarUIView.center.y)
                        self.navigationController?.navigationBar.center = CGPoint(x: self.screenWidth ,y: self.navBarOriginalCenter.y)
                    }
                }
            } else {
                UIView.animate(withDuration: 0.3) {

                    let leftSideOfScreen = (self.screenWidth / 2) * -1

                    self.sideBarUIView.center = CGPoint(x: leftSideOfScreen ,y: self.sideBarUIView.center.y)
                    self.overlayView.center = CGPoint(x: self.screenWidth/2 ,y: self.sideBarUIView.center.y)
                    self.mainView.center = CGPoint(x: self.screenWidth/2 ,y: self.sideBarUIView.center.y)
                    self.navigationController?.navigationBar.center = CGPoint(x: self.screenWidth/2 ,y: self.navBarOriginalCenter.y)
                    self.overlayView.isHidden = true

                    self.statusBarShouldBeHidden = false
                    self.setNeedsStatusBarAppearanceUpdate()
                }
            }
        }
    }

    @IBAction func didPanSideBar(sender: UIPanGestureRecognizer) {
        let translation = sender.translation(in: view)

        if sender.state == .began {

            sideBarOriginalCenter = sideBarUIView.center
            mainViewOriginalCenter = overlayView.center
            navBarOriginalCenter = navigationController?.navigationBar.center
            overlayView.isHidden = false

            UIView.animate(withDuration: 0.3) {
                self.statusBarWindow?.alpha = 0.0
            }

        } else if sender.state == .changed {

            sideBarUIView.center = CGPoint(x: sideBarOriginalCenter.x + translation.x, y: sideBarUIView.center.y)
            overlayView.center = CGPoint(x: mainViewOriginalCenter.x + translation.x, y: sideBarUIView.center.y)
            mainView.center = CGPoint(x: mainViewOriginalCenter.x + translation.x, y: sideBarUIView.center.y)
            navigationController?.navigationBar.center = CGPoint(x: navBarOriginalCenter.x + translation.x, y: navBarOriginalCenter.y)

        } else if sender.state == .ended {

            let negHalfScreenWidth = ((self.screenWidth/2) * -1) / 2 // This should make -187.5 on iphoneX

            if sideBarUIView.center.x > negHalfScreenWidth {
                UIView.animate(withDuration: 0.3) {

                    if self.sideBarUIView.center.x > negHalfScreenWidth {

                        let leftSideOfScreen = self.screenWidth - self.screenWidth

                        self.sideBarUIView.center = CGPoint(x: leftSideOfScreen ,y: self.sideBarUIView.center.y)
                        self.overlayView.center = CGPoint(x: self.screenWidth ,y: self.sideBarUIView.center.y)
                        self.mainView.center = CGPoint(x: self.screenWidth ,y: self.sideBarUIView.center.y)
                        self.navigationController?.navigationBar.center = CGPoint(x: self.screenWidth ,y: self.navBarOriginalCenter.y)
                    }
                }
            } else {

                UIView.animate(withDuration: 0.3) {
                    let leftSideOfScreen = (self.screenWidth / 2) * -1
                    self.sideBarUIView.center = CGPoint(x: leftSideOfScreen ,y: self.sideBarUIView.center.y)
                    self.overlayView.center = CGPoint(x: self.screenWidth/2 ,y: self.sideBarUIView.center.y)
                    self.mainView.center = CGPoint(x: self.screenWidth/2 ,y: self.sideBarUIView.center.y)
                    self.navigationController?.navigationBar.center = CGPoint(x: self.screenWidth/2 ,y: self.navBarOriginalCenter.y)
                    self.overlayView.isHidden = true
                    self.statusBarWindow?.alpha = 1.0
                }
            }
        }
    }

    @IBAction fileprivate func didTapOverlay() {
        UIView.animate(withDuration: 0.3, animations: {
            let leftSideOfScreen = (self.screenWidth / 2) * -1
            self.sideBarUIView.center = CGPoint(x: leftSideOfScreen ,y: self.sideBarUIView.center.y)
            self.overlayView.center = CGPoint(x: self.screenWidth/2 ,y: self.sideBarUIView.center.y)
            self.mainView.center = CGPoint(x: self.screenWidth/2 ,y: self.sideBarUIView.center.y)
            self.navigationController?.navigationBar.center = CGPoint(x: self.screenWidth/2 ,y: self.navBarOriginalCenter.y)
            self.overlayView.isHidden = true
            self.statusBarWindow?.alpha = 1.0
        }) { (success) in
        }
    }

    @IBAction func HandleSettings(sender : UIButton) {

        self.navBarOriginalCenter = self.navigationController?.navigationBar.center

        UIView.animate(withDuration: 0.3, animations: {
            let leftSideOfScreen = self.screenWidth - self.screenWidth

            self.sideBarUIView.center = CGPoint(x: leftSideOfScreen ,y: self.sideBarUIView.center.y)
            self.overlayView.center = CGPoint(x: self.screenWidth ,y: self.sideBarUIView.center.y)
            self.mainView.center = CGPoint(x: self.screenWidth ,y: self.sideBarUIView.center.y)
            self.navigationController?.navigationBar.center = CGPoint(x: self.screenWidth ,y: self.navBarOriginalCenter.y)
            self.statusBarWindow?.alpha = 0.0
        })
        overlayView.isHidden = false
   }

    private func setupLayout(){

        mainView.heightAnchor.constraint(equalToConstant: screenHeight).isActive = true
        mainView.widthAnchor.constraint(equalToConstant: screenWidth).isActive = true

        overlayView.heightAnchor.constraint(equalToConstant: screenHeight).isActive = true
        overlayView.widthAnchor.constraint(equalToConstant: screenWidth).isActive = true

        sideBarUIView.rightAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
        sideBarUIView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        sideBarUIView.heightAnchor.constraint(equalToConstant: screenHeight).isActive = true
        sideBarUIView.widthAnchor.constraint(equalToConstant: screenWidth).isActive = true
    }
}

And the code for my 2 controllers, the code is exactly the same except the class name that I mentioned above:
class sideBarController: UIViewController {
    let screenHeight = UIScreen.main.bounds.height
    let screenWidth = UIScreen.main.bounds.width

    var greyBackground: UIView! = {
        let greyBackground = UIView()
        greyBackground.backgroundColor = UIColor(red:0.18, green:0.20, blue:0.21, alpha:1.0)
        greyBackground.translatesAutoresizingMaskIntoConstraints = false
        return greyBackground
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(greyBackground)
        setupLayout()
    }
    private func setupLayout(){
        greyBackground.rightAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
        greyBackground.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        greyBackground.heightAnchor.constraint(equalToConstant: screenHeight).isActive = true
        greyBackground.widthAnchor.constraint(equalToConstant: screenWidth).isActive = true
    }
}

Answer: I'm assuming jobListController is a UIViewController? You need to add gesture recognizers to its view (jobListController.view). Not sure if that's the only issue you're having, but that'll fix the crash.
Comment: Yes, they are both UIViewControllers. Do you mean add the gesture recognizers within each UIViewController? At the moment I cannot even load the UIViewControllers to my hamburger menu.
Comment: That's one way you could do it, but I think the cleaner way would be to add the gestureRecognizer to the view containing the child view controllers and prevent it from blocking touches by setting cancelsTouchesInView to false. Then all you have to do once a selection is made in the side bar is to remove the old view and add the new one (and add constraints so it fills the view). https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html#//apple_ref/doc/uid/TP40007457-CH11-SW18 is a good example for that.
Comment: Okay I think that makes sense, but how do I actually add the view controllers to my hamburger menu, I am getting errors when I try `addChildViewController`
Comment: addChildViewController does a few important things, but you have to do most of the legwork yourself IIRC. You'll probably have to manually add the child's view (e.g. jobListController.view) to the mainView when presenting it.
Comment: I'm sorry, but I am really confused. Can you please provide an example so I can understand a bit better?
Comment: This is an Obj C project and might be a little dated, but is similar to what you're trying to do. https://github.com/willowtreeapps/MTStackViewController


Red Hat Licensing Model, a license is needed to run it?

Question:
Possible Duplicate:
Can you help me with my software licensing issue?

I've inherited two Red Hat servers at work. I'm planning on moving them to CentOS to avoid licensing costs. Now, the licenses expired on october and I've received a Red Hat phone call to renew these licenses. They tell me this has to be solved. I don't know if take that as an threat of some kind.
Can Red Hat force me to buy new licenses? Can I still run Red Hat without the renewed licenses?
I know that now I can't update them, but they're very isolated from the Internet and other network computers, and I'm planning on move to CentOS anyway. So that's not to worry about. I'm worrying just about legal issues.
Comment: We don't handle licensing questions here because the legality varies from location to location and we're not lawyers. That said, I'd probably ignore them if I were in your situation and were migrating away.
Comment: @JorgeSuárezdeLis  Not really, no.  Just the nature of life that free licensing/legal advice on the internet is a minefield.
Comment: [Might want to read through the RedHat license agreement before doing anything, though - as you can see, it varies from country to country.](http://www.redhat.com/licenses/)
Comment: Thank you. Is there other, more suitable, StackExchange place to ask these licensing issues?
Answer: Yes they will still run fine. You just won't be able to get official updates from the redhat network anymore. Sounds like the sales guy is trying to strong arm you into a sale.


Bootstrap grid not displaying rows

Question: I am wanting to display images in a row for this portfolio, but they are displaying in a column. I can't seem to find anything that says I am doing this wrong. Any help with this?
Here is the code:

                Portfolio

                    <FontAwesomeIcon className="portfolio-icon" icon={faSearchPlus} />

            {/*-*/}

                    <FontAwesomeIcon className="portfolio-icon" icon={faSearchPlus} />

            {/*-*/}

                    <FontAwesomeIcon className="portfolio-icon" icon={faSearchPlus} />

            {/*-*/}

                    <FontAwesomeIcon className="portfolio-icon" icon={faSearchPlus} />

            {/*-*/}

                    <FontAwesomeIcon className="portfolio-icon" icon={faSearchPlus} />

Here is the CSS styling on the classNames. I am not sure what would make them not show as a row, but it may seem that some of my end tags may be messed up. It is difficult to tell.
.portfolio-image{
width: 15rem !important;
height: 8rem !important;
overflow: hidden;
border: 1px solid var(--primary-pink);
padding: 0 0.5rem;
}

.portfolio-image-box{
position: relative;
margin: 1rem;
overflow: hidden;
}

Answer: Please mention the CSS property you have applied on these className. Without these, it's difficult to find the issue.

I think the width of the inner div is set to 100%. Try to set the breakpoints and width of the image or the div.
Comment: I added the CSS to the post above, thank you, I will try setting the breakpoints and width of the image and will follow up.
Answer: Update: The className "portfolio-image-box" needs to be "portfolio-image-box col" to be recognized as apart of the grid.  This is because columns are expected to be in rows.

Bootstrap grid not displaying rows


Is there a function f(z) that satisfies a duality relation?

Question: Is there a function f(z) that satisfies the following duality relation?
$$tf(x)[(1+x)^2-f^2(t)(1-x)^2]=xf(t)[(1+t)^2-f^2(x)(1-t)^2]\ ?$$
Here $f(z)\neq 0$ and $1$.
Comment: You should include what you have tried so far.
Comment: There are at least two solutions which can be found rather quickly, so what have you tried?
Comment: I have tried it, but there is no progress.
Comment: Perhaps you are overthinking the problem because one solution is practically obvious.
Comment: Here $f(z)\neq 0$ and $1$. Have you found other solutions?
Comment: OK, you excluded $f(z)=0$ and $f(z)=1$ that leaves at least one other solution. Since you are using $z$ does that mean complex functions are allowed?
Comment: I hope that $f(z)$ is a real function not complex function.
Comment: Here is a hint to get you started: What do you know about $f(0)$?
Comment: $f(0)$ can  be arbitrary
Comment: What happens in the equation when you let $x=0$? This gives a clue.
Comment: So. We have $f^2(t)=1$.
Comment: So, can you now find a solution other than $f(z)=0$ or $f(z)=1$?
Comment: Thank you very much. It can only be a constant
Comment: At least it has a constant solution other than the two that are excluded.
Comment: I will leave you with one last hint: Let $c=f(-1)$ and try to find an equation for $f(t)$ in terms of $c$ and $t$.
Comment: Thank you. I have found a solution。
Comment: That's great. Usually one attacks this type of problem by finding the functional value of certain constants such $x=0, 1, -1$ etc to see if that gives you any hints about the function.
Answer: We are given that $f(t)\ne0$. Let $f(-1)=c$. Let $x=-1$.
Substituting into the equation gives
\begin{eqnarray}
tf(-1)[(0)^2-f^2(t)(2)^2]&=&-f(t)[(1+t)^2-f^2(-1)(1-t)^2]\\
-4ctf^2(t)&=&-f(t)[(1+t)^2-c^2(1-t)^2]\\
4ctf^2(t)-f(t)[(1+t)^2-c^2(1-t)^2]&=&0\\
4ctf(t)-[(1+t)^2-c^2(1-t)^2]&=&0\\
f(t)&=&\frac{(1+t)^2-c^2(1-t)^2}{4ct}
\end{eqnarray}
Which yields a solution for each $c\ne0$.


lp_solve ignoring trivial restrictions

Question: I made a really simple linear problem for lp_solve.
$ cat test.txt
max: 100X ;

X <= 0 ;

bin X ;

The right answer shall be that X has to be 0, as it is a binary variable and cannot be 1 due the restriction. However the result is:
$ lp_solve test.txt

Value of objective function: 100.00000000

Actual values of the variables:
X                               1

What explains this behaviour? I am doing something wrong? This also happens when alike restrictions are present on larger problems.
Comment: I think LpSolve is unhappy when all constraints are removed. Of course this is a bug: the solver should be able to return a valid solution also in the case when all constraints are presolved away.
Answer: Yes, when lp_solve does its preprocessing, it is eliminating your constraint altogether. Then the fact that X is binary kicks in and the Objective function is shown to be 100. (Incorrectly)
You can see that this is happening by running with the -stats flag:
./lp_solve -stat test.lp
Constraints: 0
Variables  : 1
Integers   : 1
Semi-cont  : 0
SOS        : 0
Non-zeros  : 0  density=nan%

The zero constraints and nan% density could be causing this unexpected behavior.
There a couple of workarounds for this.

If you eliminate the X bin; constraint altogether, it will solve it correctly and give you an objective value of 0.
Another 'hack-like' fix is to add a dummy variable to your trivial constraint. Now the entire constraint gets recorded by lp_solve.

For example, try to change your test.lp to be:
max: 100X ;

X  + x_dummy <= 0 ;

bin X ;

Which now gives the proper:
Constraints: 1
Variables  : 2
Integers   : 1
Semi-cont  : 0
SOS        : 0
Non-zeros  : 2  density=100.000000%

Hope that helps.

lp_solve ignoring trivial restrictions


Comparing differences between discrete variables in two datasets of unequal size

Question: I have two datasets, X, Y, containing discrete variables which both have a different number of instances. I want to analyse the difference between the datasets for each of these variables.
When these discrete variables are binary, I can use the Chi2 test (as suggested in Chi square test when sample sizes are different?) or Fishers Exact test (as in Compare means of two datasets of binary data). However, one of these discrete features isn't binary and I'm struggling to find a test for discrete variables where the datasets are of unequal length.
This discrete variable is ordinal and has values 0, 1 or 2. Maybe one approach could be to treat this as a continuous variable and use a non-parametric test for continuous distributions like Kolmogorov-Smirnov test, but this gives me suspiciously low p values (e.g. $1\times 10 ^{-60}$). Another approach might be to bin the variable by setting 1 to 0 or 2, and then use one of the above tests, but this would skew the data and lose information.
Is there an appropriate test for this situation?
Answer: While I was writing this question I found that the Mann-Whitney U rank test can be used here. According to the Wikipedia page, the test was originally developed under the asssumption of continuity but it can be used also on discrete ordinal data. Similarly the example given in SciPy's implementation of this test is used on discrete ordinal data.


Translating a word problem mathematically.

Question: I really hope I get my point across.
I want to translate the following into a mathematical statement:

suppose at time $t=0$, I have an amount $x(0)$ in the bank. At time $t$ I would like to make a payment, (depending on current status of my account) that cannot be more than $A$ and no less than $B$.

Is it possible to write it using $\max$ and $\min$ functions?
Thanks.
Answer: How about $\max(x,A) = A$ and $\min(x, B) = B$? You can also say $B \leq x \leq A$.


Should web apps be embedded in pages on websites?

Question: I'm new to web apps and trying to wrap my head around how they fit into a website, or if they entirely take the place of a website.
Currently I have a website that is simply a server that serves static HTML pages, with some JS embedded in. This works fine, but is kind of janky for more interactive components, where my JS is doing a lot of destroying and creating HTML elements dynamically. I would like to replace these pages of my website with web apps, which I can write in a more type-safe language (like Rust) that compiles to WebAssembly. Can I then embed this compiled web app on my website page?
Is this something regularly done in web development? I may be entirely getting the role of web apps wrong here, but it seems that this use case would be a good fit. If so, how would this normally be done? With a


how can i use pip search with my own nexus pypi repo?

Question: I deploy a nexus repo sys in my local area network, and I config a PyPI repo on it. I can use pip install to install package with my private mirror. But I cannot use pip search.
Here is my pip.ini
[global]
index-url = http://nexus.repo.com/repository/PyPI/simple
index = http://nexus.repo.com/repository/PyPI/pypi
trusted-host = nexus.repo.com

And when I use pip search it returns:

C:\Users\user>pip search redis
  HTTP error 404 while getting http://nexus.repo.com/repository/PyPI/pypi
  Exception:
  Traceback (most recent call last):
    File "c:\python27\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args)
    File "c:\python27\lib\site-packages\pip\commands\search.py", line 45, in run pypi_hits = self.search(query, options)
    File "c:\python27\lib\site-packages\pip\commands\search.py", line 62, in search hits = pypi.search({'name': query, 'summary': query}, 'or')
    File "c:\python27\lib\xmlrpclib.py", line 1243, in call return self.__send(self.__name, args)
    File "c:\python27\lib\xmlrpclib.py", line 1602, in __request verbose=self.__verbose
    File "c:\python27\lib\site-packages\pip\download.py", line 776, in request response.raise_for_status()
    File "c:\python27\lib\site-packages\pip_vendor\requests\models.py", line 862, in raise_for_status raise HTTPError(http_error_msg, response=self)
  HTTPError: 404 Client Error: Not Found for url:http://nexus.repo.com/repository/PyPI/pypi
      C:\Users\user>

I'm googling and googling, but coming up empty so far.
So here I am, hoping someone else can guide me through this.
thank you very much.
Comment: But you can install/download from that url? Try `pip download mypkg --index http://nexus.repo.com/repository/PyPI/pypi`, do you get the package downloaded? Also, what do you need `trusted-host` for if you don't use SSL anyway?
Comment: Yes, Dude. I can `pip download` and `pip install` from my repo, but I cannot `pip search` packages.
And I intend to use SSL after figured the problem. So I add trust host to configuration.
Answer: Try this:
pip search redis -i http://nexus.repo.com/repository/PyPI/pypi -vvv --trusted-host nexus.repo.com
I had the same problem, and found that I was basically searching with the /simple url, rather than the /pypi one (the /simple one works only for pip install)
Comment: already tried. but doesn't work for me.  i set config `index = http://nexus.repo.com/repository/PyPI/pypi` which means `pip search redis -i http://nexus.repo.com/repository/PyPI/pypi -vvv --trusted-host nexus.repo.com`. rigth?
Comment: This is working for me `pip search --index https://nexus.repo.com:8081/repository/my-pypi/pypi  --trusted-host nexus.repo.com:8081 my-package`
Answer: The problem for me was that I used the simple URL https://pypi.org/simple/ for the Remote Storage parameter when setting up the proxy repository instead of https://pypi.org/.
Answer: It looks like that this feature was deprecated for proxied repositories.

"pip search" command is deprecated and doesn't work with a proxy repository, but you can still search for packages in hosted repositories.


Able to ping two linux machines but cannot mount nfs share from one to another

Question: Okay so I'm new to all this stuff. I've never worked on Linux servers before. I have an Ubuntu server and Debian stretch ver 9. I installed nfs server on Ubuntu and nfs client on Debian. The machines are able to ping one another but the problem is that when I try to mount nfs share from Ubuntu to debian, it says
mount.nfs: connection timed out

The command I'm running on Debian is:
# mount <ip of Ubuntu>:/export/nfs /mnt/nfs

I created /mnt/nfs in Debian. Here, /export/nfs is the directory I created on Ubuntu and the ownership is nobody:nogroup. I also edited the /etc/exports and added the following in it:
/export/nfs <internal-network>/24(rw,insecure,all_squash).

I don't know what the problem is. Can someone please tell me what I am doing wrong?
Comment: Connection timed out would suggest the firewall.
Answer: Specify the host name of the ubuntu server before the : in your command.
For RedHat, but the idea is the same:
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/3/html/System_Administration_Guide/s1-nfs-mount.html
If the host name is myubuntu and share is /export/nfs then it should be mount myubuntu:/export/nfs not just mount :/export/nfs
Also, make sure you have iptables open and not blocking the ports.
Comment: did not answer the question, if you check OP he employed every detail you mentioned except you use hostname instead of IP.
Comment: @JonesG the question was edited after my answer and this information was added by a user other than the OP. I don't know why. The original post exactly what I described, which was the hostname/ip was missing. You can look at the edit history for details.
Answer: If the direcotry /mnt/nfs on the client machine doesn't exist already, create it first:
mkdir /mnt/nfs

It seems to be that you want to mount the share for longer time and not only temporary? If so, anothere location instead of /mnt would be preferable, because /mnt ist meant for temporary mounts - if not it's ok like that.
If you want to mount it fix, just add this lines to your /etc/fstab file:
Open the file with nano for example: nano /etc/fstab

<ip of Ubuntu>:/export/nfs/    /mnt/nfs    nfs    rw,sync,hard,intr    0    0

and enter the following command, to mount all entries from /etc/fstab
mount

Using ip or dns-name doesn't matter.
On the Server side, you have to reload the /etc/exports file whenever you edit it with the command exportfs -a
Also try to restart your nfs-server:
sudo /etc/init.d/nfs-kernel-server restart

If the systems aren't in the same subnet, check also if a external firewall is between them. With iptables -L you can check, if for a internal firewall on the systems, as well.
Answer: escalate privilege if need be using sudo prefix
$ mount -t nfs -o _netdev,rw,proto=tcp,sec=sys [serverip]:[location] [local mount point]

do not forget the underscore preceding netdev
_netdev is correct - will prevent from system from hanging if server is not online
example
$ mount -t nfs -o rw,_netdev,proto=tcp,sec=sys 10.10.2.1:/mnt/ZFS/PROXMOX/ /media/PROXMOX

Running mount -v (verbose) may give a clue
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Success Stories of "Statistics"?

Question: When it comes to Machine Learning, the successful application seem to be very well known. For example, Neural Networks have been successfully used to create Self Driving Cars and Game Playing Algorithms (e.g. Go, Chess).
When we think of classical statistical models such as regression model, it seems more difficult to think of equally well known and successful applications of such models.
I understand that this might be in part because Machine Learning might get more news/media attention and the problems in which Machine Learning tends to be applied in are in some ways easier to quantify success - e.g. does this neural network beat the world champion?. I also understand that Machine Learning itself is heavily rooted in statistics, e.g. PAC learnability.
But in terms of the classical statistical models such as regression, have their been any successful applications of these models on a similar scale to the successful applications of machine learning?
Thanks!
Comment: For a perspective that's perhaps more nuanced that the question implies: [Why games may not be the best benchmark for AI](https://venturebeat.com/uncategorized/why-games-may-not-be-the-best-benchmark-for-ai/). Self-driving cars are more of a hypothetical success since we actually don't have them.
Comment: There are countless examples in medical science that are on a bigger scale and more valuable to humanity than self driving cars and board games. For example all clinical trials.
Comment: (-1) "It seems more difficult to think of equally well known and successful applications of such models" appears to reflect no research at all.  Crack open any statistical textbook written in the last century for examples.  Maybe one could discuss the degree to which statistical applications are "well known," but that would not be on topic here on CV.
Comment: The contributions of machine learning are so miniscule when compared to the enormous contributions of statistics to scientific progress that one is tempted to think this could be a trick question.
Comment: All three answers posted so far (2022-08-12) give examples from distant past, long before Machine Learning was invented. It would be interesting to see current success stories. Re: clinical trials: This is a tautology. Clinical trials are required to use statistics. I wonder whether the situation would be different if ethics committees included Machine Learning experts.
Comment: @IgorF. Regulatory requirements mean proper legal regulation, not some software's requirement for users to change passwords periodically. If you learn anything about clinical trials it will quickly become obvious that regulatory requirements are important. Medical imaging uses statistics in many ways. Obviously medical imaging has been around longer than machine learning. has been popular.
Comment: I like the posting about how statistics helped win World War Two. For something more modern (and perhaps a better comparison to teaching cars how to drive themselves), I'd like to see an answer posted that discusses Pfizer's COVID-19 modeling. Another interesting medical topic could be networks and contract tracing (not just for COVID).
Comment: @IgorF. Where there are regulatory requirements, there are good reasons for them. There are many other medical fields, for example medical imaging, public health modeling.
Comment: @Oliver882 Re: "Where there are regulatory requirements, there are good reasons for them." Can you provide evidence (data!) for that claim? I offer a counterexample: The regulation, until five years ago, that required passwords to be changed periodically was actually harmful. Re: "medical imaging": Yes, exactly, that's where I'd like to see success stories from. I've heard of machine learning success stories in that field, but statistics?
Answer: The whole history of statistics is full of them. For example, $t$-tests were born in Guinness brewery as means of optimizing their processes:

T-Distribution, also known as Student's t-distribution, gets its name from William Sealy Gosset who first published it in English in 1908 in the scientific journal Biometrika using his pseudonym "Student" because his employer preferred staff to use pen names when publishing scientific papers instead of their real name, so he used the name "Student" to hide his identity. Gosset worked at the Guinness Brewery in Dublin, Ireland, and was interested in the problems of small samples – for example, the chemical properties of barley with small sample sizes.

Linear regression was discovered by Carl Friedrich Gauss to predict planetary movement in astronomy.
As about Poisson distribution...

A further practical application of this distribution was made by Ladislaus Bortkiewicz in 1898 when he was given the task of investigating the number of soldiers in the Prussian army killed accidentally by horse kicks;: 23-25  this experiment introduced the Poisson distribution to the field of reliability engineering.

Pierre-Simon Laplace applied Bayes theorem to estimate the mass of Saturn in the 1800s and his result was off just by 0.05%.
Everything in statistics was discovered for solving practical problems and they gained popularity because of proving useful.
Yes, it's not self-driving cars, but I doubt would have self-driving cars today if Gauss didn't do his research on the least squares in the 1800s. Every machine learning textbook mentions the Bayes theorem which was first studied by Thomas Bayes in the late 1700s. The examples are countless.
Answer: The German Tank Problem is a statistical approach to estimating a population size given a sample. The goal is to estimate the total number of items $N$, given a random sample of the population which has observable serial numbers from $1$ to $N$.
The problem is so named for its real-life application, in which Allied intelligence agencies wanted to estimate the number of German tanks being produced during World War II. By observing the serial numbers on a limited number of destroyed tanks, statisticians were able to infer the total number of tanks in the population with remarkable accuracy. Post-war analysis revealed that the statistical estimates were often superior to the estimates generated from conventional intelligence methods.
Other statistics developed during wartime include the Receiver Operator Characteristic (ROC) curve, which is a means of evaluating a classifier. WWII radar operators would have to classify radar blips as either enemy planes, or false alarms like birds or weather. The development of the ROC curve allowed a principled means of evaluating the performance of an individual radar operator, indicating whether they could correctly and reliably identify enemy aircraft, or if they would require further training. The ROC curve is used in many fields from medicine to meteorology to evaluate the performance of a classification method.
Comment: Particularly with this now being a community wiki, it might be best to post these as two distinct answers, one about the tanks and one about ROC curves for radar.
Answer: To add some medical examples to the excellent cases already cited by others:
Richard Doll established the link between smoking and lung cancer.  Although a medical doctor, the link was established using epidemiological techniques.
Florence Nightingale, the Lady of the Lamp.  The common perception is that she spent nights in hospitals during the Crimean War tending to wounded soldiers.  In fact, she spent her time compiling statistics that demonstrated that vastly more of deaths were caused by injury and disease rather than direct enemy action on the battle field.  One of the drawings she used to illustrate her point still bears her name: the Nightingale plot.  She was the first female member of the Royal Statistical Society.
John Snow identified the source of the Broad Street cholera outbreak in 1854.
The first generally recognised modern clincal trial was conducted by James Lind, a Royal Navy surgeon, who in 1747 established that lack of vitamin C was the cause of scurvy.  As a result of his work, the Royal Navy began to issue a daily ration of lemons to its sailors, thereby giving rise to the use of the (not very flattering in some quarters) soubriquet of "Limey" for Britons.
Answer: Success stories of statistics are everywhere. The reason that you don't see newspaper articles about statistical success stories is not because they rarely happen; it's because they happen so often that it's not considered news.
Some examples of successful applications of statistics are:

Every successful scientific study involving a large number of individuals or measurements
Every time an organization makes a good decision based on a large amount of data
Every time an instrument is correctly calibrated or tested by taking a large number of measurements
Every time someone makes a successful prediction about the future based on a large number of things that happened in the past

And there are millions of examples of each of these.
If you want to find a statistical success story in the news, look at any news article about any great achievement. Statistics plays a role in everything.
Comment: This is a good answer apart from the last paragraph, which is obviously not true.
Answer:
When we think of classical statistical models such as regression model, it seems more difficult to think of equally well known and successful applications of such models.

But in terms of the classical statistical models such as regression, have their been any successful applications of these models on a similar scale to the successful applications of machine learning?

Although there are many unsuccessful or wrong applications in science, I would say that science is for a large part a demonstration of successful applications.
To answer the question why classical models aren't often in the news, let's divide statistics in the inference and algorithmic viewpoints (Efron & Hastie, 2021) or, similarly, the prediction and explanation viewpoints (Yarkoni & Westfall, 2017).
Then, your machine learning examples all belong in the prediction category.
I think these obtain so much attention because they offer the basis for automated systems.
Even more so, they offer automated models which companies can use to earn money with, so they are incentivized to spend money on selling the models.
Conversely, successful applications of inference often do not mention the model; only the outcome.

Success Stories of "Statistics"?


Derivation of the posterior over topics in LDA

Question: When studying the latent Dirichlet allocation, I am not very clear about some procedures in their deriving equations. Please refer to the attached figure, how to understand those two steps, marked as 1 and 2 in the figure.
Answer: 1: denoting $z_{d,n} = A$, $w_{d,n} = B$ , $\theta_{d} = C$, $\beta_k = D$, and using the Bayes rule:
$\displaystyle p(A|B,C,D) = \frac{p(A|C,D) \ p(B|A,C,D)}{p(B|C,D)} \propto p(A|C,D)\  p(B|A,C,D)$,
where $\propto$ means it is proportional, which is the case because $p(B|C,D)$ does not depend on $A$ i.e. is a constant.
2: we can get knowing that both $p(z|\theta)$ and $p(w|z,\beta)$ are (presumably) discrete distributions, thus assigning fixed values $\theta_{d,k}$ and $\beta_{k, w_{d,n}}$.
Comment: I once heard that proportional will not affect sampling at all, and that's why it is frequently used in Bayesian statistics. How to understand that? Thanks.
Comment: I would say that if you are working with probability distributions, constant factors can be neglected since you can renormalize the distribution to sum up to 1.


Line Break After Dropdown in HTML

Question: I am trying to add a submit button after a dropdown list in an HTML form. I am unable to add a line break between the dropdown list and submit button. Attached is a Picture of the form. Below is the code I am using. Any help would be greatly appreciated.
<!DOCTYPE html>

        <form>

          <input required type="text" name="firstname" placeholder="First Name">

<input required type="text" name="lastname" placeholder="Last Name">

<input requiredtype="email" name="email" placeholder="Email">

<input required type="text" name="phonenumber" placeholder="Phone Number">

<input required type="text" name="handicap" placeholder="Handicap">

<select required name="shirtsize" size = 1>
            <option value="" selected>Shirt Size</option>
            <option value="S"> S </option>
            <option value="M"> M </option>
            <option value="L"> L </option>
            <option value="XL"> XL </option>
            <option value="XXL"> XXL </option>
            <option value="XXXL"> XXXL </option>
            <input type="submit" value=Register>

        </form>

Answer: Close the select and add a line break (
)

<select required name="shirtsize" size = 1>
  <option value="" selected>Shirt Size</option>
  <option value="S"> S </option>
  <option value="M"> M </option>
  <option value="L"> L </option>
  <option value="XL"> XL </option>
  <option value="XXL"> XXL </option>
  <option value="XXXL"> XXXL </option>
</select>

<input type="submit" value=Register>
Answer: @David is exactly right, I'd add a second line break though to keep the format similar to your picture.

<select required name="shirtsize" size = 1>
  <option value="" selected>Shirt Size</option>
  <option value="S"> S </option>
  <option value="M"> M </option>
  <option value="L"> L </option>
  <option value="XL"> XL </option>
  <option value="XXL"> XXL </option>
  <option value="XXXL"> XXXL </option>
</select>

<input type="submit" value=Register>
Comment: Awesome! Thank you both for the help!

Line Break After Dropdown in HTML


How to understand what a high p value indicates

Question: I am reading a research article and trying to interpret and report the results. The article is comparing gabapentin and estrogen for the treatment of hot flashes. There was no difference between gabapentin group and estrogen group change scores, t=0.53 and p=0.63. The alpha value set by the researcher was p<0.017. I know that with this p value I cannot rejected the null hypothesis. I am assuming that the null hypothesis is that there is no difference between the two groups? However, this does not necessarily mean that the null hypothesis is true. How do I report this? What is this p value telling me about the results? One of my references since that the p value is the probability that the obtained result is due to chance alone, how does this relate to these results?
Comment: You interpret the high p-value as saying that you have insufficient evidence to conclude that there is a difference between the groups. As for the definition, it is the probability of obtaining a more extreme result than the observed result, assuming that the null hypothesis is true.
Comment: @mkt it feels like you could just copy your comment into an answer, even if it is quite short.
Comment: To emphasize the last point made by @mkt: the p value does *not* represent "the probability that the obtained result is due to chance alone"
Comment: @Björn Fair point - I'm always a bit uncertain with short answers. I'll think about fleshing it out a bit more and turning it into an answer.
Comment: So if I understand this correctly, when comparing the gabapentin and estrogen groups I cannot say with confidence that there is a difference between the group scores. However, this does not necessarily mean that the null hypothesis is correct and there is no difference between the groups. This could be due to a chance sample error from a small sample size? Is this correct? Does the fact that the p value is so large mean anything? Does is mean more than if the p value was p = 0.16 which is still over the alpha?
Answer: P value is NOT "the probability that the obtained result is due to chance alone." A P value of 0.63 means that there is a 63% chance that if you accept the alternate hypothesis (Ha; that there is a difference) you will be mistakenly rejecting the null hypothesis (Ho; no difference). In other words you cannot say with confidence that there is a difference. Hypothesis testing will not allow you to "accept" the Ho. It is like in criminal court the defendant is found either guilty (reject Null), or not guilty (cannot reject Null); there is no finding of innocent (accept Null). If the study was powered adequately and you believe that finding a difference in effect would require such a high sample size as to not clinically significant you might say (in the discussion) that there is likely no difference, however no test can determine no difference (i.e. accept the Null).
Comment: I assume the unusual alpha is because of a multiple comparisons correction, such as Bonferroni. 0.017 is approximately 0.05/3
Comment: Also alpha of 0.017 is not standard. Most of the time alpha is 0.05.
Comment: A test for equivalence (difference of at most +- delta) is possible, but rarely used.
Comment: That is correct they did use the unusual alpha because of a multiple comparison correction.


How to create pages with images in the content?

Question: I'm trying to create a page with content that looks like this:

I'm using CKEditor to edit the content, and it allows me to add images to the article. However, the images need to be already present at some URL.
Is there a way I can upload an image (the image of the doctor with a pad) to my drupal site separately, and then use its URL to insert the image in my article?
In other words, how do I upload just an image to my drupal site so that it can be used elsewhere?
Comment: possible duplicate of [give node author ability to position the image when uploading content](http://drupal.stackexchange.com/questions/73706/give-node-author-ability-to-position-the-image-when-uploading-content)
Answer: You should do something like this.
Have two regions, one with the content (ie the left blurry blob). And one called sidebar. The sidebar region would have a block that you would add the right image. And a block (which I assume would be something like a view or maybe it's manually added) to do the Related Links.
Then you could have a content header region for the top part.
So you would end up with
<code>|  Content Header  |
| Content | Sidebar|
</code>
Or at least that is how I would do it.
Answer: You could just install the IMCE module, which will allow you to upload images and insert them into CKEditor/WYSIWYG fields. You can use the IMCE module regardless of whether you want to insert the image into your content node directly or make a separate block.


set hour, minute and seconds to exact numbers in sql

Question: I am populating my databae with dummy information for testing purposes, thanks to http://mitchelsellers.com/blogs/2008/09/12/creating-random-sql-server-test-data.aspx And it is working, however my date is randomized and get random years/months but allways the current time, a few examples exctracted from my database:
2017-05-30 16:41:53.190
2017-07-21 16:41:53.193
2016-04-23 16:41:53.193

however my application using these dates must have them in the form of
2017-05-30 16:00:00.000
2017-07-21 01:30:00.000
2016-04-23 04:45:00.000

In other words the date is currently fine, but the minute should be on of 00,15,30,45 and seconds and miliseconds should allways be 00.
Any way to add random times on the format above to my sql?
My current SQL logic is as follows:
DECLARE @RowCount INT
DECLARE @RowString VARCHAR(10)
DECLARE @Random INT
DECLARE @Upper INT
DECLARE @Lower INT
DECLARE @InsertDate DATETIME
DECLAre @LoopThisManyTimes INT

SET @Lower = -360 /* move 360 days backwards */
SET @Upper = 360 /*  move 360 days forward */
SET @RowCount = 0 /* start the counter at 0 */
SET @LoopThisManyTimes = 10 /* set the number of posts to add */

USE [Scheduler]
TRUNCATE TABLE [dbo].[Appointments] /* clear table for testing purposes */
WHILE @RowCount < @LoopThisManyTimes /*loop and add to table */
BEGIN
SET @RowString = CAST(@RowCount AS VARCHAR(10))
    SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
    SET @InsertDate = DATEADD(dd, @Random, GETDATE())

Answer: Just do the calculation in seconds rather than days.  Here is one way:
WHILE @RowCount < @LoopThisManyTimes /*loop and add to table */
BEGIN
    SET @RowString = CAST(@RowCount AS VARCHAR(10));
    SELECT @Random = ROUND(((@Upper - @Lower -1)*60*60*24 * RAND() + @Lower*60*60*24), 0);
    SET @InsertDate = DATEADD(second, @Random, GETDATE());
END;

EDIT:
If you want fixed minutes:
WHILE @RowCount < @LoopThisManyTimes /*loop and add to table */
BEGIN
    SET @RowString = CAST(@RowCount AS VARCHAR(10));
    SELECT @Random = ROUND(((@Upper - @Lower -1)*4*24 * RAND() + @Lower*4*24), 0);
    SET @InsertDate = DATEADD(minute, @Random*15, CAST(GETDATE() as DATE));
END;

I think that arithmetic is right.
Comment: So close now, excellent answer, now I got random timestrokes but i need minutes to allways be 00, 15, 30 or 45 and second + milisecond allways 00 and 000 respectivly. A great start in the right direction, thanks.
Comment: @darrrrUC: Change `60*60*24` to `60/15*60*24` and the `DATEADD` to `(second, CAST(@Random*15 AS INTEGER), GETDATE())` to get 15 second increments
Comment: They are still not rounded :)
Comment: @darrrrUC Yep, you need to cast first: `CAST(@Random AS INTEGER) *15`


References for quasi finite and proper implies finite

Question: Does anybody know a reference for a proof of:
Let $f: X \rightarrow Y$ be a quasi-finite proper morphism of varieties. Then $f$ is finite.
Is there one in Hartshorne? I could not find it.
Thanks!
Comment: An overkill proof via ZMT: By the Grothendieck version of Zariski's main theorem, $f$ is the composition of an open embedding $g: X\rightarrow Z$ and a finite morphism $h:Z\rightarrow Y$. Then, $g$ is the composition of the graph morphism $X \rightarrow X\times_Y Z$ and the projection $X\times_Y Z \rightarrow Z.$ The first is a base-change of the morphism $Z \rightarrow Z\times_Y Z$, which is a closed embedding and thus proper, and the second is a base change of $f$, and thus proper. Therefore, $g$ is proper and thus an isomorphism (as the image must be both closed and open.)
Comment: Your question is only the "second thing" in the title.
Comment: @QiL, oops, found a reference for the first thing while typing and forgot to change the title, thanks.
Comment: @Nehsb, why don't you post this as an answer?
Answer: The proof is in ÉGA IV 3. It is in two steps.
Step I : reduce to the case of $\mathrm Y = \mathrm{Spec}(\mathrm A)$ where $\mathrm A$ is a complete noetherian local ring.
Step II : quasi-finite $\mathfrak m_{\mathrm A}$-seperated modules are finite for such an $\mathrm A$.
Answer: I think this is just a generalization of the fact that finite integral extensions of domains are finitely generated module over the lower integral domain.
Anyway if you need a reference/proof to the statement in your post, you can cite Lemma 02OG of the stacks project.


Show that two anti derivatives differ by a constant

Question: Today in Calc, we stumbled upon two anti derivatives (2 students had different approaches which we worked out) which are:
$$
\ln \left| \frac{\sin x - 1 - \cos x + \sqrt 2 + \sqrt 2 \cos x}{\sin x - 1 - \cos x - \sqrt 2 - \sqrt 2 \cos x} \right|
$$
and
$$
\ln \left| \frac{2 - \sqrt 2 \cos x + \sqrt 2 \sin x}{\sqrt 2 \sin x + \sqrt 2 \cos x} \right|.
$$
It turns out (fortunately) they they only differ by a constant, which according to the TI is approximately $0.88137358$ after taking the difference of their graphs. But to show algebraically that they are equal, I tried several approaches, but failed. Also, I am interested what that constant in exact terms would be. Jokingly, I told my students to do this for homework as we ran out of time, but honestly this one stumps me too. So please, any suggestions from you great thinkers out there?
Comment: Well, the constant is $\ln(\sqrt 2) +1$ (let $x=\pi/2$) ...
Comment: Please post the integral.
Comment: @SammyBlack, it is the integral of $\frac{1}{sinx+cosx}$  One student did it with the tangent half angle formula (weierstrass subs) the other student wrote the denom as $sin(x+pi/4)$ with a radical factor up front. The latter is a standard anti derivative. In my post both anti derivatives have that same coefficient up front, so that matches. It's the ln terms what is the issue
Comment: @DavidMitra your brackets are wrong, but you got that correct after playing around with your answer: $ln(1+\sqrt2)$ THANKS!!!
Comment: Oh, yes. Sorry.
Answer: If we assume that both results are correct, then we just need to evaluate the following difference at a particular value of $x$.
\begin{eqnarray*}
C &=&\ln \left\vert \frac{2-\sqrt{2}\cos x+\sqrt{2}\sin x}{\sqrt{2}\sin x+
\sqrt{2}\cos x}\right\vert  \\
&&-\ln \left\vert \frac{\sin x-1-\cos x+\sqrt{2}+\sqrt{2}\cos x}{\sin
x-1-\cos x-\sqrt{2}-\sqrt{2}\cos x}\right\vert  \\
&=&\ln \left\vert \frac{2-\sqrt{2}\cos x+\sqrt{2}\sin x}{\sqrt{2}\sin x+
\sqrt{2}\cos x}\left( \frac{\sin x-1-\cos x+\sqrt{2}+\sqrt{2}\cos x}{\sin
x-1-\cos x-\sqrt{2}-\sqrt{2}\cos x}\right) ^{-1}\right\vert .
\end{eqnarray*}
For $x=0$ we find $C=\ln |- \left( \sqrt{2}+1\right)|=\ln \left( \sqrt{2}+1\right).$
If we want to prove that the two antiderivatives differ by a constant, then we can express $\sin x$ and $\tan x$ in terms of $t=\tan \frac{x}{2}$ to obtain a rational function in $t$, which we will then simplify until we get a constant. Since
\begin{eqnarray*}
\sin x &=&\frac{2\tan \frac{x}{2}}{1+\tan ^{2}\frac{x}{2}}=\frac{2t}{1+t^{2}}
\\
\cos x &=&\frac{1-\tan ^{2}\frac{x}{2}}{1+\tan ^{2}\frac{x}{2}}=\frac{1-t^{2}
}{1+t^{2}},
\end{eqnarray*}
we have that
\begin{eqnarray*}
C &=&\ln \left\vert \frac{\left( 2-\sqrt{2}\frac{1-t^{2}}{1+t^{2}}+2\sqrt{2}
\frac{t}{1+t^{2}}\right) \left( 2\frac{t}{1+t^{2}}-1-\frac{1-t^{2}}{1+t^{2}}-
\sqrt{2}-\sqrt{2}\frac{1-t^{2}}{1+t^{2}}\right) }{\left( 2\sqrt{2}\frac{t}{
1+t^{2}}+\sqrt{2}\frac{1-t^{2}}{1+t^{2}}\right) \left( 2\frac{t}{1+t^{2}}-1-
\frac{1-t^{2}}{1+t^{2}}+\sqrt{2}+\sqrt{2}\frac{1-t^{2}}{1+t^{2}}\right) }
\right\vert  \\
&=&\ln \left\vert \frac{-\frac{\sqrt{2}}{2}\left( t-1-\sqrt{2}\right) \left(
2+\sqrt{2}\right) \left( t+\sqrt{2}-1\right) ^{2}}{\left( t-1+\sqrt{2}
\right) \left( -2t-1+t^{2}\right) }\right\vert  \\
&=&\ln \left\vert \frac{-\frac{\sqrt{2}}{2}\left( 2+\sqrt{2}\right) \left(
-2t-1+t^{2}\right) }{\left( -2t-1+t^{2}\right) }\right\vert  \\
&=&\ln \left\vert -\left( \sqrt{2}+1\right) \right\vert  \\
&=&\ln \left( \sqrt{2}+1\right) .
\end{eqnarray*}
Comment: Thanks, this looks nice. We know that the two anti derivatives are OK because we graphed it and took the difference of the graphs. It is a constant which turns out to be the one stated earlier. We then went into the trig mode and trying to prove one anti derivative into the other, meaning working with one trig expression and converting it into the other. That turned out to be nearly impossible. But your approach by subtracting the natural logs (and getting a constant) is certainly a worthwile approach.
Comment: @imranfat You are welcome. The use of the tangent half angle formulae simplified the computation very much.


Rodar uma instrução no mysql de calculo de data de nascimento e atualizar a coluna idade

Question: Tenho uma coluna chamada data_nasc e outra coluna idade, porém queria que toda vez que o sistema carregasse rodasse essa instrução dentro do MySQL e atualizasse o campo idade de todos os registros.
Até aqui funciona, porém o resultado sai na coluna temporária ColunaCalculoIdade, quero que o resultado atualizar os campo da coluna idade
SELECT        TIMESTAMPDIFF(YEAR, data_nasc, CURRENT_DATE) AS ColunaCalculoIdade
FROM            clientes

Comment: por que não cria uma coluna computada que já vai calcular isso pra vc? eu comentei sobre isso nessa pergunta: https://pt.stackoverflow.com/questions/514534/para-que-serve-a-estrutura-de-dados-virtual-no-dbeaver-ou-no-mysql/516720#516720
Comment: lembre que só gravar na hora de incluir vai ter a idade naquele instante, no dia seguinte pode já estar desatualizado, uma coluna computada vai sempre calcular no instante da consulta :)
Comment: Normalmente não se grava idade no banco de dados. Só a data de nascimento já é suficiente para deduzir a idade.
Comment: Andei olhando a coluna computada, ainda muito complicada para um iniciante, o que quero é que quando abra o Form de cadastro o usuário faça uma consulta por idade e apareça os cadastros com a idade pesquisada ou quanto rodar o relatorio a idade ja vai atualizada, o máximo que consegui é fazer o codigo acima.
Comment: ja tentei usar assim:
**UPDATE clientes SET idade= SELECT  TIMESTAMPDIFF(YEAR, data_nasc, CURRENT_DATE) AS ColunaCalculoIdade FROM clientes**
Só queria que o resultado de calculo da data de nascimento atualizasse minha coluna idade.
Answer: Resolvi da seguinte fomra:
Coloquei um evento para rodar 24 HORAS POR DIA
CREATE DEFINER=root@localhost EVENT CalculoIdade ON SCHEDULE EVERY 24 HOUR STARTS '2021-07-17 00:00:01' ON COMPLETION PRESERVE ENABLE DO UPDATE clientes SET idade = TIMESTAMPDIFF(YEAR, data_nasc, CURRENT_DATE)


Conceptual: Reselling ISP services (vISP?)

Question: Hello I am trying to understand how some "wifi"/vISP companies work. I do hope this is the appropriate forum/site for my question. I'll start with an example:
Lets say you are at an airport and there is wifi available. However in order to use this wifi you must pay ($5 an hour) to use it. Lets say this company also supplies the same services at the local coffee shops as well: Wifi at the cost of $5/hr.
What is this company doing? Are they buying internet access through an ISP (ie Comcast) and just throwing a wireless router on it and selling the password at $5/hr. Or are they buying the internet through a cheaper rate via wholesale ISP and reselling it as there own, I believe this is called a vISP?
If it is the vISP route (and if I am understanding the vISP concept correctly), how do they deliver the internet access to the airport and coffee shops, do they pay the original ISP to lay the wires from the backbound to the desired locations, or are they just renting backbound real estate from the original ISP company and buying their own cables/laying the foundation for those locations (airport, coffe shop)? Basically who is supplying the modem.
Thank you for your time,
John
Answer: I am not sure how all of them work, but in Ireland, there is a company called BitBuzz who install a broadband line into the premisis and then run their service from that. the company who gets the connection from them also gets a broadband connection for their own use. More details are available at their connect site.
There are also smaller providers, like Fon who give you a device to plug into your own broadband connection.
So, in reality, it depends on the provider. Some could use a standard off the shelf internet connection, others may resell the connection thats already there... Hope this helps...
Comment: so BitBuzz is an ISP correct? Or are they really just using another ISP as a provider and re marketing themselves as an ISP. It is difficult for me to understand. From what I believe: to become an ISP it takes a serious amount of upfront capital to create such a vast infrastructure - which these WiFi providers do not seem to be capable of.
Comment: It depends on how you define ISP... ISP is someone who provides an internet connection. Technically speaking, in my home, i am an ISP to my Sister and to anyone else using the Wifi... Larger ISPs need to run cables, own datacenters, etc, but smaller ones can rent a lot of stuff from an upstream provider. In reality, BitBuzz are an ISP, since they provide me with internet connectivity in some areas of Ireland. they do have their own Infrastructure, but a lot of it is piggybacking on other providers (Eircom, for example, are mostly used for broadband, from what i have seen).


Can a goalkeeper use his/her hands within the opponents penalty area?

Question: The Wikipedia article on goalkeepers states that:

The goalkeeper is the only player in the side who may use his or her hands and arms to catch, throw and save the ball, but only within the penalty area.

(boldface added, I'v edited the wiki page to solve the ambiguity)
It is however not clear to me whether the goalkeeper can only use his/her hands within the penalty area of his/her team or is he/she allowed to use his/her hands within the penalty area of the opponents team as well.
Sometimes goalkeepers effectively cross the field for instance to assist the team in a final corner, etc. I am wondering if the goalkeeper would be allowed to use his hands (for instance to catch the ball and throw it to the opponents goal?
Can someone provide a reference whether this is allowed?
Answer: In the Laws of the Game, Law 12 - Fouls and Misconduct says the following (emphasis mine on first bullet):

A direct free kick is awarded if a player commits any of the following offences:

handles the ball deliberately (except for the goalkeeper within their penalty area)
Holds an opponent
impedes an opponent with contact
spits at an opponent

In your scenario, the goalkeeper would not be in their own penalty area, but the penalty area of the other team. It would be a foul and the defending team would get a direct free kick.
Comment: Apologies - I hadn't realized I had linked to the 2011 version. I've updated my link!
Answer: As has been pointed out, the goalkeeper may only deliberately handle the ball within their own penalty area.
Furthermore, if the goalkeeper attempts to score a goal with their hands in the opponents' penalty area - as is likely in the scenario you have posed - not only would a direct free kick be awarded, but the goalkeeper would also be cautioned (shown the yellow card) for unsporting behaviour.
From the 2016/17 Laws of the Game - 12.3 Disciplinary Action:

There are different circumstances when a player must be cautioned for unsporting behaviour including if a player:
...

handles the ball in an attempt to score a goal (whether or not the attempt is successful) or in an unsuccessful attempt to prevent a goal


Ubuntu SSH connections don't close

Question: We have a connection to one of our servers from an external party. This party logs in using sftp and uploads some files. The sessions are not closed by that party and they don't know how to get that done (it's a Windows server and appearantly the scripts they are using do not support it).
Now the server crashed last week because it was low in memory. After some searching I found out there were 2500 SSH connections (some a couple of months old). Each taking up just a little bit of memory, but together it crashed the server. I killed them all and now it is running smoothly.
How can I prevent this from happening again? I would like to have all sessions be killed after a couple of hours. Is that possible from the server side or should I create a script for that myself?
There has a lot been written about SSH timeouts, but all solutions are client side.
EDIT: For now I have created this script which runs every night:
        count=$(ps aux | grep [USERNAME] | wc -l)
        echo "Found $count processes";
<code>    for i in $(seq $count)
    do
        echo "kill $i"
        kill -9 $(ps aux | grep [USERNAME] | grep -v grep | head  -n 1 | tr -s ' ' | cut -f 2 -d ' ')
    done
    service ssh restart
</code>
You need to replace [USERNAME] with the logged in user. It will kill all processes of this user, but in my case there are only SSH connections running for this user.
Answer: Edit your SSH Server's config file to include
<code>ClientAliveInterval 600
ClientAliveCountMax 0
</code>
This will disconnect all idle clients after 10 minutes (600 seconds).
Quoting the manual:

ClientAliveCountMax
Sets the number of client alive messages (see below) which may be sent without sshd(8) receiving any messages back from the client. If
this threshold is reached while client alive messages are being sent,
sshd will disconnect the client, terminating the session. [...]
The default value is 3. If ClientAliveInterval (see below) is set to 15, and ClientAliveCountMax is left at the default, unresponsive
SSH clients will be disconnected after approximately 45 seconds. This
option applies to protocol version 2 only.
ClientAliveInterval
Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) will send a message through the
encrypted channel to request a response from the client. The default
is 0, indicating that these messages will not be sent to the client.
This option applies to protocol version 2 only.

Ubuntu SSH connections don't close


Converting VBA code to google sheets script for auto sort

Question: I am looking for assistance on a script for google sheets for an auto sort function that runs when I update the sheet with new information. The sheet name is "Summary All Events". I have data starting in Row 4, Columns A:J. I would like to auto sort any data from A4:J1000 by column 1 (A) in ascending order. Can anyone help me?
Here is the script I am running in VBA for Excel. But now I need to convert it into a script for Google Sheets.
Public Sub Worksheet_Change(ByVal Target As Excel.Range)

If Target.Column = 1 Then

    Dim lastRow As Long
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    Range("A4:J" & lastRow).Sort Key1:=Range("A4:A" & lastRow), Order1:=xlAscending, Header:=xlNo

End If

End Sub

Answer: Try the following code:
function onEdit(e) {
  var sheet = e.source.getActiveSheet();
  if (sheet.getName() == 'Sheet1') {
    var r = e.range;
    if (r.columnStart == 1 && r.rowStart >= 4)
      sheet.getRange('A4:J').sort({column:1,ascending:true});
  }
};

Now, whenever any user will edit any cell in range "A4:A", the above code will auto sort the range A4:J by column A in ascending order.


JOIN no BigQuery

Question: Preciso fazer a consulta a seguir, porém o BigQuery apresenta erro: Name CNPJ_radical not found inside A at [3:6]
Por que não consigo chamar o alias no ON do JOIN?
SELECT FORMAT(LPAD(A.CNPJ,8,'0')) as CNPJ_radical, A.DEBITO , A.CCF , A.PROTESTO , A.QTD, A.FLAG_RESTRICAO, B.porte
FROM `analytics-eda-0186.qualidade_de_dados.FLAG_RESTRICAO_PJ_202010` as A
INNER JOIN `data-3660.dados_views.v_TB_DADOS_ABERTOS_CNPJ_MES10`as B
ON A.CNPJ_radical = substr(B.numero_de_inscricao , 1 , 8)

Comment: Porque o filtro ocorre antes do `SELECT`. Logo seu campo `CNPJ_rapical` só é computado após a busca dos dados filtrados pelo SGBD.
Answer: O Bigquery até onde eu sei não "entende" o alias. Então é só você repetir a função no ON assim:
SELECT
    FORMAT(LPAD(A.CNPJ,8,'0')) as CNPJ_radical,
    A.DEBITO ,
    A.CCF ,
    A.PROTESTO ,
    A.QTD,
    A.FLAG_RESTRICAO,
    B.porte

FROM `analytics-eda-0186.qualidade_de_dados.FLAG_RESTRICAO_PJ_202010` as A
    INNER JOIN `data-3660.dados_views.v_TB_DADOS_ABERTOS_CNPJ_MES10`as B
        ON FORMAT(LPAD(A.CNPJ,8,'0')) = substr(B.numero_de_inscricao , 1 , 8)

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

JOIN no BigQuery


URI for actions of services

Question: I have defined the following service.
'salesforce_subscriptions' => array(
    'operations' => array(
      'delete' => array(
        'help' => 'Remove subscriptions from SalesForce',
        ...
        'args' => array(
          array(
            'name' => 'ids',
            'type' => 'string',
            'description' => '',
            'source' => array('param' => 'ids'),
            'optional' => FALSE,
          ),
          array(
            'name' => 'API key',
            'optional' => FALSE,
            'type' => 'string',
            'description' => 'The api key',
            'source' => array('param' => 'api_key'),
          ),
        )
      )
    ),

How can I access this?
The endpoint of the service is: endpoint.
I can access the index service by:
www.example.com/endpoint/salesforce_subscriptions
How can I access delete?
Comment: I would guess www.example.com/endpoint/salesforce_subscriptions/delete.json
Answer: You should be able to access it via
www.example.com/endpoint/salesforce_subscriptions/[ids]/delete

If that doesn't work, you may need to experiment with the id parameter source, e.g path argument vs param
For more info and example, see the node resource definition here:
_node_resource_definition

URI for actions of services


Conditioning uniform distribution on subset of support gives uniform distribution

Question: $\newcommand{\vZ}{\boldsymbol{\mathbf{Z}}}$I am reading this paper regarding a simple proof of why rejection sampling works. I managed to understand the proof of Lemma 1, but I am struggling with the other two. The second lemma says:

Suppose the $m$-dimensional random variable $\mathbf{Z}$ has a uniform distribution in $A\subset\mathbb{R}^m$, where $0<V(A)<\infty$. Let $B\subset A, V(B) > 0$. Then the conditional distribution of $\mathbf{Z}$, given $\mathbf{Z}\in B$ is uniform in $B$.

The author says the proof is obvious, but I don't see how. Here is my attempt:
Proof
First of all, $\vZ$ has a uniform distribution on $A$ means
$$
\newcommand{\vZ}{\boldsymbol{\mathbf{Z}}}
\begin{equation}
p(\vZ) =
\begin{cases}
\frac{1}{V(A)} & \text{if } \vZ\in A\\
0 & \text{otherwise}
\end{cases}
\end{equation}
$$
Now we want to find the conditional distribution of $\vZ$ given that $\vZ\in B$.
$$
\begin{align}
    p(\vZ\mid \vZ\in B) = \frac{p(\vZ, \vZ\in B)}{p(\vZ\in B)}
\end{align}
$$
We can find the denominator as
$$p(\vZ\in B) = \int_B p(\vZ) dA = \int_B \frac{1}{V(A)} dA = \frac{1}{V(A)}\int_B dA = \frac{V(B)}{V(A)}$$
At this point, I only need to find an expression for the numerator, however I since we know $\vZ\in B$, then certainly
$$p(\vZ, \vZ\in B) = p(\vZ\in B) = \frac{V(B)}{V(A)}$$
so that we get
$$p(\vZ \mid \vZ\in B) = \frac{V(B)}{V(A)} \times \frac{V(A)}{V(B)} = 1$$
However this is not the definition of being uniform in $B$. We should rather obtain something like:
$$
\begin{equation}
p(\vZ\mid \vZ\in B) =
\begin{cases}
\frac{1}{V(B)} & \text{if } \vZ\in B\\
0 & \text{otherwise}
\end{cases}
\end{equation}
$$
Comment: the key error is in the line $p(Z, Z\in B) = p(Z\in B)$.  The RHS is certainly a probability, but the LHS is not.  (Or, as a probability, its value is $0$.)  PDFs can be tricky because they are not probabilities, but rather, densities.  See if [this wikipedia article](https://en.wikipedia.org/wiki/Conditional_probability_distribution) helps...
Comment: Do you mind telling me how I should change it?
Answer: Here is an equivalent definition of being uniformly distributed:

$Z$ is uniform on $A$ if for any (measurable) subset $E\subset A$,  $$P(Z\in E)=V(E)/V(A).$$

To verify that $Z$ conditioned on $Z\in B$ is uniform on $B$, it therefore suffices to show that for any measurable $E\subset B$, that $P(Z\in E|Z\in B)=V(E)/V(B)$. Now
$$
P(Z\in E|Z\in B)=\frac{P(Z\in E\cap Z\in B)}{P(Z\in B)}=\frac{P(Z\in E)}{P(Z\in B)}=\frac{V(E)/V(A)}{V(B)/V(A)}=\frac{V(E)}{V(B)}.
$$


How to restrict field formatter to selected fields?

Question: I created new field field_csob_srcode in my custom code:
<?php
$field = array(
'field_name' => 'field_csob_srcode',
'type' => 'text',
'settings' => array(
  'max_length' => 4,
),
  );
 field_create_field($field);
?>

I would need to create custom formatter for this field. I am using such implementation of hook_field_formatter_info
<?php
function mymodule_field_formatter_info() {
  $info = array(
'csob_webpay_description' => array(
  'label' => t('SRCODE - text description'),
  'field types' => array('text'),
  'description' => t('Displays text description of message from CSOB GP     WebPay'),
),
  );
return $info;
}

It works ok, but now, I see my new formatter as option at all fields settings, which have type = 'text'. Is it possible to restrict using of formatter, not only by field type, but also by field?
When I try to set field in hook_field_formatter_info:
'field types' => array('field_csob_srcode'),

then it does not work, formatter disappears from options in field display settings.
EDIT:  I have not problem to set formatter for my field, I just need to restrict formatter ONLY for my field. So other text fields cannot use my formatter. So the formatter will not appear as option in selectbox, when selecting format for display
Comment: If memory serves correctly there's no such option, which means you're left with altering the manage fields form manually. Shouldn't be too tricky to do though
Answer: Use default formatter in your field implemention
$field = array(
  'field_name' => 'field_csob_srcode',
  'type' => 'text',
  'settings' => array(
  'max_length' => 4,
  ),
  'default_formater' => 'csob_webpay_description',
);

it should works.
Comment: Thanks, but this does not work for me. I have not problem to set formatter for my field, I just need to restrict formatter ONLY for my field. So other text fields cannot use my formatter. So the formatter will not appear as option in selectbox, when selecting format for display.
Comment: Have you implemented hook_field_info() ?
Comment: No, but as I understand, I can create field also with method field_create_field($field), then I do't need hook_field_info. Or am I wrong?
Comment: If you want to relate your widget only to your own custom field you should introduce your field to drupal as a field type , this is done using hook_field_info .


Failed adding to JNI local ref table (has 512 entries)

Question: I am working in an android application and I am getting an error "dalvikvm(11625): Failed adding to JNI local ref table (has 512 entries)" when I try to run my application on certain devices. Please help me to rectify the error.
Thanks in advance
Answer: You may have lots of objects allocated in jni but not released
or, NewGlobalRef no corresponding DeleteGlobalRef
Comment: Can you please explain. I am having an assets folder with so many png files and a sqllight database in it.Is this the reason ?
Comment: It is irrelevant to your asset files. Try read your source code to find those places you allocate a new jni object. Then see if you have corresponding release on the object. If you can share part of the source code, it will be more helpful


Just a simple thing about windowsTitle change background in Java

Question: i wan't to do a simple thing, my background's windowTitle must change in my application. But how i can access to my background's windowTitle ?
My style.xml :
<resources>

</resources>

And in my Activity :
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.page_doc);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);

How i can do this ?
Answer: try to use this
((TextView)((FrameLayout)((LinearLayout)((ViewGroup) activity.getWindow().getDecorView()).getChildAt(0)).getChildAt(0)).getChildAt(0)).setBackgroundResource(R.drawable.back);

Comment: I tried this :

     RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayoutWindowTitle);
        rl.setBackgroundResource(R.drawable.fond_doc);
Answer: You can just use the ids of the window_title layout. Just like you would do with normal layout.
I assume that you have something like a LinearLayout in your window_title layout. Just use the id of it to get it and set the background Drawable.


WSO2 BRS Stateful sessions

Question: One of the posts on WSO2.com suggests that you can use stateful sessions with Drools in WSO2 BRS. However, all the examples, as far as I can see, use stateless access to a single implicit stateless session.
Can anyone tell me how to configure WSO2 BRS to access more advanced Drools usage and direct service calls to the right sessions, control firing of rules etc ?
Comment: If usage within WSO2 doesn't narrow this question down considerably, this "Can anyone tell..." covers about anything there is in Drools which would result in a 100 page plus answer.
Comment: To be clear, it's really the way WSO2 wraps Drools that I'm asking about. So it's not clear to me how in the WSO2 BRS you can gain more fine control of Drools execution. My best guess is that is in the content of the .rsl file that describes the service, however I can't find a full description of what that file can contain.
Comment: I'm beginning to think that this is being managed through stateful AXIS2 services - so that the Drools session, is in effect, always stateful.
Answer: Adding some information even though this question is much older because may helpful to others.
The WSO2 BRS wraps the Drools engine and provide ability to expose set of rules (in several .drl file) and decision tables as axis2 service (lets say rule services).
In BRS you can create stateful and stateless rule session. The stateful sessions are bound to axis2 session (trasport session, soap session, Application session). You can find statful rule session samples in [1]
The service is described in .rsl file. Refer [2] for more information.
[1] https://docs.wso2.com/display/BRS220/Banking+Service
[2] https://docs.wso2.com/display/BRS220/Creating+and+Deploying+the+Rule+Service

WSO2 BRS Stateful sessions


Find an element of $SO(1,2)$ such that is not diagonalisable in $\mathbb{C}$

Question: I am starting to work with Lie Groups and I was given the following exercise:

Find an example of $A$ be a $3 \times 3$ matrix with real coefficients such that preserves a inner
product with signature $(1,2)$ such that $A$ is not diagonalisable.

My thoughts:
Characterising the whole $SO(1,2)$ by hand seems to be an complicated approach, as it is a nonlinear system with 9 variables. I suppose it could be done but does not seem to be very enlightening.
As any matrix in $\mathbb{C}$ has a Jordan form, I thought it was a good place to start. So I tried to compute what Jordan forms could be in $SO(1,2)$. Turns out that none of then do (beside the diagonal ones). The thing is that $SO(1,2)$ is not closed by conjugations of invertible matrices.
I know that would be easy to disprove in the case we were talking about $SO(n)$, but the signature changes everything.
Answer: A good approach is using a theorem due to Witt:

Lemma: Let $k$ be a field and $\operatorname{char}k\ne 2$. Let $\phi$ be a non-degenerate symmetric bilinear map $\phi:k^n\times k^n\to k$, let $W$ be a subspace of $k^n$ and let $A:W\to k^n$ be an injective map such that $\phi(Aw,Av)=\phi(w,v)$ for all $w,v\in W$. Then, there is a (necessarily injective) map $\widetilde A:k^n\to k^n$ such that $\phi\left(\widetilde Ax,\widetilde Ay\right)=\phi(x,y)$ for all $x,y\in k^n$ and $\left.\widetilde A\right\rvert_W=A$.

Now, we can choose a system of coordinates on $\Bbb R^3$ such that $$\phi(x,y)=x^t\begin{pmatrix}1&0&0\\0&0&1\\0&1&0\end{pmatrix}y$$
Let's call $W=\operatorname{span}(e_1,e_2)$, so that $\phi^W:=\left.\phi\right\rvert_{W\times W}$ is the symmetric bilinear function $$a^t\begin{pmatrix}1&0\\0&0\end{pmatrix}b$$
Now, you can find rather easily an isometry $A:W\to W$ of $(W, \phi^W)$ which is not diagonalisable. Any extension of $A$ to $\Bbb R^3$ is a map the restriction of which to the invariant subspace $W$ is not diagonalisable. Thus, it cannot be diagonalised.
Added: If you're lost mid-way, the point of the reasoning above is giving an abstract reason for the existence of a real matrix $A=\begin{pmatrix}1&0&a\\ 1&1&b\\ 0&0&c\end{pmatrix}$ such that $A^t\begin{pmatrix}1&0&0\\0&0&1\\ 0&1&0\end{pmatrix}A=\begin{pmatrix}1&0&0\\0&0&1\\0&1&0\end{pmatrix}$. Of course, such a matrix can be found explicitly.