Why are the constraints not working when orientation changes and navigation to new view

Question: I am making a collection view that when one of the cells is pressed it navigates to a second view, however I am experiencing a bug. When in Landscape orientation when I navigate to the second view the constraints change for the first view.
This is what it looks like as vertical and landscape when the app is first open,

Now when ever any of these cells are pressed while in LANDSCAPE orientation it takes me to a new view (which is fine), but before the transition finishes, I can see the constraints of the collection view change (which is not) so I go back to the first view and it looks different, it now looks like this:

I am not sure what I am doing wrong. I tried to not use safeAreaLayoutGuide but it makes no difference to this problem.
Here is the code for the ViewController:
class ProfileViewController: UIViewController {

    var profiles: [Profile] = []

    private let collectionView: UICollectionView = {
        let viewLayout = UICollectionViewFlowLayout()
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: viewLayout)
        collectionView.backgroundColor = .white
        return collectionView
    }()

    private enum LayoutConstant {
        static let spacing: CGFloat = 16.0
        static let itemHeight: CGFloat = 300.0
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
        setupLayouts()
        populateProfiles()
        collectionView.reloadData()
    }

    private func setupViews() {
        view.backgroundColor = .white
        view.addSubview(collectionView)

        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(ProfileCell.self, forCellWithReuseIdentifier: ProfileCell.identifier)
    }

    private func setupLayouts() {
        collectionView.translatesAutoresizingMaskIntoConstraints = false

        // Layout constraints for `collectionView`
        NSLayoutConstraint.activate([
            collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            collectionView.leftAnchor.constraint(equalTo: view.leftAnchor),
            collectionView.rightAnchor.constraint(equalTo: view.rightAnchor)
        ])
    }

    private func populateProfiles() {
        profiles = [
            Profile(name: "Thor", location: "Boston", imageName: "", profession: "astronomy"),
            Profile(name: "Mike", location: "Albequerque", imageName: "", profession: "basketball"),
            Profile(name: "Walter White", location: "New Mexico", imageName: "", profession: "chemistry"),
            Profile(name: "Sam Brothers", location: "California", imageName: "", profession: "geography"),
            Profile(name: "Chopin", location: "Norway", imageName: "", profession: "geometry"),
            Profile(name: "Castles", location: "UK", imageName: "", profession: "history"),
            Profile(name: "Dr. Johnson", location: "Australia", imageName: "", profession: "microscope"),
            Profile(name: "Tom Hanks", location: "Bel Air", imageName: "", profession: "theater"),
            Profile(name: "Roger Federer", location: "Switzerland", imageName: "", profession: "trophy"),
            Profile(name: "Elon Musk", location: "San Francisco", imageName: "", profession: "graduate")
        ]
    }

    init() {
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension ProfileViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return profiles.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ProfileCell.identifier, for: indexPath) as! ProfileCell

        let profile = profiles[indexPath.row]
        cell.setup(with: profile)
        cell.contentView.backgroundColor = .red
        return cell
    }
  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let vc = LightViewController()
    vc.modalPresentationStyle = .fullScreen
    self.present(vc, animated: true)
    var pressedData = Data(id: 1, name: "Test", description: "Test")
    vc.viewModel.lightPublisher.send(pressedData)
  }
}

extension ProfileViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let width = itemWidth(for: view.frame.width, spacing: LayoutConstant.spacing)

        return CGSize(width: width, height: LayoutConstant.itemHeight)
    }

    func itemWidth(for width: CGFloat, spacing: CGFloat) -> CGFloat {
        let itemsInRow: CGFloat = 2

        let totalSpacing: CGFloat = 2 * spacing + (itemsInRow - 1) * spacing
        let finalWidth = (width - totalSpacing) / itemsInRow

        return floor(finalWidth)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: LayoutConstant.spacing, left: LayoutConstant.spacing, bottom: LayoutConstant.spacing, right: LayoutConstant.spacing)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return LayoutConstant.spacing
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return LayoutConstant.spacing
    }
}

this is the code for the cell:
import UIKit

protocol ReusableView: AnyObject {
    static var identifier: String { get }
}

final class ProfileCell: UICollectionViewCell {

    private enum Constants {
        // MARK: contentView layout constants
        static let contentViewCornerRadius: CGFloat = 4.0

        // MARK: profileImageView layout constants
        static let imageHeight: CGFloat = 180.0

        // MARK: Generic layout constants
        static let verticalSpacing: CGFloat = 8.0
        static let horizontalPadding: CGFloat = 16.0
        static let profileDescriptionVerticalPadding: CGFloat = 8.0
    }

    private let profileImageView: UIImageView = {
        let imageView = UIImageView(frame: .zero)
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()

    let name: UILabel = {
        let label = UILabel(frame: .zero)
        label.textAlignment = .center
        label.numberOfLines = 0
        return label
    }()

    let locationLabel: UILabel = {
        let label = UILabel(frame: .zero)
        label.textAlignment = .center
        label.numberOfLines = 0
        return label
    }()

    let professionLabel: UILabel = {
        let label = UILabel(frame: .zero)
        label.textAlignment = .center
        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: .zero)
        setupViews()
        setupLayouts()
    }

    private func setupViews() {
        contentView.clipsToBounds = true
        contentView.layer.cornerRadius = Constants.contentViewCornerRadius
        contentView.backgroundColor = .white

        contentView.addSubview(profileImageView)
        contentView.addSubview(name)
        contentView.addSubview(locationLabel)
        contentView.addSubview(professionLabel)
    }

    private func setupLayouts() {
        profileImageView.translatesAutoresizingMaskIntoConstraints = false
        name.translatesAutoresizingMaskIntoConstraints = false
        locationLabel.translatesAutoresizingMaskIntoConstraints = false
        professionLabel.translatesAutoresizingMaskIntoConstraints = false

        // Layout constraints for `profileImageView`
        NSLayoutConstraint.activate([
            profileImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            profileImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            profileImageView.topAnchor.constraint(equalTo: contentView.topAnchor),
            profileImageView.heightAnchor.constraint(equalToConstant: Constants.imageHeight)
        ])

        // Layout constraints for `usernameLabel`
        NSLayoutConstraint.activate([
            name.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: Constants.horizontalPadding),
            name.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -Constants.horizontalPadding),
            name.topAnchor.constraint(equalTo: profileImageView.bottomAnchor, constant: Constants.profileDescriptionVerticalPadding)
        ])

        // Layout constraints for `descriptionLabel`
        NSLayoutConstraint.activate([
            locationLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: Constants.horizontalPadding),
            locationLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -Constants.horizontalPadding),
            locationLabel.topAnchor.constraint(equalTo: name.bottomAnchor, constant: 4.0)
        ])

        // Layout constraints for `matchLabel`
        NSLayoutConstraint.activate([
            professionLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: Constants.horizontalPadding),
            professionLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -Constants.horizontalPadding),
            professionLabel.topAnchor.constraint(equalTo: locationLabel.bottomAnchor, constant: 8.0),
            professionLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -Constants.profileDescriptionVerticalPadding)
        ])
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setup(with profile: Profile) {
        profileImageView.image = UIImage(named: profile.imageName)
        name.text = profile.name
        locationLabel.text = profile.location
        professionLabel.text = profile.profession
    }
}

extension ProfileCell: ReusableView {
    static var identifier: String {
        return String(describing: self)
    }
}

If there is anything else I can answer please ask,
Thank you

Edit: I took advice from the bottom answers and threw in some combine since I am practicing it. I am able to get the cells to keep the same number, however there is still a layout issue in landscape orientation.
here is what it looks like when moved to landscape when app loads up. To make it easier to see I made the background Color of the view .systemBlue, and the collection view background color is .white.

see the blue at the top. that is what is bothering me, because when I press one of the cells, the collection view seems to move up:

That is the top of the view, it is not a scroll issue.
here is the new view controller:
    class ProfileViewController: UIViewController {

     var profiles: [Profile] = []
    @Published var otherSubject = ColumnFlowLayout()

      lazy var cancellables = Set<AnyCancellable>()

      @Published var testNum: CGFloat = 0

      private let collectionView: UICollectionView = {
                let viewLayout = UICollectionViewFlowLayout()
                let collectionView = UICollectionView(frame: .zero, collectionViewLayout: viewLayout)
                collectionView.backgroundColor = .white
                return collectionView
            }()

            private enum LayoutConstant {
                static let spacing: CGFloat = 16.0
                static let itemHeight: CGFloat = 300.0
            }

            override func viewDidLoad() {
                super.viewDidLoad()
                setupViews()
                setupLayouts()
                populateProfiles()

**NEW --->      NotificationCenter.default
                .publisher(for: UIDevice.orientationDidChangeNotification)
                .compactMap { _ in UIDevice.current.orientation }
                .sink { value in
                self.collectionView.reloadData()
                if value == .portrait {
                   print("@@@Portrait")
                   self.testNum = 2
                 } else if value == .landscapeLeft || value == .landscapeRight {
                   self.testNum = 4
                   print("@@@Landscape")
                 }
               }
              .store(in: &cancellables)
            }

            private func setupViews() {
                view.backgroundColor = .white
                view.addSubview(collectionView)

                collectionView.dataSource = self
                collectionView.delegate = self
                collectionView.register(ProfileCell.self, forCellWithReuseIdentifier: ProfileCell.identifier)
            }

            private func setupLayouts() {
                collectionView.translatesAutoresizingMaskIntoConstraints = false

                // Layout constraints for `collectionView`
                NSLayoutConstraint.activate([
                    collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
                    collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
                    collectionView.leftAnchor.constraint(equalTo: view.leftAnchor),
                    collectionView.rightAnchor.constraint(equalTo: view.rightAnchor)
                ])
            }

            private func populateProfiles() {
                profiles = [
                    Profile(name: "Thor", location: "Boston", imageName: "", profession: "astronomy"),
                    Profile(name: "Mike", location: "Albequerque", imageName: "", profession: "basketball"),
                    Profile(name: "Walter White", location: "New Mexico", imageName: "", profession: "chemistry"),
                    Profile(name: "Sam Brothers", location: "California", imageName: "", profession: "geography"),
                    Profile(name: "Chopin", location: "Norway", imageName: "", profession: "geometry"),
                    Profile(name: "Castles", location: "UK", imageName: "", profession: "history"),
                    Profile(name: "Dr. Johnson", location: "Australia", imageName: "", profession: "microscope"),
                    Profile(name: "Tom Hanks", location: "Bel Air", imageName: "", profession: "theater"),
                    Profile(name: "Roger Federer", location: "Switzerland", imageName: "", profession: "trophy"),
                    Profile(name: "Elon Musk", location: "San Francisco", imageName: "", profession: "graduate")
                ]
            }

            init() {
                super.init(nibName: nil, bundle: nil)
            }

            required init?(coder: NSCoder) {
                fatalError("init(coder:) has not been implemented")
            }

        }

        extension ProfileViewController: UICollectionViewDataSource {
            func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
                return profiles.count
            }

            func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ProfileCell.identifier, for: indexPath) as! ProfileCell

                let profile = profiles[indexPath.row]
                cell.setup(with: profile)
                cell.contentView.backgroundColor = .red
                return cell
            }
          func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            let vc = LightViewController()
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true)
            var pressedData = Data(id: 1, name: "Test", description: "Test")
            vc.viewModel.lightPublisher.send(pressedData)
          }
        }

        extension ProfileViewController: UICollectionViewDelegateFlowLayout {
            func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

                let width = itemWidth(for: view.frame.width, spacing: LayoutConstant.spacing)

                return CGSize(width: width, height: LayoutConstant.itemHeight)
            }

            func itemWidth(for width: CGFloat, spacing: CGFloat) -> CGFloat {
     **NEW ---> let itemsInRow: CGFloat = testNum

                let totalSpacing: CGFloat = 2 * spacing + (itemsInRow - 1) * spacing
                let finalWidth = (width - totalSpacing) / itemsInRow

                return floor(finalWidth)
            }

            func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
                return UIEdgeInsets(top: LayoutConstant.spacing, left: LayoutConstant.spacing, bottom: LayoutConstant.spacing, right: LayoutConstant.spacing)
            }

            func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
                return LayoutConstant.spacing
            }

            func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
                return LayoutConstant.spacing
            }
        }

I am just wondering what is going on with the top constraint and how do I fix this? Thank you
Answer: Your code is setup to draw two cells across the width of the screen. But your code does not attempt to adjust anything during device rotation.
You start the app in portrait and it draws two cells across the width of the screen. Let's say for sake of discussion that results in the cells being 180 points wide.
Now you rotate to landscape. The cell layout is not being updated so the cells stay at 180 points wide. Since the screen is now wider you get 4 cells (roughly) across the screen.
While in landscape you tap a cell and the new screen is presented. As a result of it being presented and then dismissed, the collection view gets redrawn and the layout is recalculated. Since your code specifies two cells across the width, you now have two cells in landscape, just as your code is written to do. So the new cell width is now, let's say, 380 points.
When you now rotate back to portrait those really wide (380 pt) cells are still in use and now only one cell fits (roughly) per row.
So that is why you see the results you see.
You likely need two adjustments to your code:

Update the cell layout as the screen size changes. Do this by overriding the viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) view controller method.
Update your calculations for the cell size as needed to account for different screen sizes.

You should also consider having your ProfileViewController class extend UICollectionViewController instead of UIViewController. If the view controller only has a collection view as its only subview it saves a lot of work and code.
Comment: Hey, I thought about what you said about the size of the cells, and I put my own spin on it, since I am practicing my Combine, however there is just one little issue that still persists, and I wanted to know your thoughts.
Comment: 1) I again urge you to use `UICollectionViewController` instead of `UIViewController`. Save yourself a lot of extra work. 2) Don't base anything on orientation. Base things on the size of the collection view. It's a better approach for handling different sized devices. It's especially important on an iPad when supporting split screen modes.
Comment: 1) I get that and I usually do that, this is just practice for now, I just keep getting this problem. 2) Ok, I can change this, extra) would something like this solve the other issue where the top constraint is off, see new images. Thank you
Comment: I tried using the viewWillTransition, still not sure what the difference between using the Notification Center to notice the device change, and I was able to get the cells to work, but the other issue with the top constraint is still an issue and am not sure why.
Comment: Not sure why the top constraint appears to be off. I don't see anything obvious in the code you posted. The reason to use `viewWillTransition` versus orientation is that `viewWillTransition` will handle a lot more cases. Think about iPad apps supporting split screen where the user can change the screen size without changing the device orientation.
Comment: I figured out the constraint issue, it was a sceneDelegate error. Thank you


Do players share strategies/weaknesses of other players who were their team members

Question: I was reading an interview of Luis Suarez and it made me think...
Do players share secrets, weaknesses of other players whom they played with at club level, when they go head to head in international level.
For instance, in this FIFA world cup, there are many players who are of different nations, but  play in the same club.
Won't the club manager be concerned about this?
Answer: On an individual level Suarez of course is aware of the weaknesses of England's Glen Johnson as they probably play each other all the time in Liverpool's training ground.
He is probably also aware of, at some level, how best to defend against one of Raheem Stirlings runs into the box.
However, Uruguay's coach has almost certainly analysed the two England players as well, as have several thousand football pundits around the world.
So whether he discusses his insight with others or not is somewhat immaterial and I don't see how this knowledge would give his team a better chance of wining against England, nor do I see how this could be of concern to Brendan Rodgers.
Son't forget that these players will not exhibit the same behaviors playing for England as they do for Liverpool - that is down to the managers and coaches in the respective international teams.
What I think would be damaging to a team is to talk about what the club manager's planned tactics were going to be for the upcoming season to any team mates who play in opposing teams in the same league.
Comment: I agree to most of what you have said. But saying that these details won't give Uruguay a better chance to win is not accurate, IMO. For ex, there could be a particular trait, exhibit of a particular player, which is crucial to how he plays. You can analyse all you want, but someone who plays/train with him everyday, can give you better details. Also, at these levels, small details can make the most difference.


Usages of Mean(X/Y) vs. Mean(X) / Mean(Y)

Question: I have a table with two columns X and Y. Each row represents an aggregate statistics for an instance. I introduce a new column as Z = X / Y, which is another important information on the instance. Now, I want to present the overall statistics of the instances (i.e. Mean).
Here I have a concern:  Which one should I use among Mean(X / Y) and Mean(X) / Mean(Y) to represent Mean of Z? Simply, it might be Mean(X/Y) just because Z=X/Y.
However, I have two concerns:

Mean(Y) * Mean(Z) != Mean(X); it makes it hard for people to trust the numbers.
the differences between Mean(X/Y) and Mean(X)/Mean(Y) are significant. Do the differences themselves tell something meaningful statistically?

// I update my case.
The table keeps the user records on a system. Users can upload data to it.

X: the number of uploads
Y: the volume of uploads
Z: Y/X; volume per upload

What I want to do is to simulate such a system with the workloads that are similar to the real.
I simply create N instances of users (N cannot be too large) with X' = Mean(X) and Z' = Mean(Z).
So during the simulation each user uploads data of total volume: (X') * (Z').
Then when I aggregate the simulation results, I end up with: Mean(Y') != Mean(Y).
Comment: see ''ratio estimators'' e.g.: http://stats.stackexchange.com/questions/164738/confidence-interval-of-ratio-estimator/164745#164745
Comment: I am in the train now, i' ll answer in the evening.
Comment: Have you examined the _distribution_ of volume per upload, or of uploads per user, not just mean values? For simulation you probably should be sampling from the distributions rather than just using mean values, in any event.
Comment: Much good advice here but I often find that a mean is unsuitable for summarizing such a ratio even if both quantities are strictly positive. The interval $X < Y$ is mapped to $0 < (X / Y) < 1$ and the interval $Y > X$ is mapped to $\infty > (X / Y) > 1$ which is quite asymmetric. The resulting distribution is often highly skewed, which alone can make means awkward or problematic. The remedy is often to work with logarithm of the ratio and/or (equivalently) geometric means.
Comment: @fcop Hmm, when does the ratio estimation help? When I want to run a simulation with N instances (each has Mean(X), Mean(Y) and Mean(Z) characteristics) based on the statistics? Can I use the ratio estimatior instead of Mean(Z)?
Comment: Can you say more about the context, e.g. what could be X, what could be Y?
Comment: @fcop I updated the post. Could you take a look at it?
Comment: @fcop what's the best option to give the both information? not using the mean?
Comment: @EdM Agree. Using mean values does not work considering highly skewed distributions of X, Y and Z.
Where can I start with sampling? Randomly selecting N different users from the table? The number of samples I need will depend on the distribution. Right? (Time to study...)
Comment: The nature and numbers of the sampling you need to do might depend on what you are trying to accomplish with your simulation, which is not completely clear from the present version of your question. The more information about your goals that you provide, the more someone might be able to help.
Answer: You should present Mean (X/Y) if X/Y is a useful measure and a mean is a useful way to summarize it. By Jensen's Inequality we know that the ratio of the mean is never equal to the mean of the ratio except under some special circumstances.
Comment: @syko that's an epistemological problem. Be sure to carefully explain that they are distinct quantities. I don't think your example contradicts intuition. Take Y=-X , X = -1 or 1 with equal probability.
Comment: Thanks, I think your answer is correct. However, as I mentioned as one of my concerns, people (who will not care for what the Jensen's Inequality is about) can tend not to believe the numbers. Because Mean(Y) * Mean(Z) != Mean(X) which contradicts to the intuition. What would be the best explanation on it?
Comment: @AdamO I think you've got an error in your calculation; in this case $E(1/Y) > 1$ since (with probability 1) $1/Y>1$.
Comment: @R.M. What do you mean "limit of two independent random variables"?
Comment: @AdamO What I meant was that you have two independent variables, and you construct an infinite number of pairs from samples of the two. -- I realize now that I was wrong about my comment, though, in that I neglected the complexity of the reciprocal. While Mean(X)*Mean(1/Y) = Mean(X/Y) for completely independent variables, you can't say that Mean(X)/Mean(Y) = Mean(X/Y), unless you have a rare distribution of Y such that Mean(1/Y) = 1/Mean(Y). So your intuition is assuming 1. the two variables are independent (uncorrelated) and 2. Mean(1/Y) = 1/Mean(Y), which isn't correct in general.
Answer: $Z=Y/X$ may be meaningful for individual users as their individual average volume per upload, but $\text{Mean}(Y/X)$ does not look meaningful in aggregate as some users use the system more than others.
If you took a weighted mean of $Z=Y/X$ to account for this, the natural weights would be the numbers of uploads $X$ and the resulting weighted mean would turn out to be $$\text{Weighted Mean}(Z)=\text{Sum}(X \times Y/X)/ \text{Sum}(X)=\text{Sum}(Y)/ \text{Sum}(X) \\ =\text{Mean}(Y)/ \text{Mean}(X)$$ which would also be the aggregate average volume per upload across the system.
Your concerns are justified: It would probably be better to use the latter option.


How to use AsyncValue feature when I am using select?

Question: I have a provider like this:
@riverpod
class MainProductNew extends _$MainProductNew {
  @override
  AsyncValue<MainProductStateModel> build(String id) {
    return const AsyncValue.loading();
  }

  Future<void> getMainProduct() async {
    final result = await ref.watch(productViewNewRepositoryProvider).getMainProduct(id);

state = AsyncValue.data( state.value!.copyWith(mainProductModel: result.extractDataOrThrow));
  }
}

Now in my widget I want to listen to changes for mainProductModel. So I am using select method.
   var mainProductState = ref.watch(
        MainProductNewProvider(widget.mainProductId)
            .select((value) => value.value?.mainProductModel));

In this scenario I will loose when feature to show loading and error.
How can I use select without loosing asyncValue feature ?
I want to use a model as a state and inside this model I have a few models. I want to use it in a few widgets, and these widgets will listen to related models when they are changed the widgets will be rebuilt .
Answer: You can use whenData:
var mainProductState = ref.watch(
    MainProductNewProvider(widget.mainProductId)
        .select((value) => value.whenData((value) => value.mainProductModel)));

From the documentation:

Shorthand for when to handle only the data case.
For loading/error cases, creates a new AsyncValue with the corresponding generic type while preserving the error/stacktrace.


Arc parameter equation

Question: So, I have the function $y=-x^2+3$, and I'm to generate the parametric equation for the arc that is above $y=x$. I got from $-x^2+3>x$ to  $\frac{1-\sqrt{13}}{-2}<x<\frac{1+\sqrt{13}}{-2}$, but I'm not sure how to proceed from here.
Answer: Now use the parametrization $(x, -x^2+3)$, and you are done.

Arc parameter equation


Creating a page from custom form

Question: I am designing a site for ship maintenance. For now I have 3 files: .info, .install, and .module.
In .install the table schema is automatically installed into the database. It has information like ID, shipname, officer name etc.
Now in .module I have created a form in which you input shipname, officer name, subject, etc.
My problem is this: When I input my data in the form, the data is stored into the table and I display it into to a table (my_module_submissions).
Besides that I want to have a page created every time a user inputs the form and that the page title is taken from the subject.
It's like when you create new content like a story, you input title, content, and some other data. Then when you click submit you are redirected to the newly created page.
Currently I have the form which data is stored into a table, and I get that information and show it into a table (using db_select). How can i create the above?
Filling the information

now when i input the data i get my inputed data showned in this link
 : content/repair_of_main_fuse_box_wiring
So i have a PAGE where i can go to

Now my situation right now is this :
I have created the same thing in php as the first picture . But i can only show my data like this :

Now i have the data but i have no link for every specific row in a table. I dont have a page a can go to for that data.
Comment: OK, picture you created a virtual phonebook using views and other modules that let you verify phone number, email etc. Now you create a form that has lets say : Name, Lastname, phone number,e-mail, street adress ect. basic stuff. Now when you would click save or submit a new page is created (www.mysite.com/mike_something) where you can view the sotred data. NOW, lets say you create your own module for that. You write the code and in my case when i click save it goes to the table (created in .install) and i call it back in a table.
Comment: See the difference when you use the modules you get a PAGE with the data and a link to that data. In my case all of my data is stored in a table and i can only show it in a table. What i would like to learn is how to when i click submit that i get a PAGE and a link to that data.  And yes db_select is used as a dynamic querie.
Comment: yeah it is because you dont have the whole pictures and houndred of lines of code that do specific thing. The pictures are just an very old project of mine. I cannot use forms because i have to then use a lot of modules that do the stuff needs to be done. A good programer would never use modules and so on for something more complex because you relay on someones else module to work for a long time. So if you can help ok if not dont judge me because you don't know or wont tell or give a link how to do what i need to do.
Answer: Is it a drupal 7?
If so, its easily to create new entity type. More information here.
Why you don't like to use nodes to store your data?
Just create new node type with required fields and add permission to create nodes of this type to all users.
In both cases you can use views to represent data into table format.
Comment: Using views would be ok, but other addons that are not in the core are not for me. One changes and the walls come crushing down because i have to use 7-8 modules to do what needs to be done for the site. Yes it is Drupal 7.
Comment: There's nothing wrong with using 7-8 modules as long as it gets the job done. However re-inventing the wheel, I'm against that kind of approach.
Comment: Yeah that why we had the dark ages. Why not reinvent the wheel ? The wheel is reinvented whit Tweel, and the wheel was reinvented from stone to wood to rubber. Any how lets say you have 7-8 modules and you updeate them (funky cool new features) and lets say you have a site of 10 000 people. Boom drupal or other modules dont support some other features, or something else is wrong and your site starts doing funky things what then? You blame the module?  I am fine with sites that are simple and dont need alot of modules, but for me it's a no go. So if someone can help OK in not OK.
Comment: That's what backups and version controls are for so you always can revert back. If you're updating with no return points then you're doing it wrong. Anyway, good luck.
Comment: +1 for using what is available where possible. Most of the time you will be better off in the long run.
I would say use a node type, then give users access to create, then if you need to store extra data in another table use node hooks - http://api.drupal.org/api/drupal/7/search/hook_node_ - like hook_node_insert() and hook_node_update(), etc.

Creating a page from custom form


CountDownLatch leads to disappearance of content in JFrame (JButtons, etc.) and comes back only when mouse overed

Question: I am working on Deal or No Deal with a user interface. The first problem I ran into was how to wait for a button action to continue, and I used Count Down Latches and it worked perfectly. But whenever, I click a button, everything in my JFrame disappears and comes back when you mouse over, it all of a sudden reappears when I press another buttton (This never happened before I used Count Down Latches, and this also happens with Semaphores, etc.) I'll try to keep my code as relevant as possible.
    public CountDownLatch cdl = new CountDownLatch(1);
    pickFirst();
    try {
        cdl.await();
    } catch (Exception E) {
    }
    while (banker.findCasesLeft() > 2) {
        banker = new Banker(Main.f.values);

        for (i = casesToPick; i >= 1; i--) {
            cdl = new CountDownLatch(1);
            pickCase();
            picked = false;
            try {
                cdl.await();
            } catch (Exception E) {
            }
        }

^^^ That was my class that deals with picking cases Below is class with actionlisteners
public void actionPerformed(ActionEvent ae) {
    if (!Main.me.pickedFirst) {
        Main.me.pickedCase = caseNo;
        Main.f.log += "You picked to keep case " + caseNo + ".\n";
        setText(caseNo + "\np");
        Main.f.changeLog();
        Main.me.pickedFirst = true;
        Main.me.cdl.countDown();
    } else {
        int value = Main.me.values[caseNo-1];
        Main.me.values[caseNo] = 0;
        Main.f.values[getIndex(value)].setSelected(true);
        Main.f.log += "You picked to get rid of case " + caseNo + ". It contained $" + value + ".\n";
        Main.f.changeLog();
        Main.me.picked = true;
        Main.me.cdl.countDown();
    }
    setEnabled(false);
}

Comment: WIthout a [mcve](https://stackoverflow.com/help/mcve) it's impossible to know exactly what the problem might be.  However `Main.x` scares me as it suggests that much of your program is based on the use of `static`, not to mention a complete lack of access control...
Comment: Check the [mcve](https://stackoverflow.com/help/mcve) link, it will tell you everything you need to know
Comment: Updates to the UI shouldn't require to have to re-build the output, the screen going blank isn't a normal state of the UI to go through, there is something seriously wrong with how your UI is working
Comment: Will it still be a problem if I'm only using one?
Comment: Also, what else do I need to add to show the problem?
Comment: I have no idea?  What happens if you change the reference to one of those `static` variables?  What's stopping any other part of your program from doing the same?
Comment: I have fixed the problem. All I had to do was unload the butttons from my JFrame and add them back again. Thanks for the help.
Comment: That would be raising the dead in my mind if I found my self faced with the solution, something is very wrong...
Comment: Maybe its because the bottom class extended a JButton and that is being added to the JFrame? Sorry if I let that out to confuse you.
Comment: *"Sorry if I let that out to confuse you."*  If you had posted a MCTaRE as advised by @MadProgrammer in their first comment, we could have known that since it was posted.
Answer: Note that the await() method of CountDownLatch "Causes the current thread to wait until the latch has counted down to zero." If that thread is the event dispatch thread, GUI updates will be blocked until the wait condition changes. In general, CountDownLatch is meant to allow separate threads to rendezvous; it should't be used to within the event dispatch thread. This complete example, which coordinates multiple SwingWorker instances, may help clarify the usage.
Comment: As an alternative, consider the MVC approach examined [here](http://stackoverflow.com/a/3072979/230513).


Positive Elements: Decomposition?

Question: Problem
Given a C*-algebra with unit $1\in\mathcal{A}$.
Then every selfadjoint element decomposes into positives ones:
$$A=A^*:\quad A=\frac12(|A|-A)-\frac12(|A|-A)\quad\left(\frac12(|A|\pm A)\geq0\right)$$
However, one also has the special dcomposition:
$$A=A^*:\quad A=\frac12(\|A\|1+A)-\frac12(\|A\|1-A)\quad\left(\frac12(\|A\|1\pm A)\geq0\right)$$
In general, they differ as $|A|\neq\|A\|1$. But the positive decomposition is unique, isn't it?
Disclaimer
This thread is meant as summary. For more informations see:

SE blog: Answer own Question
MSE meta: Answer own Question

(The second especially reveals the opinion of the community!)
Answer: The missing ingredient is orthogonality: $A_+A_-=A_-A_+=0$
The former ones are:
$$\frac12(|A|\pm A)\frac12(|A|\mp A)=\frac{1}{4}(|A|^2-A^2)=0$$
while the latter ones aren't:
$$\frac12(\|A\|1\pm A)\frac12(\|A\|1\pm A)=\frac12(\|A\|^21-A^2)\neq0$$
So only the first ones correspond to the unique decomposition!

Positive Elements: Decomposition?


Math formulae for organs?

Question: I already know that an organ can be synthesized by using sine waves at specific frequencies.
But if you generate sine waves like that, the timbre of the note is very very plain (it sounds just like a plain tone)
Is there anywhere I can find the math formulae for blending sine waves of different shapes (or triangle waves even) to get more pleasant sounding generated tones?
Comment: There was a project called aeolus, in which the program author created an excellent software synthesizer for pipe organ. http://users.skynet.be/solaris/linuxaudio/aeolus.html
Answer: Additive synthesis can be more than just stacking a bunch of sine waves to emulate an instrument. For instance are the sine waves following the harmonic series or some other series of harmonics? are the sine waves at a constant amplitude? are the sine waves in the same phase?
The key thing to remember is that almost all natural sounds will have dynamic events that are in constant change so only stacking waves in a static manner will not render a complex tone.
One might start with making an analysis of what tone or sound you are interested in replicating. Here is the 101 on this:
TAKING THE WAVEFORM APART
http://artsites.ucsc.edu/ems/music/tech_background/TE-04/teces_04.html
and
THE MATHEMATICS OF ELECTRONIC MUSIC
http://artsites.ucsc.edu/ems/music/tech_background/TE-11/teces_11.html
and
Frequency modulation synthesis
http://en.wikipedia.org/wiki/Frequency_modulation_synthesis
and a tutorial:
http://www.sfu.ca/~truax/fmtut.html
This is not trivial work.
Answer: adding sin waves together of different amplitude,phase,frequency will get you to ALL the tones that are periodic.  But periodic tones are pretty boring to the ear by themselves.  So you wrap a volume/filtercutoff controlling envelope or lfo around em and they start getting interesting.  then throw them thru some fx filters like chorus and reverb and they get MORE interesting.  An organ is basically the first form of software synthesizer that we came up with.  But, mmm, I'm no expert in these rather deep matters.

Math formulae for organs?


how to update the page content without refresh the page by jquery

Question: the page url is   http://example.com/index.php?main_page=index&Path=<?php echo $_GET['Path'];?>
there are some contents on the page:

<a href="http://example.com/index.php?main_page=index&Path=<?php echo $_GET['Path'];?>&sort=1a">price

 the content....

if i click the price, the content will be arranged according to the price with  ascending.

<a href="http://example.com/index.php?main_page=index&Path=<?php echo $_GET['Path'];?>&sort=1d">price

 the content....

if i click the price, the content will be arranged according to the price with descending.
now, i want to get when the visitor click the price text, the content arranged can be exchanged. the default state is ascending. and don't refresh the page.
how should i do?
Answer: Can use JQuery load to assign the html from the url without reloading the page.
On the click the on the price link you can load the content div.
e.g.
$('#content_div').load($('#a_price').attr('href'));

For html below -
<a id="1d" href="example.com/index.php?main_page=index&Path=<?php echo $_GET['Path'];?>&sort=1d">1d
<a id="1a" href="example.com/index.php?main_page=index&Path=<?php echo $_GET['Path'];?>&sort=1a">1a

Javascript -
$('#1d, #1a').click(function(event){
    // Prevent default link behaviour
    event.preventDefault();
    // load the div contents from the link
    $('#producListing').load(this.attr('href'));
})

Have added the ids to the link. Can be made generic.
Also, the link contents should render partial content only with the results, which you would need to display.
Comment: Just be sure to give your content div the id of 'content_div' that this answer suggests.
Comment: Jayendra ,i am sorry i still don't know how to do it. if all the content are in the ID productListing,$("#productListing").load($('#a_price').attr('href'); there are two URL(, ) how to write it? thank you


If n is a positive integer that is four digits long and is relatively prime to 100!, why must n be prime?

Question: Suppose there is some positive integer n that is four digits long and is relatively prime to 100! (meaning n and 100! have no common factors other than 1). n must be prime, but why?
100! is a composite number, but composite numbers can be relatively prime to other composite numbers, so that can't be the reason n is prime. n being four digits long and 100! having factors that are all less than four digits must have something to do with it, but I can't wrap my head around the exact reason.
So, why does n have to be prime in this situation?
Comment: Assume that $n$ is not prime and contains a prime factor $p > 100$. What can you say about $\frac{n}{p}$?
Answer: Hint: suppose some number $n$ is not prime, but $n$ has no prime factors less than 100. That is, $n$ is the product of at least two prime numbers greater than 100. What's the smallest that $n$ could be?
Comment: Ah ha! If n is composite but has no prime factors less than or equal to 100, the smallest n could be would be five digits, so it must be prime. Thank you!


Confusing Bar (Multiple Voices)

Question: I just started learning about composing with multiple voices on the same staff (using piano) and I am quite certain that I understand the basics of how that works, however, I came across this bar in a piece that has a 3/2 time signature that I cannot seem to make sense of. The problem is that the count of notes in the bar doesn't seem right. I tried to separate the two voices but I can't distinguish them properly. I have heard about the different stem rules, but when I looked it up I couldn't find the rules that apply to two voices. What exactly are the rules for this? The only thing that I found helpful is the distinction between the up-stem and down-stem voice, but the chord made up of half notes in the treble clef is down-stem, which indicates it is the down stem voice that continues from the previous whole notes, but the sixteenth notes also have down stems, which is not right in 3/2 if they are the same voice. Perhaps this bar is wrong? Any help would be appreciated, thanks.
Answer: God, is this a badly written bar. Since it's in 3/2, here is my take on it:

Here are the 3/2:

So that is one voice on the left hand (pretty clear) and the first voice of the right hand.

This would be the second voice of the right hand, which lasts only 2/2, followed by a rest:

These just seem to be grace notes not written as grace notes:

I am saying grace notes,  because there is a legato on the first four that is connected to the chord on the next beat, but it doesn't fit in time. The last three notes would be no problem if they were grace notes, because it's not uncommon to have three grace notes and also they are also connected to something on the next bar, just like grace notes.

Confusing Bar (Multiple Voices)


Kubernetes Service ExternalName

Question: I have some problems with Kubernetes ExternalName Service. I want to access server 'dummy.restapiexample.com' from the cluster . I created the following service:
<code>apiVersion: v1
kind: Service
metadata:
   name: dummy-svc
spec:
    type: ExternalName
    externalName: dummy.restapiexample.com
</code>
<code>$ kubectl get svc
NAME         TYPE           CLUSTER-IP   EXTERNAL-IP                PORT(S)   AGE
dummy-svc    ExternalName   <none>       dummy.restapiexample.com   <none>    33m
kubernetes   ClusterIP      220.127.116.11   <none>                     443/TCP   6d19h
</code>
But when I try to access the service from a pod from the same namespace, I'm getting code HTTP 403.
<code>$ curl -v http://dummy-svc/api/v1/employee/1
> GET /api/v1/employee/1 HTTP/1.1
> User-Agent: curl/7.35.0
> Host: dummy-svc
> Accept: */*
>
< HTTP/1.1 403 Forbidden
< Content-Type: text/plain
< Date: Sat, 23 Nov 2019 14:21:05 GMT
< Content-Length: 9
<
</code>
I can access the external server w/o any problem:
<code>$ curl -v http://dummy.restapiexample.com/api/v1/employee/1                               │
> GET /api/v1/employee/1 HTTP/1.1
> User-Agent: curl/7.35.0
> Host: dummy.restapiexample.com
> Accept: */*
< HTTP/1.1 200 OK
...
< Content-Length: 104
{"id":"1","employee_name":"56456464646","employee_salary":"2423","employee_age":"23","profile_image":""}
</code>
What is wrong with my code? Any hint will be highly appreciated.The cluster is runnung on AWS and installed with kops.
Comment: the 403 is being returned by your server, not the service. There is nothing wrong with how you configured the service.
Comment: The service is just resolving the name. If you try a trace route you should see it reach your server property
Comment: You're using a different url through the service, your application may not like that
Comment: I understand that the code returned by my service, I don't understand why. As I understand, the service should just forward requests to the external server, but it refuses to do it.
Comment: Thanks! I see your point. You're right. If I ping my service, I get a response from the remote server correctly. I just wonder, what is the difference between 2 curl commands: one directly sends a request to the remote server and receives correct response and another - sends the same request via the service and receives 403?
Comment: The external server might be checking your `Host` header and reject anything not matching it's proper hostname, so you might have to set the "proper" Host header.
Answer: As pointed by Patrik W, the service works correctly. It routes requests to the remote server. Ping reaches the remote server:
<code>$ ping dummy-svc

PING dummy.restapiexample.com (220.127.116.11) 56(84) bytes of data.
64 bytes from ec2-52-209-246-67.eu-west-1.compute.amazonaws.com (18.104.22.168): icmp_seq=1 ttl=62 time=1.29 ms
</code>
Code 403 received from the remote server because of different URLs.
@Patrik W: Thanks for the help.

Kubernetes Service ExternalName


For which intervals on $\Bbb R$ is $\sum_{n=1}^\infty\frac{x^n}{1+x^{2n}}$ uniformly convergent?

Question: For which intervals on $\Bbb R$ is the following series uniformly convergent?
$$\sum_{n=1}^\infty\frac{x^n}{1+x^{2n}}$$
This is what I thought:
Let $a\in[0,1)$. Then on intervals $\left[-a,a\right]$:
$$\left|\frac{x^n}{1+x^{2n}}\right|\leq a^n$$
And the series $\sum a^n$ converges. It is uniformly convergent by the M test.
Is this correct ? Are there more intervals ?
Answer: Yes, this is correct.
Now note the series diverges for $x=\pm 1$.
And for all $|x|> a>1$, you have
$$
0\leq \frac{x^n}{1+x^{2n}}\leq \frac{x^n}{x^{2n}}= \left(\frac{1}{x}\right)^n\leq  \left(\frac{1}{a}\right)^n.
$$
So you have also uniform convergence by the $M$-test on $(-\infty,-a]\cup[a,+\infty)$.
You can't do better than these intervals, ie you don't have uniform convergence on $(-1,1)$, $(-\infty,-1)$ or $(1,+\infty)$.
Otherwise, by the uniform Cauchy criterion, you would find for instance that
$$
\frac{1}{2}=\lim_{n\rightarrow+\infty} \sup_{x\in(-1,1)}\frac{x^n}{1+x^{2n}}=0.
$$
Contradiction. It works the same on the other two intervals.


Count Method on Undefined Active Record Array @objects.count

Question: Is there a way to write a clean if nil then in a view. Assuming my lack of ruby is biting me here. Example,
If object nil, then return, nothing found
have
<%= @objects.count if @objects %>

want something like this
<%= @objects.count if @objects then "nothing found" %>

Answer: There are many ways to write something like this.
Something simple would be:
<% if @objects %>
  <%= @objects.count %>
<% else %>
  nothing found
<% end %>

If you get into a slightly more complex conditional I would suggest moving the logic into a helper and call it from the view. ex:
<%= count_for(@object) %>

Answer: Here's a good solution for you:
<%= "nothing found" unless @objects.try(:length).to_i > 0 %>

One of the issues is that you can't run count on a nil object. Therefore you need to use Rails' super handy .try() method to return nil when @objects = nil, rather than NoMethodError.
Next issue: You can't make a comparison between nil and a number using > so you need to convert the results of @objects.length to an integer which will return 0 for nil.
Lastly, try calling length rather than count. This will avoid running any extra queries when @objects is defined.
Avoids: SELECT COUNT(*) FROM 'objects'
Also if you want to display the count using this one-liner technique you can simply write up a shorthand if/else statement as follows:
<%= @objects.try(:length).to_i > 0 ? @objects.length : "nothing found" %>

One last option:
Use the pluralize method, which can handle a nil count:
Showing <%= pluralize( @objects.try(:length), 'object' ) %>

Sorry, I know this is pretty late, but hopefully helpful for someone else!
Comment: That seems overly confusing and samtically wrong. If the `try` call returns nil, you are essentially asking if 0 is greater than 1.
Comment: Changed to use .to_i as I think it's clearer. Thanks for your feedback


Functions and convergence in law

Question: Let $X$ be a random variable taking values in some metric space $M$. Let $\{\phi_n\}$ be a sequence of measurable functions from $M$ to another metric space $\tilde M$. Suppose that $\phi_n(X)$ converges in law to a random variable $Y$. Must it be the case that the pairs $(X, \phi_n(X))$ converge in law to a pair $(X, \phi(X))$, where $\phi$ is a measurable function such that $\phi(X)$ has the same law as $Y$?
Comment: When $M$ and $\widetilde M$ are separable, did you try to use Skorohod representation?
Comment: Yes, I tried this. It reduces us to the case of showing that if $(X_n)$ all have the same law, $X_n\rightarrow X$, $\phi_n(X_n) \rightarrow Y$ a.s., then $Y$ is a.s. a function of $X$. However, I don't see a way to prove this.
Answer: Generally speaking, the answer is no. Follows a counter-example with Bernoulli random variables (if you prefer continuous variables, you can construct something similar with the central limit theorem, see the end of my answer).
Let $X$ be a sequence of independent random variables with uniform distribution on the discrete space $\Bbb Z_2$ and let $\phi_n(x) = x_1 + \dots + x_n$. There is trivially convergence in law for $\phi_n(X)$ because for every $n$, the sum $X_1+\dots+X_n$ has uniform distribution on $\Bbb Z_2$.
Suppose that there is some random variable $Y$ such that $(X,\phi_n(X))$ converges in law to $(X,Y)$.
Consider an arbitrary function $f \colon \Bbb Z_2 \to \Bbb R$ and an arbitrary event $A \in \sigma(X_1,\dots,X_k)$. For every $n \geq k+1$, the random variables $1_A$ and $\phi_n(X)$ are independent. Taking the identity
$$
\Pr(A)\cdot E[f(\phi_n(X))] = E[1_A\cdot f(\phi_n(X))]
$$
to the limit, we see that $\Pr(A)\cdot E[f(Y)] = E[1_A\cdot f(Y)]$.
As a consequence, the random variables $X$ and $Y$ are independent. If $Y$ was to be some $\phi(X)$, then it would be constant. This is absurd.

Let $X$ be a sequence of i.i.d. real random variables with $E(X_1)=0$ and $E(X_1^2)=1$. The central limit theorem asserts that
$$
\phi_n(X) = \frac{1}{\sqrt{n}}\sum_{k=1}^n X_k \xrightarrow[n\to\infty]{law} Y \sim \mathcal{N}(0,1)
$$
This would require a proper proof but I think that the following is true (because $1/\sqrt{n}$ "kills" $X_1,\dots,X_k$ for finite $k$):
If $(X,\phi_n(X))$ converges in law to $(X,Y)$, then $X$ and $Y$ are independent.
Another consequence of this is that in the CLT, there is never almost sure convergence (or convergence in probability) for the sequence $\phi_n(X)$. Notice that this is not in contradiction with the Almost Sure CLT.
Comment: Thanks for the reply! It seems though that the function $\phi_n(X)$ is not independent of $\sigma(X_1 , ... , X_k)$ for $n >k$. Indeed, if we switch the value of one of the $X_j$'s for $j\leq k$, then $\phi_n(X)$ changes from 0 to 1 or vice versa.
Comment: I might be wrong, but I don't think this contradicts the definition of independence in Probability Theory.
Comment: @user15464: Do you agree?
Comment: I still do not agree with your first construction. I think your second construction is somewhat better though. What topology are you using for X?
Comment: Have you checked the definition of independence? Or is there something else you don't agree with? The topology used is the product topology (note that it is metrizable).
Comment: Ah, okay, I see. My mistake. The first example is fine, sorry for the confusion.
Answer: A more elementary counterexample: Let $X$ have uniform distribution over $[0,1]$ and define $\phi_n(x):=x$ when $n$ is odd, and $\phi_n(x):=1-x$ when $n$ is even. It's clear that every $\phi_n(X)$ has the same distribution (namely, that of $X$), hence we have convergence in law. However, the pair $(X,\phi_n(X))$ doesn't converge in law to anything, since its distribution keeps flipping back and forth.

Functions and convergence in law


Having some trouble with piano fingering

Question: I'm practicing some warm up exercises from the All in One Adult Piano Course. In the book these are left hand exercises. On the top staff the G7 says finger positioning should be 5, 2, 1. Is the finger placement relative to the root position (in this case G)?
Also, why does the G7 chord only have 3 notes?
Comment: **G7** contains G B D F. Usually the 5th can be omitted without losing anything. Chord voicings containing the root, 3rd and 7th are called _shell voicings_; they capture the essential quality of the chord, and are very useful.
Answer: No, the fingering is not relative to the root.
The numbers represent your fingers, starting with 1 at the thumb.
You play with your left hand pinky (5) the b, index (2) the f and thumb (1) the g - so the finger numbers are written next to the note they should play.
The d is skipped here for simplification. If you are advanced enough you could try adding it (I would suggest the middle finger).
Comment: Probably best not to add the D to a chord in this register, the open voicing is less 'muddy'.   Elementary piano music often uses block chords in the left hand. Not always the most effective texture.
Comment: Just to translate from possible German - the 'h' in the answer is more commonly known as 'B'.
Comment: @LaurencePayne I just tried to express that it would be possible to add the missing D, and there's no strict  _rule_ here as a beginner might think.
Comment: Yes, beginners crave 'rules' don't they!   :-)  Actually, there sort of is a rule here.  Or two rules.  The one that says to keep LH voicings as uncluttered as possible.  And the one that tells us the 5th is the least essential note in a triad-based chord.
Answer: In this case the suggested fingering is the most efficient.  Fingering is contingent upon where you are coming from and where you are going.  Also, how ergonomic your technique is.  Someone with an effortless virtuoso technique can get away with creative fingering.  For instance, Art Tatum would play an arpeggio using only two fingers that many accomplished pianists would struggle to play with four fingers. Freedom of the arm frees the fingers and for the most part the propriety of fingering disappears.  I call it "throwing away your technique," once you ascend to that level of competency, creativity, musicianship and courage to stop thinking and just be the conduit between piano and music.
As far as leaving notes out, often, less is more.  Take the song, "The Rose."  Its introduction on a C chord is only a C and G with the E missing.  It creates a simple, open and more linear progression as the ensuing chords are just as sparse.  That allows the pianist to explore the following:
Often a counter melody can be crafted out of the accompaniment for a pianist with fine tuned finger interdependence.  Imagine that in your example a small instrumental combo was playing the arrangement and a clarinet was playing the E, F, E, F . . . If the clarinet were legato and the others were slightly detached, it would create an inner voice or counter melody.  If you added the missing D it could hamper your execution, destroy the simplicity, muddy up the chord and, if the piece WERE being played by three instruments, who would play the fourth?  I often look for invisible lines to explore in the accompanying notes, a line I can make legato or not in an effort to accompany the melody rather than just plunk static chords as an accompaniment.
The piano is its own instrument but often is called upon to imitate or play something imagined for orchestra.  Chopin's music is great for exploring inner alternative melodic progressions that are not the melody.
Regarding the words "warm up," technique is in the brain and if your body and blood are warm, your hands are always at the ready especially if you've already been moving about.  Like, walking.  Do you do warm ups before you begin walking each day?  Sure, when you get out of bed you may feel the need to break a few cobwebs but that is only because synovium fluid (body's lubricant) needs to do its job.  Like starting your car, all the oil is in the pan and needs to be pumped back up to the engine but once it is done, in a split second, the engine is ready to go and at the beck and call of the car's brain - you.
Your hands are much the same.  If the body is warm, and your brain knows how to play ergonomically, technique will always be there in an instant.  However, if you have flaws in your technique, and you brow beat "strength and endurance" into the wrong muscles, you will always feel that you need to warm up until you beat the incorrect muscles into submission. If you feel you need to practice every day, you are probably doing something wrong.   If you can go several days without practicing and you drop your hands and your technique is still there, you are doing something right.
Practice doesn't make perfect.  Perfect practice makes perfect and perfection is in the brain, which controls our muscles and nerves, not the other way around.


Error after changing name of Naturald parameter

Question: I have changed NaturalId column name using liquibase (from "name" to "query_name"):
<changeSet id="rename_name_to_query_name">
    <preConditions onFail="CONTINUE">
        <columnExists tableName="pm_dbqueries" columnName="name" />
        <not>
            <columnExists tableName="pm_dbqueries" columnName="query_name" />
        </not>
    </preConditions>
    <renameColumn
        columnDataType="varchar(40)"
        newColumnName="query_name"
        oldColumnName="name"
        tableName="pm_dbqueries"/>
</changeSet>

It works correctly, the name has changed... I've also updated my Entity class in java:
@Entity
@Table( name = "pm_dbqueries", uniqueConstraints = { @UniqueConstraint(columnNames = "id"),
                                                      @UniqueConstraint(columnNames = "query_name") } )
@SequenceGenerator( name = "pm_dbqueries_seq", sequenceName = "pm_dbqueries_seq" )
public class DBQuery
{
    @Id
    @GeneratedValue( strategy = GenerationType.AUTO, generator = "pm_dbqueries_seq" )
    @Column(name = "id", unique = true, nullable = false)
    private Long id;

    @NaturalId
    @Column(name = "query_name", unique = true, nullable = false, length = 40)
    private String queryName;

    @Column(name = "query", unique = false, nullable = false, length = 4000)
    private String query;

    public Long getId()
    {
        return id;
    }

    public void setId( Long id )
    {
        this.id = id;
    }

    public String getQueryName()
    {
        return queryName;
    }

    public void setQueryName( String queryName )
    {
        this.queryName = queryName;
    }

    public String getQuery()
    {
        return query;
    }

    public void setQuery( String query )
    {
        this.query = query;
    }
}

But the thing is... when I'm trying to execute this:
return (DBQuery) sessionFactory.getCurrentSession().byNaturalId(DBQuery.class).using( "query_name", name ).load();

Error shows up:
org.hibernate.HibernateException: No value specified for natural-id property XXX.DBQuery#queryName
    at org.hibernate.event.spi.ResolveNaturalIdEvent.<init>(ResolveNaturalIdEvent.java:102)
    at org.hibernate.event.spi.ResolveNaturalIdEvent.<init>(ResolveNaturalIdEvent.java:52)
    at org.hibernate.internal.SessionImpl$BaseNaturalIdLoadAccessImpl.resolveNaturalId(SessionImpl.java:2466)
    at org.hibernate.internal.SessionImpl$NaturalIdLoadAccessImpl.load(SessionImpl.java:2581)

It was working fine before these changes. Any suggestions?
Comment: Please don't use code snippets for code that isn't supposed to run in the browser. Use a normal code block, instead.
Answer: Try this as you need to use property names not column names here. It worked earlier because there was no difference between both (name == name).
return (DBQuery) sessionFactory.getCurrentSession().byNaturalId(DBQuery.class).using( "queryName", name ).load();

Comment: Please don't use code snippets for code that isn't supposed to run in the browser. Use a normal code block, instead.
Comment: @Seric Please consider to accept my answer if it solved your problem. Thanks!
Comment: @Cerbrus Thank you for pointing that out - did not know that so far but of course it makes perfect sense.


Steps to find limit of $\frac1{t\sqrt{t+1}} - \frac1t$ as $t\to0$

Question: So, it's been about 6 years since I've taken any type of math course, and 7 since I've taken Calculus. Recently, though, I've been trying to relearn Calculus in my free time.
I've been working through my old Calculus textbook, which has been going pretty well. Currently, though, I'm stuck on this problem:
$$\lim_{t\to0} \left(\frac{1}{t\sqrt{t+1}} - \frac1t\right)$$
I need to systematically find the limit as $t\to0$. Right away, I know that I need to manipulate it in such a way that when I plug $0$ in for $t$, I don't have $0$ in the denominator.
I know the answer is $-\frac12$, but I'm having quite a bit of trouble getting there. Could someone help to point me in the right direction? I'm not necessarily asking someone to solve it, I'm just not entirely sure what my first few steps should be.
It's been a while for me, so please keep it in the context of someone who has never worked with limits before.
Comment: You could expand: $$\frac{1}{t}\left(\frac{1}{\sqrt{1+t}}-1\right)=\frac{1}{t}\left(-\frac{t}{2}+ \frac{3t^2}{8}-\cdots \right)$$
Comment: Sorry, valverij, I worked a lot yesterday with integrals...here, partial fractions are not appropriate.
Answer: $$\frac{1}{t\sqrt{t+1}} - \frac{1}{t} = \frac{1-\sqrt{t+1}}{t\sqrt{t+1}} = \frac{1-\sqrt{t+1}}{t\sqrt{t+1}} \frac{1+\sqrt{t+1}}{1+\sqrt{t+1}}=\frac{-t}{(t\sqrt{t+1})(1+\sqrt{t+1})}=\frac{-1}{(\sqrt{t+1})(1+\sqrt{t+1})}$$
Comment: Thanks, I already see where I when wrong. I kept flipping the $1-\sqrt{t+1}$ around to read $-\sqrt{t+1}+1$ in the numerator in that first/second step, and it was tripping me up down the road.
Answer: If you rewrite the expression (by reducing all to the same denominator), you get
$$
\Delta(t)\stackrel{\text{def}}{=}\frac{1-\sqrt{t+1}}{t\sqrt{t+1}} = -\frac{1}{\sqrt{t+1}}\frac{\sqrt{t+1}-1}{t}
$$
Now, both the numerator and the denumerator go to $0$ with $t$. A way to consider this, though, is to remark that $\frac{1}{\sqrt{t+1}}$ goes nicely to $1$ when $t\to0$; if you had a way to deal with the remaining $\frac{\sqrt{t+1}-1}{t}$, you could compute the limit.
If this rings a bell, you can try to consider the function $g:x\to\sqrt{x+1}$, and its derivative at $0$ (first observing that it is defined and continuous on $[-1,\infty)$, and differentiable on $(-1,\infty)$).


I found @RecentlyNonNull in LocationResult that contradicts the code, which should I trust?

Question: I'm calling the LocationResult.extractResult method that seems to be implemented as follows (according to IntelliJ's "go to declaration"):
@RecentlyNonNull
public static LocationResult extractResult(@RecentlyNonNull Intent var0) {
    return !hasResult(var0) ? null : (LocationResult)var0.getParcelableExtra("com.google.android.gms.location.EXTRA_LOCATION_RESULT");
}

It's hard to believe this code will never return null. Should I trust the annotation, or the common sense that the "then" branch of the conditional operator may sometimes be selected? The consequence of an NPE from this would probably be an application crash.
Since I'm using this from Kotlin, it of course complains that I'm making a redundant null check.
Comment: I'd imagine this could differ at runtime if calling code outside this library to an OS class?
Answer: This is a bug, as the system does return null even on latest Android devices.
I dealt with it by suppressing the warning:
// it could be null on some devices, do not remove this annotation
@Suppress("SENSELESS_COMPARISON")


LDAP + NFS + automount home directories permissions issue

Question: When an LDAP user logs into the system they have incorrect permissions to their home directory.
LDAP and NFS services exist on the same server.
The directory shows the correct ownership / permissions:
drwx------. 4 ldaptest ldaptest 4096 Jun  9  2014 ldaptest

however the UID / GID do not match those on the server
client:
bash-4.1$ id
uid=10001(ldaptest) gid=10001(ldaptest) groups=10001(ldaptest)     context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

server:
[root@ldap1 log]# id ldaptest
uid=502(ldaptest) gid=502(ldaptest) groups=502(ldaptest)

How do I resolve this?
Comment: Funny, I found the fix right after I posted the question.  The local user account ldaptest on the server had different UID / GID than what was in the LDAP DB.  That's why there was a mismatch on the client as well.  I changed the UID/GID on the ldaptest@server account and now it works.

The account must have been created incorrectly during the migration step of setting up LDAP. (migrate_common.ph)
Comment: I have not tested this solution in Linux, but try using inherited permissions on the sub directories: http://superuser.com/questions/151911/how-to-make-new-file-permission-inherit-from-the-parent-directory
Answer: Set up LDAP idmap on the server like you have on the workstations.  Or add it to all.  Use the same UID config method and settings.


Wordpress - Show random post with JS, not PHP

Question: I have this page containing recent posts at the bottom. I have set it to randomly show me three posts from the same category as the current post. Heres the loop:

SIMILAR INSIGHTS

<?php
   // the query
   $the_query = new WP_Query( array(
     'orderby' => 'rand',
     'cat' => '-14',
     'posts_per_page' => 3,
   ));
?>

<?php if ( $the_query->have_posts() ) : ?>
  <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

      <?php
        if(get_field('quote') == ''){
        $yourTag = "" ;
        } else {
        $yourTag = "";
        }
      ?>

 <?php echo $yourTag; ?>

          <a href="<?php the_permalink(); ?>">

              <?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?>

<?php the_category(', '); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php the_excerpt(__('(more…)')); ?>

<?php the_author(); ?> | <?php echo get_the_date(); ?>

  <?php endwhile; ?>
  <?php wp_reset_postdata(); ?>

<?php else : ?>

<?php __('No News'); ?>

<?php endif; ?>

This works fine currently.
The trouble is, when finished, the site will be behind a clients custom cache and he tells me that PHP randomisers wont work as it will just show the cached version. He suggested I do any randomising using Javascript!
So firstly - is this possible? Secondly, How would I go about targeting this is javascript!? Thanks for looking!!
Answer: Unfortunately you won't be able to randomize a post in this way for the caching reason.
What you can do instead is use an Ajax call to dynamically fetch and insert a random post...
$.get('/wp-content/themes/SomeTheme/random.php?v=' + Math.floor(Date.now() / 1000))
.done(function(resp) {
  $('.random-post').html(resp);
})
.fail(function(xhr) {
  // handle error (xhr object contains the response)
});

And then create a separate random.php file in your theme and put the code to randomly return a single post in there. Note, that you don't need to put the whole layout around the post (don't include header.php etc). That's because this exact HTML fragment will be sent to the frontend and inserted dynamically.
The ?v= parameter is required for cache busting so that it fetches a new post each time.
Comment: I revised my answer slightly to include `?v=` which is required depending on how you're caching things.
Comment: Thank you for this - just so I have it right, I would create a loop that displays a single blog post in it's own php file - Then add this code to my Wordpress template file inside the loop on the page to pull in 3x the single blog posts?  - Will this now run the risk of the post duplicating if each one is random?
Comment: I tweaked my answer above slightly, I forgot to include the local variable `resp` in the arguments. To answer your other question, that comes down to the way you query the random.php file. What you can do is change the url to be `random.php?v=123&count=3`, so if you want it to give 3 random posts you can say `count=3` if you have another area of your site where you want to change that you could say `count=2`. There is the possibility that BETWEEN widgets you might have duplicates, if you really wanted to fix that you could tweak the functionality slightly by...
Comment: specifying a range in the intiial call, like `⦥=1-2&count=3` and in the other one `⦥=3-4&count=2`), that way its a random post within the last 1-2 weeks, and in the ohter widget its a random post in the last 3-4 weeks. Thats going quite deep into details... generally the chance of a random post would be quite rare, and if you have only 1 widget area on your page then it doesnt matter anyway
Comment: Another option is to make the php file return json instead, so like: `{posts: [{...}, {...}])`, and make jQuery fetch that file using the `?count=5` parameter. This count would be the TOTAL number of posts you want, across the entire site. From there, you could take those 5 results and instead of inserting them using the `.html(resp)` command you would build out the actual widgets using loops or a templating library like DoT.js.
Comment: As far as what goes in the PHP file, everything i've mentioned can be done with the `WP_Query` function: https://codex.wordpress.org/Class_Reference/WP_Query
Comment: I've given you a range from simple to more advanced, it really depends on 1) how many widgets there are per page, 2) how much you dont want duplicates even if the chance is fairly low. If you have only 1 widget on your whole site then `?count=X` is enough. If you have multiple then its up to you on whether you want to use the `range` method or to fetch ALL the posts you want for the entire page in JSON format, and then 'build' each html widget area manually, using the posts you fetched (and using each one only once)
Answer: Try wrapping the entire funtionality as a shortcode.


An equation for the third powers of the roots of a given quadradic polynomial

Question: The roots of the equation $3x^2-4x+1=0$ are $\alpha$ and $\beta$. Find the equation with integer coefficients that has roots $\alpha^3$ and $\beta^3$.
GIVEN
SR: $\alpha + \beta = \frac43$
PR: $\alpha\beta = \frac13$
REQUIRED
SR: $\alpha^3 + \beta^3 = (\alpha + \beta) (\alpha^2 + 2\alpha \beta + \beta^2)$
$\alpha^3 + 3\alpha^2 \beta + \alpha \beta^2 + \alpha^2 \beta + 3\alpha \beta^2 + \beta^3$
$\alpha^3 + 3\alpha^2 \beta + \alpha \beta^2 + \alpha^2 \beta + 3\alpha \beta^2 + \beta^3 = (\alpha + \beta)^3$
$\alpha^3+ \beta^3 = (\alpha + \beta)^3 - 3(\alpha \beta)^2 - (\alpha \beta)^2$
$\alpha^3 + \beta^3 = (\frac43)^2 - 3(\frac13)^2 - (\frac13)^2$
$\alpha^3 + \beta^3 = \frac{16}{9} - \frac13 - \frac19$
$\alpha^3 + \beta^3 = \frac43$
PR: $\alpha^3 \beta^3$
$(\alpha \beta)^3 = (\frac13)^3 = \frac{1}{27}$
EQUATION
$x^2 - \frac43 x + \frac{1}{27} = 0$
$27x^2 - 36x + 1 = 0$
I am not sure if it's suppose to be:
$(\alpha + \beta) (\alpha^2 + 2\alpha \beta + \beta^2)$
Or
$(\alpha + \beta) (\alpha^2 + 3\alpha \beta + \beta^2)$
Also sorry about the formatting, if you don't mind fixing it for me. Not sure how to do it.
Thank You.
Comment: How do you get $\alpha^3+\beta^3=(\alpha + \beta) (\alpha^2 + 2\alpha \beta + \beta^2)?$
Comment: I think you can find alpha and beta, then find the polynomial with (x-alpha)*(x-beta).
Comment: @mfl $\alpha^2 + \beta^2 = (\alpha^2 + 2\alpha \beta + \beta^2)$ so i thought $\alpha^3 + \beta^3$ would be that multiplied by itself.
Comment: As you can check by multiplying the factors, $$\alpha^3 + \beta^3 = (\alpha + \beta)(\alpha^2 - \alpha\beta + \beta^2)$$
Answer: solving the equation we get
$x_1=1$ and $x_2=\frac{1}{3}$  thus we have $\alpha^3=1$ and $\beta^3=\frac{1}{27}$
and our equation is given by
$(x-1)(x-1/27)=0$ therefore we get
$27x^2-28x+1=0$
the equation $3x^2-4x+1=0$ is equivalent to
$x^2-\frac{4}{3}x+\frac{1}{3}=0$
after the formula for a quadratic equation we obtain
$x_{1,2}=\frac{2}{3}\pm\sqrt{\frac{4}{9}-\frac{3}{9}}$ thus we get $x_1=1$ or $x_2=\frac{1}{3}$
Comment: Can you please explain how you got 1.
Comment: In your first line, you meant $x_2 = \frac{1}{3}$.
Comment: i have corrected it thank you
Answer: Using the quadratic formula, we have $$\alpha, \beta = \frac{-(-4) \pm \sqrt{(-4)^2-4(3)(1)}}{6} \\ = \frac{4 \pm \sqrt{16-12}}{6} \\ = \frac{4 \pm 2}{6} \\ = 1, \frac{1}{3} $$ Hence a polynomial you could use with roots at $\alpha^3 = 1^3 = 1$ and $\beta^3 = \left(\frac{1}{3}\right)^3 = \frac{1}{27}$ would be $$f(x) = (x-1)\left(x-\frac{1}{27}\right) \\ = x^2 -\frac{28x}{27}+\frac{1}{27}$$ Or in general, for any constant $ C \neq 0$, then $C\cdot f(x)$ will have zeroes at $\alpha^3, \beta^3$


Pegar caminho de diretorio

Question: Eu quero pegar um diretorio do sistema, abrir uma janela e nessa janela eu seleciono um diretorio. Consigo selecionar arquivos com o OpenFileDialog mas diretorios não.
Answer: Pode utilizar a classe FolderBrowserDialog:
// Instancia a classe.
using (FolderBrowserDialog dirDialog = new FolderBrowserDialog())
{
    // Mostra a janela de escolha do directorio
    DialogResult res = dirDialog.ShowDialog();
    if (res == DialogResult.OK)
    {
        // Como o utilizador carregou no OK, o directorio escolhido pode ser acedido da seguinte forma:
        string directorio = dirDialog.SelectedPath;
    }
    else
    {
        // Caso o utilizador tenha cancelado
        // ...
    }
}

Alem do uso básico pode ainda permitir ao utilizador criar diretórios pela janela. Para isso coloque a seguinte propriedade a true:
dirDialog.ShowNewFolderButton = true;

Pode ainda decidir qual o directorio escolhido quando a janela e aberta. Para isso utilize a propriedade FolderBrowserDialog.RootFolder.
Answer: No lugar de usar OpenFileDialog use o controle folderBrowserDialog
Fonte
http://msdn.microsoft.com/en-us/library/aa984305%28v=vs.71%29.aspx

Pegar caminho de diretorio


Classify the main semantic relation of a sentence using keras

Question: I tried to ask in SO, but they told me to ask here.
I have a big dataset like this:
<code>RELATION<tab>SENTENCE
color<tab>The cat is black
color<tab>My dog is white
place<tab>Des Moines is in Iowa
place<tab>Des Moines is the capital of Iowa
is-a<tab>Des Moines is a city
is-a<tab>3D printer is a type of printer
is-a<tab>New Beetle was a car by Volkswagen
...
</code>
I need to build a classifier that, given a sentence, returns a relation as accurately as possible.
I have already programmed something with keras (python), but in this case I really don't know where to start from. For the moment I only realized that an important feature could be the order of the words in the sentence, but I don't know how to explot this.
Do you have some hint? E.g. about features, embeddings, hidden layers. May LSTM be a good NN? Why?
I hope this is not too broad, but I just need some hint.
Answer: A good start would be using some pre-trained embedding like word2vec to transform the sentences into lists of vectors. As opposed to other feature representations for text classification (e.g., TF-IDF) here the structure of the sentence is taken into account. So the first layer of your network could be this word2vec-based embedding; then, you can put some Conv1D/pooling layers, to end with a couple of dense layers and a softmax final layer. Of course, you will have to zero-pad some of the samples to make them all have the same length. You could also use LSTM to manage the sequential nature of words in  sentences. However, in my experience if your texts are relatively short and there are not huge length differences, the Conv1D/pooling combo will work well and  will be easier to train.
Your final architecture could look something like this:

We used that kind of network to solve a similar problem in a recent paper [1]. However, in this case the final layer wasn't using softmax, but a simple dense layer trained to perform metric learning [2].
[1] https://link.springer.com/article/10.1007/s10489-017-1109-7
[2] https://cs.nyu.edu/~sumit/research/assets/cvpr06.pdf


Is it possible to do graphics programming in AWK?

Question: I guess this is a question about what it means to be Turing complete. Awk is a programming language, and I've heard you can do anything with those, but aren't there physical limitations as well? I mean, you probably can't delete files with a minecraft red-stone computer. Similarly I imagine you can't do graphics with AWK.
What sort of extension would be necessary to AWK for it to be able to do graphics?
Comment: What do you mean by graphics programming?
Comment: Hmm... could you expand on that question?
Answer: The notion of Turing completeness refers to being able to compute any computable function (from natural numbers to natural numbers, or {0,1}* to {0,1}*, or the like). It is a somewhat abstract concept and does not refer to specifics of hardware like graphics (or USB ports or wireless connections or anything of that sort). It does not even talk of the behaviour of "always running" programs like (HTTP/FTP/ssh/etc) servers. It only talks of computations which take some finite input, and

Halt and produces a finite output, or
Run forever.

So it doesn't really make sense to relate Awk's Turing-completeness with its support for graphics libraries.
Comment: Very nice! Yeah: me and a friend were just joking about using AWK for graphics programming. Then we started thinking more seriously about why AWK might not be able to do that, and about what it means to be Turing Complete. You're right that this judgement doesn't make sense.
Answer: You can use awk to write to ASCII formats such as:

portable (black & white) bitmap (PBM)
portable graymap (PGM)
portable pixmap (PPM)

Then you can easily convert that to any other format desired using netPBM or ImageMagick, or Gimp, or any of dozens of other tools.
Awk can write graphics directly to the screen.

awk-raycaster is a 3D Doom-style game written in awk using ANSI graphics in a terminal. (Make sure you enlarge your terminal enough or it will apear jumbled.) https://github.com/TheMozg/awk-raycaster

awk-glib is a graphics library to use ANSI graphics to display surprisingly good (though somewhat blocky) animated images directly to the terminal. https://github.com/patsie75/awk-glib

.

awkGL is an extension to awk that lets awk produce high resolution 2D and 3D graphics directly. Unfortunately I can't persuade it to compile on my computer. https://github.com/takubo/awkGL
Comment: Late to the party, but this is awesome!!!
Answer: You can use the "system()"-command to call any program from within awk. I have used awk many times in combination with imagemagick, So, in principle you could use awk for graphics programming. But most probably you would prefer Tcl with Tk for these tasks. Awk was intended for text processing long before graphical displays, Tcl with Tk was made for rapid prototyping (with graphics and gui).
HTH Chris
Answer: I have used awk to do Graphics/Image Processing in many answers on StackOverflow. No need to repeat them all but here are a few...

Convert RGB array to image
Highlighting pixels by Hue
Box in characters identified by OCR
Cut image into pieces and make randomised montage


Interpretation of difference in difference with a trend break term included

Question: If I expand a difference in difference to the following type of specification:
\begin{split}
y_{c,t} = \beta_1(\tau*treat_c) + \beta_2(post_t * treat_c) + \beta_3(post_t*treat_c*\tau) + \mu_c + \eta_{t} + \epsilon_{ct}
\end{split}
where if $\beta_1=\beta_3=0$ collapses to the standard two way fixed effect/difference in difference specification (let c = county and t = year, and the latter three terms are the county and time fixed effects, respectively and then the error term). $\tau$ is a linear time trend. I understand that this is now allowing the treatment counties to have differential linear pre trends ($\beta_1$), and allowing the treatment to have a trend break, so the effect of treatment at time $\tau$ is given by:
$\beta_2 + \beta_3*\tau$
So my question is, say I plug in $\tau$ = 2. Is $\beta_2 + \beta_3*2$ giving me the effect $\textit{at}$ year 2, or is it giving me the cumulative effect of treatment up to year 2?
Comment: What is $\tau$ in this example? A linear time trend?
Comment: Yes it is, sorry about that. I will edit the question to clarify that
Answer: The model exhibits some redundancies. In practice, we typically multiply $\mu_c$ with the linear term. The treatment dummy will drop out of the model depending upon how you order your variables, but it shouldn't matter with respect to the identification of the difference-in-differences coefficient. Here is the equation I see most often estimated in practice:
\begin{equation}
y_{ct} = \beta_c(\mu_{c} \times \tau) + \mu_{c} + \eta_{t} + \delta(T_c \times P_t ) + \epsilon_{ct}
\end{equation}
where each unit $c$ receives its own unique time trend, hence why $\beta_c$ is $c$-subscripted. In the foregoing equation, the treatment effect is given by $\delta$, even in the presence of a unit-specific time trend. If you've seen applied work where the time trend was multiplied with $T_c$ and $P_t$ then please provide a reference. I have yet to see this executed in practice.
As far as setting $\tau = 2$, I see three possible scenarios. The first scenario is a time trend variable that is set at a particular value for all observations. I don't think this is what you're proposing since the trend term is now time invariant and will drop out of the model; it is collinear with the unit fixed effects.
The second scenario is a trend term that is binned at a particular value (i.e., $\tau = 1, \bar{2}$). In other words, $\tau$ is assumed to be constant once units reach the second time period (i.e., $\tau = 1, 2, ..., 2$). In this setting, you're assuming each unit's trend is linear up to a specific point. I don't think this is what you're proposing either, but it isn't outside the realm of possibilities.
The third scenario is manually setting $\tau = 2$ inside of the model formula and interacting it with each unit—separately. The model evaluates any instance where $\tau = 2$ as a time shock. The indicator for the second time period is collinear with the time fixed effects. Note how you're no longer estimating unit-specific linear time trends. Instead, this is more of a unit-year effect. Instead of a common shock experienced by all units (i.e., time effect), you're now allowing each unit to have its own effect in 2011. For example, the shock in 2011 may vary across jurisdictions. This is not how we estimate accumulating treatment effects.
The interaction of $\tau$ with the traditional difference-in-differences product term is curious. For instance, $P_t$ is a post-treatment indicator. Assuming you acquired serial observations on units before treatment, then I assume $P_t$ switches on in a later period, much later than the second time period. Typically we want to observe how effects accumulate in the post-period.
Now suppose you want the treatment effect at year 2, which I assume is the year before the real exposure of interest, then interact $T_c$ with a time dummy (i.e., $P_{t = 2011}$). If this is a period before some intervention, then it is, technically, a placebo treatment. In other words, we shouldn't be observing strong non-zero effects before the treatment actually begins!
Demonstrating "cumulative" treatment effects is vastly different than including unit-specific linear time trends. If you're estimating the latter, then I recommend multiplying a linear trend with your unit dummies. Do not interact the linear term with all variables in your model.


Residuals in a linear model are independent but sum to zero; isn't it a contradiction?

Question:
The sum of the residuals in a linear model equals zero.
The residuals in a linear model are independent.

Isn't it a contradiction?
Comment: You confuse two meanings of "residual."  The first bullet refers to the differences between the data and their *fitted values.*  The second refers to a collection of random variables that are used to model the differences between the data and their *expectations.*
Comment: The second thing are more often called errors (which has the benefit of clearly distinguishing them from the sample quantities in your first statement). Errors (population quantities) are independent, but residuals (sample quantities) are not.
Answer: The question appears to confuse two meanings of "residual."

The first bullet refers to the differences between the data and their fitted values.
The second bullet refers to a collection of random variables that are used to model the differences between the data and their expectations.

This might become clearer upon examining the simplest possible example: estimating the mean of a population, $\mu$, by taking two independent observations from it (with replacement).  The data can be modeled by an ordered pair of random variables $(X_1, X_2)$.  The "fitted values" are the estimated mean,
$$\bar X = (X_1 + X_2)/2.$$
This number is the fit for each of the two observations.

The residuals are the differences between the data and the fit.  They consist of the ordered pair $$(e_1, e_2) = (X_1 - \bar X, X_2 - \bar X) = ((X_1-X_2)/2, -(X_1-X_2)/2).$$  Consequently $e_2 = -e_1$, showing the residuals are dependent.
An alternative model of these data uses the random variables $$(\epsilon_1, \epsilon_2) = (X_1 - \mu, X_2 - \mu).$$ Often these random variables are called "errors" but sometimes they are also called "residuals."  Since the $X_i$ are independent, and $\mu$ is just some constant, the $\epsilon_i$ are also independent.

It might be of interest to note that $e_1 + e_2 = 0$ whereas $\mathbb{E}(\epsilon_1) = \mathbb{E}(\epsilon_2) = 0$.  The former is a true dependence among random variables whereas the latter is merely a constraint concerning the underlying model.
Answer: First, let's clarify the terminology, which can be different in different fields. For instance, in econometrics we differentiate between errors and residuals. Let's look at a simple model:
$$y_i=\beta_0+\beta_1 x_i+\varepsilon_i$$
Here, $\varepsilon_i$ is called errors. They are not observable, i.e. unknowns. The parameters (betas, coefficients) of the model are also unknown.
We can try to fit and estimate the model, and obtain the parameter estimates $\hat\beta_0,\hat\beta_1$, then we can obtain the residuals:
$$\hat\varepsilon_i=y-\hat\beta_1 x -\hat\beta_0$$
So, residuals $\hat\varepsilon_i$ are estimates of unobserved errors $\varepsilon_i$.
Why is this so important? Because you mixed and matched several concepts from different places in your question.
The first question alludes to the technical property of linear models. When you estimate the model, $\hat\beta_0$ will absorb the mean of errors making the residual mean zero.
The second question sounds like one of the assumptions of Gauss-Markov theorem, but misplacing the errors with residuals. The theorem's assumption is about errors. It may or may not hold true. Both residuals and errors may show autocorrelation, for instance.
Comment: +1 The edit gets this answer just right, so I have deleted my previous comment.
Answer: The residuals  are certainly not independent. Assume that the true errors $u_i, i=1,...,n$ are fully independent. In a linear model
$$y_i = \mathbb x_i'\beta + u_i \implies u_i = y_i - \mathbb x_i'\beta$$
the residuals equal, under OLS estimation
$$\hat u_i = y_i - \mathbb x_i'\hat \beta(\mathbf y, \mathbf X) = y_i - \mathbb x_i' \left(\mathbf X' \mathbf X\right)^{-1}\mathbf X'\mathbf y $$
$$= y_i - \mathbb x_i' \left(\mathbf X' \mathbf X\right)^{-1}\mathbf X'\left (\mathbf X \beta + \mathbf u\right) $$
$$\implies \hat u_i = u_i -\mathbb x_i' \left(\mathbf X' \mathbf X\right)^{-1}\mathbf X'\mathbf u$$
Considering
$$E(\hat u_i \hat u_j) = E(u_iu_j)  - E\left[u_i\mathbb x_j' \left(\mathbf X' \mathbf X\right)^{-1}\mathbf X'\mathbf u\right]\\-E\left[u_j\mathbb x_i' \left(\mathbf X' \mathbf X\right)^{-1}\mathbf X'\mathbf u\right] + E\left[\mathbb x_i' \left(\mathbf X' \mathbf X\right)^{-1}\mathbf X'\mathbf u\mathbf u'\mathbf X \left(\mathbf X' \mathbf X\right)^{-1}\mathbb x_j'\right]$$
we can see that it is not equal to zero, because for example,
$$ E\left[u_i\mathbb x_j' \left(\mathbf X' \mathbf X\right)^{-1}\mathbf X'\mathbf u\right] \neq 0$$
since $u_i$ exists in $\mathbf u$ also, and so we get $u_i^2$ whose conditional or unconditional expected value cannot be eqaul to zero (why?).
So the residuals are not independent, even if the true errors are, and even if the regressors are independent from the true errors.


What's the final package name of an activty after gradle merges manifests in a app+library project?

Question: I have a project that is formed by a project and a library project. Both of them have their own manifest.
The library project has all the acitivities definitions (and practically all the code). The app project has a manifest where only an Application class is defined. (If you ask why i have this structure is because i have a common library and i create multiple app projects to change themes and api calls)
My question is, when i have to define my initial activity class name in platforms, i.e Facebook, should i use my library project package name as it is defined in its manifest? or gradle merges it with my app project package name?
Example:
com.app.finalproject is my application package name.
com.commonlibrary.ui.SplashActivity is my common package name of my initial activity and it is defined in my common library project manifest.
So, after gradle merges the two manifest what is the package name of my SplashActivity ? is it still com.commonlibrary.ui.SplashActivity o is it something like com.app.finalproject.ui.SplashActivity ?
Thanks in advance.
Answer: Activities do not have a package name, strictly speaking.
The Java class that implements an activity will be in a Java package. That package is denoted by the package line at the top of the class file, along with the directory in which the Java class resides. None of that is affected by the manifest merger process.
Sometimes, you need a full ComponentName of an activity or other component. In that case, the package portion of the ComponentName will be the application ID. The Java class portion of the ComponentName will still use its regular Java package.
Using your example, if I am understanding it correctly, the activity is still com.commonlibrary.ui.SplashActivity. The ComponentName for that activity would be com.app.finalproject/com.commonlibrary.ui.SplashActivity.
Comment: Hi, by package name i meant the java package where the Activity is located.
And you are right. I've just decompiled with apktool my apk and in the merged manifest the activity is still com.commonlibrary.ui.SplashActivity.

Thanks for your answer!


Can I test OpenID Provider on server from a Relying Party in my local machine? - DotNetOpenAuth

Question: I had created a provider and a Relying Party in Visual Studio using the DNOA library and it worked well. Then, I moved the provider to the server and tried to test it from the Relying Party from my local machine. The RP gives the error of 'No OpenID endpoint found'.
I think I am missing something in Web.config. In the WhitelistHost attribute, I have added the wildcard "*" which should make the provider to accept requrests from anyone (for testing purpose). Is there anything else that I am not aware of? I am relatively new to the topic.
Web.config -

<uri>
    <idn enabled="All"/>
    <iriParsing enabled="true"/>
</uri>

<dotNetOpenAuth>
    <openid>
        <provider>
            <security requireSsl="false" />
            <behaviors>

            </behaviors>
        </provider>
    </openid>
    <messaging>
        <untrustedWebRequest>
            <whitelistHosts>

                <add name="localhost"/>
                <add name="*"/>
            </whitelistHosts>
        </untrustedWebRequest>
    </messaging>

    <reporting enabled="true" />
</dotNetOpenAuth>

<appSettings>
    <add key="whitelistedRealms" value="http://localhost:39165/;http://othertrustedrealm/;http://localhost/;http://localhost:4856/"/>

    <add key="ImplicitAuth" value="true"/>
</appSettings>
....

Edit: I am not sure if it matters but the server uses SSL.
Answer: Try being explicit in your whitelisthosts configuration - put the address of your server in.
Short of this, turn on logging on both the RP and the ID server. Step through the process on the RP.
Also, do you have a proxy between your dev PC and the internet ? if so you will need to tell your RP code how to communicate through it.
Answer: I am not sure if you ever found an answer to this question, but I had the same problem. I was able to repair the issue but Whitelisting localhost on not only the Provider end but also the Relying Part end as well.