text:
Q: How to create a header layer that would stay the same over several ViewControllers? I'd like to create a header that wouldn't move at all in my application that contains several ViewControllers. My header is simply a view containing a logo (UIImageView), a UIButton and a UILabel. I've heard that I can do that with a UINavigationController or by adding a subview to the UIWindow, but it doesn't work for me (maybe I'm doing it wrong). My main issue is to keep it fixed at the top of the screen (like a hud?) during segue animations, and I would also need to be able to modify the content of the UILabel during the application process.
I work on Xcode 13 with a storyboard for iOS 15 on iPad.
Hope I've been clear enough.
EDIT
It appears that inserting a view in the UIWindow would be the best solution for me, though I'm not sure how to do that properly. All the examples I find don't work and are deprecated/outdated.

A: You can create a custom UITabBarController and then add it to SceneDelegate as -
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        let vc = CustomTab()
        self.window?.rootViewController = vc
        self.window?.makeKeyAndVisible()
        .......

In custom TabBar add all your navigation controllers as -
viewControllers = [nav1, nav2, nav3, nav4]

And in every view controller class you can hide, change or modify the tabbar prperties.

A: So finally I succeeded using the method of Imran to which I added few things to match what I needed.
I have a singleton class for my header ViewController that contains the elements I needed inside of it.
let HEADER = STORYBOARD.instantiateViewController(withIdentifier: "HeaderLayer") as? HeaderViewController

class HeaderViewController: UIViewController {

    @IBOutlet weak var ThemeLabel: UILabel!
    @IBOutlet weak var DifficultyImage: UIImageView!
    @IBOutlet weak var ExitButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        // ...
    }

    // Methods
}

And here's how I put my header in the UIWindow to make it appear at the top of the screen, where it will stay fixed even during segue animations. I change the frame because in full screen it would disable the interactions for the views underneath.
let STORYBOARD = UIStoryboard(name: "Main", bundle: nil)

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        HEADER!.view.frame = CGRect(x: 0, y: 0, width: 1366, height: 142)
        window?.addSubview(HEADER!.view)
        window?.makeKeyAndVisible()

        // ...
    }
    // ...
}

Then it's necessary to bring the header to front everytime one of my ViewControllers appears.
class ViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        let window = UIApplication.shared.keyWindow
        window?.bringSubviewToFront(HEADER!.view)

        // ...
    }
}

I'm not using any UINavigationController or UITabBarController, but it is possible with this method.
The only problem I encountered is that UIApplication.shared.keywindow is deprecated. But it doesn't seem to cause any issue and I didn't find a solution yet.


text:
Q: Deploying a pre-built container image in Google Kubernetes Engine I have a docker image in my local machine which I have pushed to Google Cloud Containers.
Now I want to deploy this image in Google Kubernetes Engine.
I am following the steps in below link -
https://cloud.google.com/cloud-build/docs/deploying-builds/deploy-gke#deploying_a_pre-built_container_image
I will create a YAML deployment config file.
My problem is where Do I need to keep this file in google cloud so that it can be used for deployment.
Also, in YAML file what is nginx - I have used the default one. Where do I need to keep this YAML config file.
ms_aggregator is name of my image
 apiVersion: "apps/v1"
kind: "Deployment"
metadata:
  name: "deployment-aggregator"
spec:
  replicas: 1
  selector:
    matchLabels:
      app: "nginx-1"
  template:
    metadata:
      labels:
        app: "nginx-1"
    spec:
      containers:
      - name: "nginx-1"
        image: "ms_aggregator"

A: You need to use the full image name, that usually includes the image registry and repository.
From the example:
"gcr.io/cloud-builders/gke-deploy"

Usually, the GCP format is
<docker registry host>/<gcp-project-name>/<image-name>

For you, this is likely:
gcr.io/<your-gcp-project-name>/ms_aggregator

But if you have choosed to use a registry in a different location, the registry name could be e.g. eu.gcr.io

A: You are mixing two things. The docs which you are referring is of GKE deploy builder which is a wrapper around kubectl. This will deploy the built image using Google Cloud's recommended  deployment mechanism and you do not need a Kubernetes deployment yaml file. This is more of CI/CD a style.
Now if you want to deploy the pre built image using a Kubernetes deployment yaml that you have already you do not need GKE deploy and you can configure and use kubectl directly for this.
Following this guide here configure kubectl to access GKE cluster.
After that you can do kubectl apply -f deployment.yaml to deploy the image as a container in GKE. The deployment.yaml file can be anywhere in the system where you are configuring kubectl

redpajama_set_name: RedPajamaStackExchange


text:
Q: Paint a JPanel to a BufferedImage or Print it without rendering it to screen first Picture this... A program GUI JFrame that is split in 2, EAST and WEST. The first JPanel is just a print preview screen. The EAST side of the JFrame is where the user can create a 1 2 or 3 size image. The user clicks the "Add" button and the defined image on the right goes to the panel on the left. So if the user clicks "Add" 3 times with different size images, then the panel uses FlowLayout to organize the added panel images added on the left.
When you run this code, you can see a sorta idea of what I want. Really what would be nice is to create all this off-screen and call it MainPanel. Then have printPreview extend MainPanel and scale it down for screen view. And have the Printable method paint the MainPanel into the print method which would be a correct size.
So my question...
-Can you copy or paint a JPanel before it is rendered on the screen?
-Is there a better way to do what I want, I FlowLayout solves what I want amazingly, so a JPanel seems to be the answer unless there is something I do not know of.
Ok now that that is pictured. I have built some code that is about as SSCCE as I can get.
Guys I have tried asking this question at New To Java forums and they just do not respond, I am not double posting on purpose, I completely rewrote this from scratch.
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.print.*;
import java.awt.event.*;

public class PrintGrid extends JFrame {

    Paper paper = new Paper();

    PrintGrid() {
        super("Check out this grid panel");
        setSize(672, 750);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        add(paper);
        setVisible(true);

    } // end PrintGrid constructor

    // **************************
    // ****** PAPER CLASS *******
    // **************************
    private class Paper extends JPanel {

        final int PAPER_X = 672, PAPER_Y = 975, UNIT = 12, DPI = 72;
        X1 x1a = new X1(), x1b = new X1(), x1c = new X1();
        X2 x2a = new X2(), x2b = new X2(), x2c = new X2();
        X3 x3a = new X3(), x3b = new X3(), x3c = new X3();

        Paper() {
            setPreferredSize(new Dimension(PAPER_X, PAPER_Y));
            setBackground(Color.GRAY);
            setLayout(new FlowLayout(FlowLayout.LEADING));

            //Users will manually add different sizes to this sheet.
            add(x1a);
            add(x2a);
            add(x3a);
            add(x1b);
            add(x1c);
            add(x2b);
            add(x3b);
        }

        // ******* Parent Class for GridUnits *******
        abstract class GridUnit extends JPanel {

            MouseListen ml = new MouseListen();
            float alpha = 1.0f;

            GridUnit() {
                this.addMouseListener(ml);
            }

            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                this.setBackground(Color.BLACK);

                Graphics2D g2 = (Graphics2D) g;
                g2.setComposite(makeComposite(alpha));

                g.setColor(Color.WHITE);
                g.drawRect(0, 0, this.getWidth()-1, this.getHeight()-1);

                g.setColor(Color.darkGray);
                g.fillRect(15, 15, this.getWidth()-30, this.getHeight()-30);

            } // end paintComponent.

            private AlphaComposite makeComposite(float alpha) {
                int type = AlphaComposite.SRC_OVER;
                return(AlphaComposite.getInstance(type, alpha));
            }

            void click() {
                setVisible(false);
            }
            void entered() {
                alpha = 0.8f;
                repaint();

            }
            void exited() {
                alpha = 1.0f;
                repaint();
            }

            class MouseListen extends MouseAdapter {
                public void mouseEntered(MouseEvent event) {
                    entered();
                }
                public void mouseExited(MouseEvent event) {
                    exited();
                }
                public void mousePressed(MouseEvent event) {
                    click();
                }
            }

        } // end GridUnit class

        class X1 extends GridUnit {
            X1() {
                setPreferredSize(new Dimension(UNIT*13, UNIT*18));
            }
        } // end X1 Class

        class X2 extends GridUnit {
            X2() {
                setPreferredSize(new Dimension(UNIT*26, UNIT*18));
            }
        } // end X1 Class

        class X3 extends GridUnit {
            X3() {
                setPreferredSize(new Dimension(UNIT*39, UNIT*18));
            }
        } // end X1 Class

    } // end Paper class.

    public static void main(String[] args) {
        new PrintGrid();
    } // end main method.

} //  end PrintGrid class.

A: It's quite trivial to paint any Java component to an offscreen image, from which you can do as you please, including copying a portion or scaled image to a final target.
Subclass JComponent and override void paintComponent(Graphics g).  Paint to a BufferedImage, then copy the image to the target component.  Off the top of my head, something like:
void paintComponent(Graphics g) {
    BufferedImage img=new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_ARGB);
    Graphics2D    gph=(Graphics2D)img.getGraphics();

    // paint to gph here
    gph.dispose();

    g.drawImage(img);  // paints the contents of img to the component's graphics context.
    }


text:
Q: How can exec() be used with command line input? Can someone please explain the use of exec functions when the input is given in command line? For example, if entered:
$ ./a.out ls -l

where a.out is the executable file. It would be great if you could share examples so that I can get clarification.
P.S. I've already gone through this thread, but I need clarification with command line inputs primarily.


text:
Q: Radio Button ripple cuts off
In the above image the Radio Button delivery ripple cuts off when clicking. I tried padding. But padding only applies for text not the button. I can able to get full ripple in the upper and lower sides by setting height to radio button but I'm unable to fix the ripple cuts in left side.
My XML:

<RelativeLayout
    android:id="@+id/rl_menu"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/primary">

    <ImageView
        android:id="@+id/goBackBtn"
        style="@style/BackArrayStyle" />

    <TextView
        android:id="@+id/actionBarTitle"
        style="@style/ActionBarTextStyle"
        android:layout_width="wrap_content"
        android:layout_toEndOf="@+id/goBackBtn"
        android:lines="1"
        android:maxLines="1"
        android:text="Filter" />

    <ImageView
        android:id="@+id/imgReset"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"
        android:layout_marginStart="10dp"
        android:background="@drawable/image_primary_ripple"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:src="@drawable/ic_reset_black" />
</RelativeLayout>

<RadioGroup
    android:id="@+id/radio_group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/rl_menu"
    android:layout_margin="40dp"
    android:gravity="center"
    android:layout_centerHorizontal="true"
    android:orientation="horizontal">

    <RadioButton
        android:gravity="center"
        android:id="@+id/radioDelivery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delivery" />

    <RadioButton
        android:id="@+id/radioPickUp"
        android:layout_marginStart="30dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pick Up" />

</RadioGroup>

<RelativeLayout
    android:id="@+id/rlSeekBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/radio_group">

    <TextView
        android:id="@+id/tvRadiusLabel"
        android:layout_width="170dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="30dp"
        android:text="Pick Up Radius"
        android:textSize="17sp"
        android:textStyle="bold" />

    <View
        android:id="@+id/div_radius"
        android:layout_width="match_parent"
        android:layout_height=".3dp"
        android:layout_below="@id/tvRadiusLabel"
        android:layout_marginBottom="30dp"
        android:layout_marginEnd="30dp"
        android:layout_marginStart="30dp"
        android:layout_marginTop="10dp"
        android:background="@color/colorAccent" />

    <SeekBar
        android:padding="10dp"
        android:id="@+id/seekBarDistance"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/div_radius"
        android:layout_centerHorizontal="true"
        android:max="20"
        android:thumb="@drawable/ic_seek_bar_thumb"
        android:maxHeight="15dp"
        android:minHeight="10dp"
        android:progress="1" />

    <TextView
        android:id="@+id/tvRadius"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_below="@id/seekBarDistance"
        android:layout_marginEnd="30dp"
        android:text="1 Km" />
</RelativeLayout>

<TextView
    android:id="@+id/tvSortBy"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/rlSeekBar"
    android:layout_marginStart="30dp"
    android:layout_marginTop="20dp"
    android:text="Sort By"
    android:textSize="17sp"
    android:textStyle="bold" />

<View
    android:id="@+id/div_seek_bar"
    android:layout_width="match_parent"
    android:layout_height=".3dp"
    android:layout_below="@id/tvSortBy"
    android:layout_marginBottom="20dp"
    android:layout_marginEnd="30dp"
    android:layout_marginStart="30dp"
    android:layout_marginTop="10dp"
    android:background="@color/colorAccent" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/div_seek_bar"
    android:layout_centerHorizontal="true"
    android:orientation="vertical"
    android:visibility="gone">

    <TextView
        android:id="@+id/btnRating"
        android:layout_width="170dp"
        android:layout_height="40dp"
        android:layout_marginBottom="20dp"
        android:background="@color/primary"
        android:drawableStart="@drawable/ic_star_half_white"
        android:gravity="center_vertical"
        android:paddingStart="7dp"
        android:text="     Rating"
        android:textColor="@color/white"
        android:textSize="15sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/btnDistance"
        android:layout_width="170dp"
        android:layout_height="40dp"
        android:layout_marginBottom="20dp"
        android:background="@color/primary"
        android:drawableStart="@drawable/ic_near_me_white"
        android:gravity="center_vertical"
        android:paddingStart="7dp"
        android:text="     Distance"
        android:textColor="@color/white"
        android:textSize="15sp"
        android:textStyle="bold" />
</LinearLayout>

<RadioGroup
    android:padding="20dp"
    android:id="@+id/radio_group1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/div_seek_bar"
    android:layout_marginEnd="40dp"
    android:layout_marginStart="40dp"
    android:gravity="center"
    android:orientation="horizontal">

    <RadioButton
        android:id="@+id/radioRating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Rating" />

    <RadioButton
        android:id="@+id/radioDistance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="30dp"
        android:text="Distance" />

</RadioGroup>

<Button
    android:id="@+id/btnApply"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:background="@color/primary"
    android:text="Apply Filter"
    android:textColor="@color/white"
    android:textStyle="bold" />

How to fix this Ripple issue? Any help would be appreciated...

A: Here I made some changes in your code and it's working fine on my devices. Check it if it works for you:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">

<RelativeLayout
    android:id="@+id/rl_menu"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/Primary">

    <ImageView
        android:id="@+id/goBackBtn"
        style="@style/BackArrayStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/actionBarTitle"
        style="@style/ActionBarTextStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@+id/goBackBtn"
        android:layout_toRightOf="@+id/goBackBtn"
        android:lines="1"
        android:maxLines="1"
        android:text="Filter" />

    <ImageView
        android:id="@+id/imgReset"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:layout_marginStart="10dp"
        android:background="@drawable/image_primary_ripple"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:src="@drawable/ic_reset_black" />

    <RadioGroup
        android:id="@+id/radio_group"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_margin="40dp"
        android:gravity="center"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/radioDelivery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Delivery" />

        <RadioButton
            android:id="@+id/radioPickUp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:layout_marginStart="30dp"
            android:text="Pick Up" />

    </RadioGroup>

    <RelativeLayout
        android:id="@+id/rlSeekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/radio_group">

        <TextView
            android:id="@+id/tvRadiusLabel"
            android:layout_width="170dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:layout_marginStart="30dp"

            android:text="Pick Up Radius"
            android:textSize="17sp"
            android:textStyle="bold" />

        <View
            android:id="@+id/div_radius"
            android:layout_width="match_parent"
            android:layout_height=".3dp"
            android:layout_below="@id/tvRadiusLabel"
            android:layout_marginBottom="30dp"
            android:layout_marginEnd="30dp"
            android:layout_marginStart="30dp"
            android:layout_marginTop="10dp"
            android:background="@color/colorAccent" />

        <SeekBar
            android:id="@+id/seekBarDistance"
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:layout_below="@+id/div_radius"
            android:layout_centerHorizontal="true"
            android:max="20"
            android:thumb="@drawable/ic_seek_bar_thumb"
            android:maxHeight="15dp"
            android:minHeight="10dp"
            android:padding="10dp"
            android:progress="1" />

        <TextView
            android:id="@+id/tvRadius"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_below="@id/seekBarDistance"
            android:layout_marginEnd="30dp"
            android:layout_marginRight="30dp"
            android:text="1 Km" />
    </RelativeLayout>

    <TextView
        android:id="@+id/tvSortBy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rlSeekBar"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_marginTop="20dp"
        android:text="Sort By"
        android:textSize="17sp"
        android:textStyle="bold" />

    <View
        android:id="@+id/div_seek_bar"
        android:layout_width="match_parent"
        android:layout_height=".3dp"
        android:layout_below="@id/tvSortBy"
        android:layout_marginBottom="20dp"
        android:layout_marginEnd="30dp"
        android:layout_marginStart="30dp"
        android:layout_marginTop="10dp"
        android:background="@color/colorAccent" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/div_seek_bar"
        android:layout_centerHorizontal="true"
        android:orientation="vertical"
        android:visibility="gone">

        <TextView
            android:id="@+id/btnRating"
            android:layout_width="170dp"
            android:layout_height="40dp"
            android:layout_marginBottom="20dp"
            android:background="@color/primary"
            android:drawableStart="@drawable/ic_star_half_white"
            android:drawableLeft="@drawable/ic_star_half_white"
            android:gravity="center_vertical"
            android:paddingLeft="7dp"
            android:paddingStart="7dp"
            android:text="     Rating"
            android:textColor="@color/white"
            android:textSize="15sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/btnDistance"
            android:layout_width="170dp"
            android:layout_height="40dp"
            android:layout_marginBottom="20dp"
            android:background="@color/primary"
            android:drawableStart="@drawable/ic_near_me_white"
            android:drawableLeft="@drawable/ic_near_me_white"
            android:gravity="center_vertical"
            android:paddingEnd="7dp"
            android:paddingStart="7dp"
            android:text="     Distance"
            android:textColor="@color/white"
            android:textSize="15sp"
            android:textStyle="bold" />
    </LinearLayout>

    <RadioGroup
        android:id="@+id/radio_group1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/div_seek_bar"
        android:layout_marginEnd="40dp"
        android:layout_marginStart="40dp"
        android:gravity="center"
        android:orientation="horizontal"
        android:padding="20dp">

        <RadioButton
            android:id="@+id/radioRating"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Rating" />

        <RadioButton
            android:id="@+id/radioDistance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:layout_marginStart="30dp"
            android:text="Distance" />

    </RadioGroup>

    <Button
        android:id="@+id/btnApply"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:background="@color/primary_text"
        android:text="Apply Filter"
        android:textColor="@color/white"
        android:textStyle="bold" />
</RelativeLayout>

Hope it helps.

A: I found the problem and fixed it. My team turned off hardware acceleration to fix another issue in the project.
I removed android:hardwareAccelerated="false" in the manifest. Now it's working fine.
Thanks for your help guys :)


text:
Q: Return array object from a multi-dimensional array of objects that contains a specific Value I'm trying to create a function that acts like a search mechanism which goes through an array of objects and returns a particular array object which contains a particular value (search parameter) in this array
var jobs= [
  {
    "startDate": "5/2017",
    "endDate": null,
    "isCurrent": true,
    "seniority": "Senior",
  },
  {
    "startDate": "5/2013",
    "endDate": "5/2019",
    "isCurrent": false,
    "seniority": "Junior",
  },
]

I want to create a function where you provide an array, array key and an array value i.e
nameOfFunction(jobs,"seniority","Senior")
and it returns/logs
{"startDate": "5/2017","endDate": null,"isCurrent": true,"seniority": "Senior",},

A: The array's filter method does this, but if you wanted to wrap it, you could do something like this...

var jobs= [
  {
    "startDate": "5/2017",
    "endDate": null,
    "isCurrent": true,
    "seniority": "Senior",
  },
  {
    "startDate": "5/2013",
    "endDate": "5/2019",
    "isCurrent": false,
    "seniority": "Junior",
  },
]

const nameOfFunction = (ar, key, val) => ar.filter(obj=>obj[key]===val);

var results = nameOfFunction(jobs,"seniority","Senior")
console.log(results);

A: You can use filter:

var jobs= [
  {
    "startDate": "5/2017",
    "endDate": null,
    "isCurrent": true,
    "seniority": "Senior",
  },
  {
    "startDate": "5/2013",
    "endDate": "5/2019",
    "isCurrent": false,
    "seniority": "Junior",
  },
]

const findObject = (obj, prop, value) => obj.filter(obj => obj[prop] === value)

console.log(findObject(jobs, 'seniority', 'Senior'))

EDIT:

var jobs= [
  {
    "startDate": "5/2017",
    "endDate": null,
    "isCurrent": true,
    "seniority": "Senior",
  },
  {
    "startDate": "5/2013",
    "endDate": "5/2019",
    "isCurrent": false,
    "seniority": "Junior",
  },
]

const findObject = (obj, prop, value, key) => obj.filter(obj => obj[prop] === value).map(obj => obj[key])

console.log(findObject(jobs, 'seniority', 'Senior', 'startDate'))

A: You could use the filter method on your passed in array. Here I have also used destructuring assignment to get the value (v) of the current object from the passed in key. I then compare the value of the object (v) with the val passed into the function to see whether it should be kept in the new array.
See example below:

const jobs= [
  {
    "startDate": "5/2017",
    "endDate": null,
    "isCurrent": true,
    "seniority": "Senior",
  },
  {
    "startDate": "5/2013",
    "endDate": "5/2019",
    "isCurrent": false,
    "seniority": "Junior",
  },
];

const filterArr = (arr, key, val) =>
  arr.filter(({[key]:v}) => v===val);

console.log(filterArr(jobs, "seniority", "Senior"));

A: You may try out like,

var jobs= [
  {
    "startDate": "5/2017",
    "endDate": null,
    "isCurrent": true,
    "seniority": "Senior",
  },
  {
    "startDate": "5/2013",
    "endDate": "5/2019",
    "isCurrent": false,
    "seniority": "Junior",
  },
];

// This function will return array of filtered elements
function searchArray(array,propertyKey,propertyValue){
  return array.filter(function(a){
      return a[propertyKey] === propertyValue;
  });
}

console.log(searchArray(jobs, 'seniority', 'Senior'));

// With new way

function searchArrayNewMethod(array,propertyKey,propertyValue){
  return array.filter( a => a[propertyKey] === propertyValue);
}

console.log(searchArrayNewMethod(jobs, 'seniority', 'Senior'));


text:
Q: is there any difference in validation of validates_uniqueness_of and uniqueness? class Category < ApplicationRecord
    validates :name ,presence: true
    validates_uniqueness_of :name
end

class Category < ApplicationRecord
    validates :name ,presence: true,uniqueness: true
end

is there any difference in validation of the given two models?

A: There's two ways to accurately answer this question:
1 - It behaves in exactly the same way.
In this sense, there's no difference. validates_uniqueness_of generates exactly the same validation as the :uniqueness flag on validates.
2 - There are reasons to do it with the flags
In terms of reading the models, the flags help because they allow you to put all the validations on an attribute (here, it's name) in the same place. So when you rad down, you see validations on name and you can be confident you know what they all are on that line.
It's also worth noting that the flags are a newer style and it's probable the older, more wordy style, will be removed from Rails at some point in the future.


text:
Q: How can i refresh a xaml page with WPF? i want to refresh a xaml page with wpf but i dont know how can i do this...
I can't do this :
NavigationService?.Navigate(new MainWindow());

i've try this one :
this.NavigationService.Refresh();

but still not working can you help me ?


text:
Q: Pandas : Change values of a range of cells using another dataframe I hope you're doing well.
So I have two dataframes, and I want to change the values of a specific range using the other dataframe as following :
So I have these two dataframes
Dataframe 1 :

    A   B   C
0   foo 2   3
1   foo 9   nan
2   foo 1   4
3   bar 90  1
4   boo 12  89

Dataframe 2 :

    M   N   O
0   foo 8   19
1   foo 3   8
2   foo 5   nan
3   bar 0   16
4   boo 1   100

So I want to replace the values of B and C concerning the 'foo' item (column A) in dataframe 1 by the values of N and O concerning the 'foo' item (column M) that exist in dataframe 2 as following :
Dataframe 1 :

    A   B   C
0   foo 8   19
1   foo 3   8
2   foo 5   nan
3   bar 90  1
4   boo 12  89

A: You can use pandas.DataFrame.where with a condition on df1['A']:
df1[['B', 'C']] = df1[['B', 'C']].where(~df1['A'].eq('foo'), df2[['B', 'C']])

or the other way around:
df1[['B', 'C']] = df2[['B', 'C']].where(df1['A'].eq('foo'), df1[['B', 'C']])

If the columns in df2 have a different name, you can access the underlying numpy array with .values:
df1[['B', 'C']] = df1[['B', 'C']].where(~df1['A'].eq('foo'), df2[['N', 'O']].values)

A: df1 = pd.DataFrame({'A': ['foo','foo','foo','bar','boo'],'B': [2,9,1,90,12],'C':[3,np.nan,4,1,89]})
df2 = pd.DataFrame({'A': ['foo','foo','foo','bar','boo'],'B': [8,3,5,0,1],'C':[19,8,np.nan,16,100]})

df1.loc[df1['A']=='foo',['B','C']] = df2[df2['A']=='foo'][['B','C']]
df1

Gives:
    A   B   C
0   foo 8   19.0
1   foo 3   8.0
2   foo 5   NaN
3   bar 90  1.0
4   boo 12  89.0


text:
Q: MPDF colsum is not displaying table columns sum in table footer I am using mpdf in laravel. But it is not displaying {colsum} in the table footer. using Laravel PDF: mPDF wrapper for Laravel 5.

controller code to pass data to view file.
 $data = [
        'data' => $vochur,
        'date' => date('m/d/Y H:i:s A'),
        'setting' => $setting,
        'user' => Auth::user()->first_name
    ];

    $pdf = PDFF::loadView('pdf.vouchers', $data);

view file code. using

                {colsum}
                {colsum}
                {colsum}
                {colsum}
                {colsum}

            @foreach ($data['bilties'] as $key => $item)

                    {{$item['id']}}
                    {{$item['customer']['name']}}
                    {{$item['product_type']}}
                    {{$item['quantity']}}
                    {{$item['fare']}}
                    {{$item['labour']}}
                    {{$item['adv']}}
                    {{$item['total']}}

            @endforeach


text:
Q: Motion blur effect on scroll I'm trying to apply a motion blur effect to a HTML div when scrolling. In order to do this, I'll need to make clone of the each div every 1/5 of a second, and keep its position fixed on the page when scrolling. I'll also need to decrease the opacity of each div clone every 1/5 second, and make sure that there are only 5 clones of the div on the page at a time (so that I won's have hundreds of clones of the div on the page after a few seconds). Would it be possible to create a motion blur effect in JavaScript using this method?

Create the illusion of a motion blur by creating clones of this div every 1/5 of a second, reducing the opacity of each clone every 1/5 of a second, and remove each clone as soon as it has completely faded away.

A: This implementation uses an SVG Gaussian blur filter. The strength of the blur is based on your scrolling velocity.

var blurFilter = document.getElementById('blur-kernel');
var html = $('html');
var prevPos = $(window).scrollTop();
var prevTime = Date.now();
var speed = 0;
var cheat = 0;

function blur() {
  cheat = 1 - cheat; // alternates between 0 and 1; used to force browser repaint by setting CSS

  let newPos = $(window).scrollTop();
  let newTime = Date.now()

  // distance over time times milliseconds per frame
  velocity = (newPos - prevPos) / Math.max(1, newTime - prevTime) * 1000 / 60;

  prevPos = newPos;
  prevTime = newTime;

  const STRENGTH = 1;
  blurSize = Math.max(0, Math.abs(velocity) / 2 * STRENGTH - 0.5);

  blurFilter.setStdDeviation(0, Math.floor(blurSize));
  blurFilter.setAttribute('stdDeviation', '0,' + blurSize);

  // forces browser repaint
  html.css('width', cheat + 'px');

  requestAnimationFrame(blur);
}

requestAnimationFrame(blur);
html {
  filter: url(#blur);
  -webkit-filter: url(#blur);
  will-change: filter, -webkit-filter;
  transform: translateZ(0);
  font: 16px sans-serif;
  line-height: 1.5;
}
body, img {
  /* setting the width of the body makes the
  html element's force-repaint "cheat" have no visible effect */
  width: calc(100vw - 20px); /* minus scrollbar */
  margin: 0;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eget tincidunt ipsum. Nullam metus mauris, scelerisque vel accumsan at, dapibus non odio. Cras volutpat malesuada tempus. Pellentesque vehicula posuere dolor et aliquet. Proin laoreet nisl sapien, ut congue neque placerat at. In ac nulla nec erat pretium egestas id ut orci. Vestibulum nec ultrices diam, sed efficitur ligula. Maecenas elementum molestie diam, vel mattis velit. Sed eu dignissim nibh, quis sollicitudin dolor. Praesent interdum pharetra aliquam. Maecenas mi est, semper nec dui euismod, semper interdum sem. Vestibulum sed porttitor purus. Ut convallis non urna non blandit. Quisque pharetra dolor ac ex dictum ultrices. Vestibulum cursus hendrerit elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Praesent mi nisl, dictum nec velit tincidunt, vestibulum congue purus. Nam venenatis elit lectus, quis fringilla felis dictum sed. Etiam ac lacus a neque lobortis rhoncus at vitae felis. In dapibus massa massa. Integer semper egestas interdum. Praesent augue magna, ultrices at consectetur eget, semper sit amet sapien. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque sollicitudin libero tortor, at gravida justo suscipit et. Maecenas euismod tellus eget lectus sollicitudin, nec consequat mauris porta. Aliquam vitae dolor ut ante commodo volutpat non sed leo. Donec malesuada justo tempus enim aliquet cursus. Pellentesque magna lectus, rhoncus ac porttitor at, congue vitae eros.

Proin ultricies dignissim arcu. Maecenas felis nunc, convallis non turpis at, laoreet dictum velit. Proin euismod libero ut orci commodo, in consequat orci fringilla. Donec ac congue mauris, lacinia mollis risus. Maecenas lorem diam, pulvinar quis est non, ornare cursus libero. Quisque ut magna sed arcu hendrerit facilisis eget vitae risus. In gravida nunc nec arcu tincidunt finibus. Nam sem ligula, vulputate in lorem ut, lobortis feugiat purus. Etiam placerat arcu efficitur risus pharetra eleifend. Nunc consectetur urna quis sapien placerat molestie. Vestibulum commodo elit nec facilisis varius. Ut ut posuere nisl, vitae pharetra enim. Aliquam molestie viverra venenatis.

Quisque tempus, sem et malesuada ornare, orci leo pulvinar nisi, laoreet vestibulum augue sem vitae nisl. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi quis commodo lorem. Sed ac scelerisque mauris, in lobortis ligula. Curabitur vestibulum blandit auctor. Aenean viverra turpis in dui tincidunt, vitae auctor quam faucibus. Sed id risus cursus, vehicula lorem at, tincidunt mi. Aenean maximus porttitor magna cursus interdum. Etiam sit amet mattis quam. Fusce sodales sodales porta. In hendrerit, velit eget tempus pretium, sapien tortor rutrum enim, eget aliquet libero velit et libero. Aliquam a consequat sem. Integer feugiat ut quam eu finibus. Sed rhoncus eleifend viverra. Mauris at viverra nulla, sit amet ultrices diam.

In sagittis nisi quis mi tristique mollis. Sed vulputate orci quis leo commodo, eu auctor orci tincidunt. Nullam eget posuere felis, in ultricies nibh. Nunc congue lorem sed elit fringilla lacinia. Vivamus ac ante tempor, ultricies ante nec, volutpat eros. Aenean laoreet justo imperdiet metus placerat accumsan. Quisque odio nibh, venenatis sit amet dignissim ut, tempor ultrices libero.

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="filters">
  <defs>
    <filter id="blur">
      <feGaussianBlur id="blur-kernel" in="SourceGraphic" edgeMode='duplicate' stdDeviation="0,0" />
    </filter>
  </defs>
</svg>

I'm testing it on a MacBook Pro, and Chrome is the only browser where this motion blur effect works smoothly. It's extremely laggy in Safari and Firefox, I think due to different rendering techniques.

A: I found this post on Stackoverflow:
How is this blur effect done in javascript?
$('img').on('mouseenter', function () {

        var $theClone = $(this).clone().css({ opacity : 0.5, position : 'absolute', top : 0 });

        $(this).parent().append($theClone);

        $theClone.animate({ left : 10 }, 500).on('mouseleave', function () {
            $(this).stop().fadeOut(250, function () {
                $(this).remove();
            });
        });
    });

Or maybe this function :
  function addParallaxScrolling() {
        if (!$("bgImageTop")) {
            return
        }
        if (window.orientation == undefined && !Browser.firefox) {
            var body = document.getElement("body"),
                headerimage = $("bgImageTop"),
                headergrad = $("bgGradientTop");
            window.addEvent("scroll", function windowScrollEvent() {
                body.setStyle("background-position", "0px " + (this.getScroll().y / 4) + "px");
                headerimage.setStyle("top", this.getScroll().y / 4 + "px");
                headergrad.setStyle("top", headerimage.getStyle("top").toInt() + headerimage.getStyle("height").toInt() + "px")
            })
        }
    }

Hope i can help you.


text:
Q: Cannot read property state of undefined privateroute I found online how to create a costumed private route,
However, I'm getting an error
"Cannot read property 'state' of undefined" on line 12
I'm kinda new to react and I'm having trouble understanding props vs this.
Router.js
import React, { Component } from 'react';
import { Route, BrowserRouter, Redirect } from "react-router-dom";

import Login from './Authentication/Login';
import  Register  from './Authentication/Register';
import PageRouter from './page/PageRouter';
import Profile from './page/Profile';
import Rankings from './page/Rankings';
import Shop from './page/Shop';

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={
        (props) => (
      this.state
        ? <Component {...props} />
        : <Redirect to='/login' />
    )} />
  )

class Router extends Component{
    constructor(props){
        super(props);
        this.state = {
            login: false,
        }
    }

    render(){
        return(
            <div>
                <BrowserRouter>
                <Route exact path="/" component={ Register }></Route>
                    <Route path='/register' component={ Register }/>
                    <Route path="/login" component={ Login } />
                    <PrivateRoute path='/home' component={ PageRouter } />
                    <Route path ='/profile' component={ Profile } />
                    <Route path = '/rankings' component={ Rankings } />
                    <Route path = '/shop' component={ Shop }/>
                </BrowserRouter>
            </div>
        );
    }
}

export default Router;

Any information would help. Thanks!

A: This isn't a React issue. The key you're missing here is understanding JavaScript context. Right now PrivateRoute's lexical scope is the global or window object (or if in strict mode undefined). You currently have no state on that object. If you want a way to utilize your Router class' state, then I would suggest you pass in some prop to PrivateRoute via Router.
So if you wanted to access the login property on state try something like:
<PrivateRoute path='/home' component={ PageRouter } isLoggedIn={this.state.login} />
then your PrivateRoute would have access to a prop called isLoggedIn which you could use in your ternary.

A: "Cannot read property 'state' of undefined" on line 12 I'm kinda new to react and I'm having trouble understanding props vs this.

*

*Props is (in simple terms) a collection of attibutes that your component needs, eg: <MyComponent name="xxx" address="yyy"/> where name and address can be accessed by this.props.name or this.props.address respectively.

*Keyword this is a different concept altogether. this referring to the component itself. It means, you can access its (component) state, props, or methods that is defined inside the component class

I don't know if this is related to your issue or not, but I noticed that your sample code is coming from a tutorial (https://tylermcginnis.com/react-router-protected-routes-authentication/).
Below is my implementation of PrivateRoute:
const PrivateRoute = ({ component: Component, ...rest }: {component: any}) => (
    <Route {...rest} render={(props) => (
        fakeAuth.isAuthenticated === true
            ? <Component {...props} />
            : <Redirect to={{
                pathname: '/login',
                state: { from: props.location }
            }} />
    )} />
)

PrivateRoute.propTypes = {
    component: PropTypes.any,
    location: PropTypes.string,
    path: PropTypes.string
};

The state properties is not this.state. It is a parameter from Redirectof react-router-dom


text:
Q: An array of views (views that have an UIImage and 3 buttons): Is a custom view/drawRect needed? Do I need to create a custom view (i.e., a subclass of a UIView where I override drawRect) in order to eventually make an array containing those custom views? Because I ultimately want to make a scrollView that implements page control and displays a number of views (i.e., the array of custom views) on separate pages. The views are just an UIImage above three buttons. And the image for one view is different for each other view (e.g., electronic flash cards).

A: It doesn't look like you need a custom view to override drawRect: since you are looking to build a collection view using a single image view and three buttons. However it will not hurt to create one so that accessing the sub views can be done via named properties. For example, customObject.imageView and customObject.firstButton. As a unit it makes sense to create one as it will be messy to keep track of all the image views and buttons you would end up adding to the scroll view otherwise.


text:
Q: No LoginModules configured for DefaultPrincipalMapping WAS Libert y profile 8.5.5.9 I used the info in this link https://www.ibm.com/support/knowledgecenter/SSEQTP_8.5.5/com.ibm.websphere.wlp.doc/ae/twlp_dev_prog_login_auth_data.html As per my info which I got from this discussion thread. https://developer.ibm.com/answers/questions/261209/websphere-liberty-profile-and-j2c-authdata-retriev-1.html
The DefaultPrincipalMapping programmatic login is avaiable and should work. I configured everything updated to Liberty profile v 8.5.5.9 , yet my code throws exception at [err] javax.security.auth.login.LoginException: No LoginModules configured for DefaultPrincipalMapping [err] at javax.security.auth.login.LoginContext.init(LoginContext.java:264) [err] at javax.security.auth.login.LoginContext.(LoginContext.java:417) Here is my code snippet..
     Context context = new InitialContext();
     String user = (String) context.lookup("cell/persistent/ADBindUser");
     String password = (String) context.lookup("cell/persistent/ADBindPwd");

     Map<String, String> map = new HashMap<String, String>();
     map.put(Constants.MAPPING_ALIAS, "WPSBIND");

// CallbackHandler callbackHandler = // WSMappingCallbackHandlerFactory.getInstance().getCallbackHandler(map, null);
     CallbackHandler callbackHandler =new WSMappingCallbackHandler(map, null);

     LoginContext loginContext =
         new LoginContext("DefaultPrincipalMapping", callbackHandler);
     try{
         loginContext.login();
     }catch(LoginException le) {

     }

Can any one please tell me what I am missing here.

A: Instead of "DefaultPrincipalMapping" the login configuration "system.DEFAULT" did the job for me.
The final hint was hidden in the documentation:

system.DEFAULT
Used for login when no JAAS configuration is specified.
...
The system.WEB_INBOUND and system.DEFAULT configurations have these
  default login modules in this order: hashtable, userNameAndPassword,
  certificate, and token. The WSLogin configuration has the proxy login module
  as the default login module, and the proxy delegates all the
  operations to the real login module in system.DEFAULT.

WSLogin fails with an Unrecognized Callback in case the application uses e.g. org.jboss.security.auth.callback.UsernamePasswordHandler as the callback. If the application cannot be modified, system.DEFAULT provides an alternative.


text:
Q: Origin of "skin" as euphemism for money What is the origin or history of using "skin" to refer to "money?" For example, a golf competition called a "skins game" or, referring to an investor who, "has some skin in the game."

A: Ultimately it appears to go back to the US Federal Reserve's design of dollar bills.
OED lists your references separately.

P18. colloq. (orig. N. Amer. Business). to have (one's) skin in the game and variants:
  to have a stake in the success of something, esp. to have a financial or personal investment in a business; to be closely involved in something.
It is not clear whether the metaphor underlying this phrase is to do with putting oneself at risk (cf. the metonymic uses of skin at Phrases 1c), or with risking one's money (cf. sense 6); both have been suggested.
P1 c. In phrases concerning a person's life and safety, esp. to save one's (own) skin : to protect oneself from injury, punishment, or some other unwanted fate; spec. to save one's own life.
6. fig. U.S. slang. A dollar; = frogskin n.

An investor with "skin in the game" can either risk his money (skin = dollar) or maybe his entire livelihood. Either seems reasonable, although I think I favour the first because the word skin the phrase can be replaced easily with money. It's not easy to go from P1 c to P18.
The golf game has a sense all of its own:

26. N. Amer. Golf. A sum of money offered as a wager or prize to the winner of a given hole, which in case of there being no outright winner may accrue to the following hole. Cf. skins game n. [a game with such sums of money].

Again, skin here refers to money.
Skin as money appears to derive from the colour of dollar bills:

frogskin n.  [with reference to the green colour of the banknotes] slang  (a) U.S. a one-dollar bill; = toadskin n.
† toadskin n. N. Amer. slang. (obs.)  (a) a five-cent stamp;  (b) a banknote.

A: The Hudson's Bay Company, that was incorporated in 1670. They're company motto is Per Pelle Cutem which translates as For Pelts, Skins.
So, I think it's safe to say that it goes back before the founding of the USA.
A lot of North America was visited first by Europeans looking to trade for furs with the Indians, or to trap them themselves. Pelts were as good as currency for the first 200 years that the Europeans where on the continent.
The expression might come from a native language or perhaps (and I find this more likely) was part of the trade creoles that were created to communicate between cultures.


text:
Q: Include template in template Mustache.php I have 3 template files:
main.tpl
main_header.tpl
main_footer.tpl

I need to include the last 2 templates inside the first one using Mustache.php
I can't find documentation about it.
How can I do?

A: The included templates are called "partials" in Mustache. The tag to include them looks like this:
{{> main_header }}
{{> main_footer }}

You will need to set up a template loader so that Mustache can automatically load them.
Since your file extension is .tpl, you should also let your template loader know.
The resulting code probably looks something like this:
<?php

$m = new Mustache_Engine(array(
    'loader' => new Mustache_Loader_FilesystemLoader(
        __DIR__.'/path/to/views',
        array('extension' => '.tpl')
    ),
));

echo $m->render('main', $data);


text:
Q: How to make responsive design like Instagram in React Native? When opening Instagram on the iPad, it displays like this.

Instagram
It looks like Instagram doesn't use react-native-responsive-screen because the size of each screen is the same as in iPhone.
I would appreciate it if you could give me any advice.

A: Any iPhone only app has an iPhone size on iPad.
iOS apps can be:

*

*iPhone only,

*iPad only,

*universal (for both iPhones & iPads).

It can be configured in Xcode.
These settings are not related to React Native. It's an iOS specific thing.


text:
Q: Spring boot MongoDB replica set exception I'm using Spring Boot 2.0.3 and MongoDB. I have 2 databases that I need to connect to in the application. Each of the databases has their own replica set. I'm not using the default spring.data.mongodb.uri property in the application.properties to connect to these databases. I have created 2 separate datasources using MongoTemplate configuration beans with the following connection URIs:
mongodb.db1.uri=mongodb://user1:password@18.220.X.X:27017,18.222.X.X:27017,18.223.X.X:27017/db1?authSource=db1
mongodb.db2.uri=mongodb://user2:password@18.188.X.X/db2?authSource=db2

I'm trying to configure the replica set in the first URI above by providing the public ips of secondary instances as mentioned in Spring documentation. But whenever I try to connect using that it times out and throws the below exception.
It works perfectly fine when you only provide the primary instance in the connection URI.
2018-09-07T11:26:56,654 INFO  [main] c.m.d.l.SLF4JLogger: Cluster created with settings {hosts=[18.220.X.X:27017, 18.222.X.X:27017, 18.223.X.X:27017], mode=MULTIPLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-09-07T11:26:56,655 INFO  [main] c.m.d.l.SLF4JLogger: Adding discovered server 18.220.X.X:27017 to client view of cluster
2018-09-07T11:26:56,680 INFO  [main] c.m.d.l.SLF4JLogger: Adding discovered server 18.222.X.X:27017 to client view of cluster
2018-09-07T11:26:56,682 INFO  [main] c.m.d.l.SLF4JLogger: Adding discovered server 18.223.X.X:27017 to client view of cluster
2018-09-07T11:26:57,090 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.222.X.X:27017] c.m.d.l.SLF4JLogger: Opened connection [connectionId{localValue:2, serverValue:4383}] to 18.222.X.X:27017
2018-09-07T11:26:57,092 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.220.X.X:27017] c.m.d.l.SLF4JLogger: Opened connection [connectionId{localValue:1, serverValue:8820}] to 18.220.X.X:27017
2018-09-07T11:26:57,092 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.223.X.X:27017] c.m.d.l.SLF4JLogger: Opened connection [connectionId{localValue:3, serverValue:4366}] to 18.223.X.X:27017
2018-09-07T11:26:57,126 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.222.X.X:27017] c.m.d.l.SLF4JLogger: Monitor thread successfully connected to server with description ServerDescription{address=18.222.X.X:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 2]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=33697993, setName='s0', canonicalAddress=172.31.13.153:27017, hosts=[172.31.1.69:27017, 172.31.0.163:27017, 172.31.13.153:27017], passives=[], arbiters=[], primary='172.31.0.163:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Fri Sep 07 11:26:55 EDT 2018, lastUpdateTimeNanos=1247772166805941}
2018-09-07T11:26:57,127 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.220.X.X:27017] c.m.d.l.SLF4JLogger: Monitor thread successfully connected to server with description ServerDescription{address=18.220.X.X:27017, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 2]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=34897475, setName='s0', canonicalAddress=172.31.0.163:27017, hosts=[172.31.1.69:27017, 172.31.0.163:27017, 172.31.13.153:27017], passives=[], arbiters=[], primary='172.31.0.163:27017', tagSet=TagSet{[]}, electionId=7fffffff0000000000000004, setVersion=1, lastWriteDate=Fri Sep 07 11:26:55 EDT 2018, lastUpdateTimeNanos=1247772168059625}
2018-09-07T11:26:57,128 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.222.X.X:27017] c.m.d.l.SLF4JLogger: Discovered cluster type of REPLICA_SET
2018-09-07T11:26:57,128 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.223.X.X:27017] c.m.d.l.SLF4JLogger: Monitor thread successfully connected to server with description ServerDescription{address=18.223.X.X:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 2]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=35436355, setName='s0', canonicalAddress=172.31.1.69:27017, hosts=[172.31.1.69:27017, 172.31.0.163:27017, 172.31.13.153:27017], passives=[], arbiters=[], primary='172.31.0.163:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Fri Sep 07 11:26:55 EDT 2018, lastUpdateTimeNanos=1247772169059561}
2018-09-07T11:26:57,129 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.222.X.X:27017] c.m.d.l.SLF4JLogger: Adding discovered server 172.31.1.69:27017 to client view of cluster
2018-09-07T11:26:57,130 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.222.X.X:27017] c.m.d.l.SLF4JLogger: Adding discovered server 172.31.0.163:27017 to client view of cluster
2018-09-07T11:26:57,130 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.222.X.X:27017] c.m.d.l.SLF4JLogger: Adding discovered server 172.31.13.153:27017 to client view of cluster
2018-09-07T11:26:57,132 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.222.X.X:27017] c.m.d.l.SLF4JLogger: Canonical address 172.31.13.153:27017 does not match server address.  Removing 18.222.X.X:27017 from client view of cluster
2018-09-07T11:26:57,133 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.223.X.X:27017] c.m.d.l.SLF4JLogger: Canonical address 172.31.1.69:27017 does not match server address.  Removing 18.223.X.X:27017 from client view of cluster
2018-09-07T11:26:57,134 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.220.X.X:27017] c.m.d.l.SLF4JLogger: Server 18.220.X.X:27017 is no longer a member of the replica set.  Removing from client view of cluster.
2018-09-07T11:26:57,134 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-18.220.X.X:27017] c.m.d.l.SLF4JLogger: Canonical address 172.31.0.163:27017 does not match server address.  Removing 18.220.X.X:27017 from client view of cluster
2018-09-07T11:26:57,171 DEBUG [main] o.r.e.q.s.MDSFileUploadServiceImpl: mds upload temp dir: /var/folders/k6/t2lhgt2j1b75zmwhhfcjyj7r0000gq/T/mds_uploads
2018-09-07T11:26:57,180 INFO  [main] c.m.d.l.SLF4JLogger: Cluster created with settings {hosts=[18.188.48.47:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-09-07T11:26:57,332 INFO  [main] c.m.d.l.SLF4JLogger: No server chosen by com.mongodb.Mongo$4@fe42a09 from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{address=172.31.1.69:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=172.31.13.153:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=172.31.0.163:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
2018-09-07T11:26:57,406 INFO  [cluster-ClusterId{value='5b9298c11e27010f371833e0', description='null'}-18.188.48.47:27017] c.m.d.l.SLF4JLogger: Opened connection [connectionId{localValue:7, serverValue:65931}] to 18.188.48.47:27017
2018-09-07T11:26:57,437 INFO  [cluster-ClusterId{value='5b9298c11e27010f371833e0', description='null'}-18.188.48.47:27017] c.m.d.l.SLF4JLogger: Monitor thread successfully connected to server with description ServerDescription{address=18.188.48.47:27017, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 1]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=29340617, setName='s0', canonicalAddress=172.31.22.223:27017, hosts=[172.31.12.43:27017, 172.31.43.141:27017, 172.31.22.223:27017], passives=[], arbiters=[], primary='172.31.22.223:27017', tagSet=TagSet{[]}, electionId=7fffffff0000000000000006, setVersion=1, lastWriteDate=Fri Sep 07 11:26:49 EDT 2018, lastUpdateTimeNanos=1247772477666312}
2018-09-07T11:27:17,135 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-172.31.13.153:27017] c.m.d.l.SLF4JLogger: Exception in monitor thread while connecting to server 172.31.13.153:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.SocketStream.open(SocketStream.java:62)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126)
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketTimeoutException: connect timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:59)
    at com.mongodb.connection.SocketStream.open(SocketStream.java:57)
    ... 3 more
2018-09-07T11:27:17,135 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-172.31.0.163:27017] c.m.d.l.SLF4JLogger: Exception in monitor thread while connecting to server 172.31.0.163:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.SocketStream.open(SocketStream.java:62)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126)
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketTimeoutException: connect timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:59)
    at com.mongodb.connection.SocketStream.open(SocketStream.java:57)
    ... 3 more
2018-09-07T11:27:17,135 INFO  [cluster-ClusterId{value='5b9298c01e27010f371833df', description='null'}-172.31.1.69:27017] c.m.d.l.SLF4JLogger: Exception in monitor thread while connecting to server 172.31.1.69:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
    at com.mongodb.connection.SocketStream.open(SocketStream.java:62)
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:126)
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:114)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketTimeoutException: connect timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:59)
    at com.mongodb.connection.SocketStream.open(SocketStream.java:57)
    ... 3 more

Caused by: org.springframework.dao.DataAccessResourceFailureException: Timed out after 30000 ms while waiting for a server that matches com.mongodb.Mongo$4@fe42a09. Client view of cluster state is {type=REPLICA_SET, servers=[{address=172.31.1.69:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}, {address=172.31.13.153:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}, {address=172.31.0.163:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}]; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches com.mongodb.Mongo$4@fe42a09. Client view of cluster state is {type=REPLICA_SET, servers=[{address=172.31.1.69:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}, {address=172.31.13.153:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}, {address=172.31.0.163:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}]
    at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:87)
    at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2592)
    at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:2459)
    at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:2244)
    at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:2227)
    at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:770)
    at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.findAll(SimpleMongoRepository.java:365)
    at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.findAll(SimpleMongoRepository.java:197)
    at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.findAll(SimpleMongoRepository.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:377)
    at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:629)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:593)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:578)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy104.findAll(Unknown Source)
    at org.x.x.x.configuration.QMRulesConfiguration.qualityMeasures(QMRulesConfiguration.java:37)
    at org.x.x.x.configuration.QMRulesConfiguration$$EnhancerBySpringCGLIB$$4410cf1a.CGLIB$qualityMeasures$2(<generated>)
    at org.x.x.x.configuration.QMRulesConfiguration$$EnhancerBySpringCGLIB$$4410cf1a$$FastClassBySpringCGLIB$$f0f9b03.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
    at org.x.x.x.configuration.QMRulesConfiguration$$EnhancerBySpringCGLIB$$4410cf1a.qualityMeasures(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 82 more
Caused by: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches com.mongodb.Mongo$4@fe42a09. Client view of cluster state is {type=REPLICA_SET, servers=[{address=172.31.1.69:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}, {address=172.31.13.153:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}, {address=172.31.0.163:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}]
    at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:389)
    at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:108)
    at com.mongodb.Mongo.getConnectedClusterDescription(Mongo.java:887)
    at com.mongodb.Mongo.createClientSession(Mongo.java:877)
    at com.mongodb.Mongo$3.getClientSession(Mongo.java:866)
    at com.mongodb.Mongo$3.execute(Mongo.java:823)
    at com.mongodb.MongoIterableImpl.execute(MongoIterableImpl.java:130)
    at com.mongodb.MongoIterableImpl.iterator(MongoIterableImpl.java:77)
    at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:2442)
    ... 118 more

What could be the problem?

A: Do you need pass in the replica set as part of the URI? We have to do that like this at the end of the uri
?replicaSet=setInQuestion


text:
Q: Bind collections from TabItems to a single DataGrid when selected I have a Window with a TabControl containing two TabItems, each containing a UserControl. These's viewmodels inherit from a BaseViewModel containing an ObservableCollection property.
Under the TabControl, I have a DataGrid; the Window's viewmodel contains the same ObservableCollection property as the BaseViewModel, and the DataGridView binds to it.
How can I bind the selected viewmodel's collection to the DataGrid, directly or not (eg. MyWindow.MyCollection = selectedVM.MyCollection)?
The idea is to update the DataGrid to always show the content of the selected tab's collection.


text:
Q: picture element don't respect viewport meta tag picture element don't respect viewport meta tag.
Any one know how can I solve this?
I have this html:
<!DOCTYPE html>

    <title>dpi</title>

    <meta name='viewport' content='initial-scale=1.0, user-scalable=no'>

    <picture>
        <source media='(min-width: 361px)' srcset='dpi_sm.png'>

    </picture>

when it runs in a standard desktop with a 1366px resolution, the picture element loads dpi_sm.png as expected.
however, when it runs in a android device, it keeps loading the dpi_sm.png image.
I tested, and it only loads the dpi.png image when I set the media to "(min-width: 981px)". It should consider the meta tag viewport, shouldn't it? But the zoom is being the default 980px, even when the viewport meta tag is there
The div and css media query works fine in both cases. Just the picture element is being a problem.


text:
Q: Listing values regardless of prompt selection I currently have a cognos report with 3 pages:

*

*Monthly Summary

*Monthly Detailed

*Full Year Trend

The month is determined by a value prompt. My question is: How can I make it so the 3rd report page ignores the Month paramvalue and shows all 12 months regardless of the value prompt? So if June, for example, was picked the first two reports would show only June but the full year trend would show January to December.
Currently the prompt works fine for the two other reports but I can't figure out how to make the third page show the same data everytime.
Thanks,
lostintern

A: It will get tricky towards year-end/beginning, but anyhow ... Extract the value of Year from your prompt and use it as a filter for your third page query.


text:
Q: Inline creation in backpack laravel I try to put an inline create on the field Application but it doesn't work
Is it due to the traisStore, here is the declaration in AppliCrudController
use \Backpack\CRUD\app\Http\Controllers\Operations\CreateOperation { store as traitStore; }
use \Backpack\CRUD\app\Http\Controllers\Operations\InlineCreateOperation { store as traitStore; }

Error message:

A: You can look at the error your Chrome Developer Tools. That will provide more info.
Open Chrome Developer Tools, choose the Network tab, then submit the form again, so Chrome gets to track your AJAX request. That request will then show up in Chrome DevTools, click it to see so you can see what error it was, under Preview or Response.


text:
Q: Storing session in database with CakePHP 2.0 I'm using CakePHP 2.0, and tries to configure it to store sessions in a database.
However, I find the official documentation very unclear. I understand I need to set the following in core.php:
<?php
Configure::write('Session', array(
    'defaults' => 'database',
    'handler' => array(
        'model' => 'CustomSession'
    )
));

I've created the table with cake's schema:
CREATE TABLE cake_sessions (
  id varchar(255) NOT NULL default '',
  data text,
  expires int(11) default NULL,
  PRIMARY KEY  (id)
);

It still doesn't work. Do I need to create the session model by myself? If so, how?

A: Since you have created the model in the core file as cake_sessions, you will need to name your table as cake_sessions. cake_session is the default model
<?php
Configure::write('Session', array(
    'defaults' => 'database',
    'handler' => array(
        'model' => 'cake_sessions'
    )
));


text:
Q: Global actions and clickjack protection Clickjack protection protects your SF org by blocking pages served from a different domain.
Now, I see an issue with you mix it with VisualForce custom global actions.
Repro steps

*

*Create the world's simplest VF page:

<apex:page>

Hello World

</apex:page>

*

*Create a new Global Action, and make it of type "Custom Visualforce", and point it to your VF page.

*Add it to the page layout of, say, Account.

*Turn clickjack protection on

*Navigate to any account

*Try to display the quick action

*This should generate an error message

I think this is caused because the Global Action is served from within an iframe. The main page is in the salesforce.com domain, while the iframe will point to visual.force.com domain. Clickjack will dutifully protect you from the dangers of the foreign VF page.
However, this is terribly broken. It's a VF page in my own org! It so happens that Salesforce likes to serve it from a different domain.
I've tried hiding the headers with showHeader="false", but now we have clickjack protection with VF pages with no header, so it doesn't cover me in all circumstances (this is in the context of a managed package, so our customers have different CJ settings).
Telling our customers to disable clickjacking is not always an option. Ironically, SF recommends not serving pages from within iframes, but this is not under our control. The SF framework for Global Actions uses iframes.
Has anyone experienced similar issues? What have you done to fix it?


text:
Q: How can I get a Windows client not in the domain to get dns from the DC? I have Server 2012 as Domain controller and DNS server.
Now if I have a machine joined to the domain, they get all servers names defined in dns zone.
I have a Windows 7 client which is not joined to the domain, but I want it to get the IP of the DNS servers.
I tried manually putting the IP 192.168.0.100 in the DNS of the network adapter, but it does not get the IP of the DNS servers.

A: When not a part of the domain, you need to use the FQDN of the host you are trying to resolve. Example:
A server named app01 on domain.lab with ip 192.168.0.69 being pinged from a machine on the same network, but not in the domain.
ping app01
 - host cannot be resolved
ping app01.domain.lab
- Reply from 192.168.0.69: time=blah blah blah

A: If you want a non-domain joined computer to resolve internal names, you should be putting the domain controller (which has DNS on it) as the DNS server and setting the DNS prefix to whatever your domain name is. Even computers not on the domain will still be able to work with the DNS server.
What won't work is other computers resolving the name of the non-joined machine since it won't be in DNS, but that wasn't your requirement.


text:
Q: Natural Language Processing - Returning results as JSON objects I am working on completing a Python programing challenge to do with Natural Language Processing and scraping information from BBC News articles. My previous submission of code (shown below) was marked and failed due to not passing the test criteria (shown below). However I am unable to think of any way to make my code pass the test.
From what I can tell the code is failing for a few reasons:

*

*Escape characters not matching the test code

*Use of "      " instead of '   ' in some variables

This is my code:
# Import modules used to complete challenge
import json
import requests
import spacy
from bs4 import BeautifulSoup

# Load the Spacy English model
nlp = spacy.load("en_core_web_sm")
# Url's stored in a list to test that the scraper function is iterable
url = ["https://www.bbc.co.uk/news/uk-52255054"]

# Function used to scrape a given BBC news article and return URL, Title, Date and Content as a json object
def bbc_scraper(url):
    # Error catching on invalid URL's and connectivity issues
    try:
        r = requests.session()
        page = r.get(url)
    except requests.exceptions.RequestException as e:
        print("Double check the URL and try again.")
        raise SystemExit(e)
    # Use beautifulSoup to parse the html content and store it as soup
    soup = BeautifulSoup(page.content, "html.parser")
    # Using beautifulSoup to find specific HTML tags within HTML classes
    title = soup.find("h1", class_="story-body__h1").text
    date = soup.find("div", class_="date date--v2").text
    main_content = soup.findAll("div", class_="story-body__inner")
    # Finding all "p" HTML tags within the main content
    news_content_paragraphs = main_content[0].find_all("p")
    list_paragraphs = []
    # Loop through all paragraphs and joins them to the final_article string
    for paragraphs in news_content_paragraphs:
        list_paragraphs.append(paragraphs.text)
        final_article = ''.join(list_paragraphs)
        # Build the json object with content scraped from the website
    results_json = json.dumps({'URL':url, 'Title':title,'Date_published':date, 'Content':final_article})
    return results_json

And then this is the test criteria used to test the JSON that my code returns:
def test_bbc_scrape():
    results = {'URL': 'https://www.bbc.co.uk/news/uk-52255054',
                'Title': 'Coronavirus: \'We need Easter as much as ever,\' says the Queen',
                'Date_published': '11 April 2020',
                'Content': '"Coronavirus will not overcome us," the Queen has said, in an Easter message to the nation. While celebrations would be different for many this year, she said: "We need Easter as much as ever." Referencing the tradition of lighting candles to mark the occasion, she said: "As dark as death can be - particularly for those suffering with grief - light and life are greater." It comes as the number of coronavirus deaths in UK hospitals reached 9,875. Speaking from Windsor Castle, the Queen said many religions had festivals celebrating light overcoming darkness, which often featured the lighting of candles. She said: "They seem to speak to every culture, and appeal to people of all faiths, and of none. "They are lit on birthday cakes and to mark family anniversaries, when we gather happily around a source of light. It unites us." The monarch, who is head of the Church of England, said: "As darkness falls on the Saturday before Easter Day, many Christians would normally light candles together.  "In church, one light would pass to another, spreading slowly and then more rapidly as more candles are lit. It\'s a way of showing how the good news of Christ\'s resurrection has been passed on from the first Easter by every generation until now." As far as we know, this is the first time the Queen has released an Easter message. And coming as it does less than a week since the televised broadcast to the nation, it underlines the gravity of the situation as it is regarded by the monarch. It serves two purposes really; it is underlining the government\'s public safety message, acknowledging Easter will be difficult for us but by keeping apart we keep others safe, and the broader Christian message of hope and reassurance.  We know how important her Christian faith is, and coming on the eve of Easter Sunday, it is clearly a significant time for people of all faiths, but particularly Christian faith. She said the discovery of the risen Christ on the first Easter Day gave his followers new hope and fresh purpose, adding that we could all take heart from this.  Wishing everyone of all faiths and denominations a blessed Easter, she said: "May the living flame of the Easter hope be a steady guide as we face the future." The Queen, 93, recorded the audio message in the White Drawing Room at Windsor Castle, with one sound engineer in the next room.  The Palace described it as "Her Majesty\'s contribution to those who are celebrating Easter privately".  It follows a speech on Sunday, in which the monarch delivered a rallying message to the nation. In it, she said the UK "will succeed" in its fight against the coronavirus pandemic, thanked people for following government rules about staying at home and praised those "coming together to help others". She also thanked key workers, saying "every hour" of work "brings us closer to a return to more normal times".'}
    scraper_result = bbc_scraper('https://www.bbc.co.uk/news/uk-52255054')
    assert json.loads(scraper_result) == results

My code returns the following:
{"URL": "https://www.bbc.co.uk/news/uk-52255054", "Title": "Coronavirus: 'We need Easter as much as ever,' says the Queen", "Date_published": "11 April 2020", "Content": "\"Coronavirus will not overcome us,\" the Queen has said, in an Easter message to the nation.While celebrations would be different for many this year, she said: \"We need Easter as much as ever.\"Referencing the tradition of lighting candles to mark the occasion, she said: \"As dark as death can be - particularly for those suffering with grief - light and life are greater.\"It comes as the number of coronavirus deaths in UK hospitals reached 9,875.Speaking from Windsor Castle, the Queen said many religions had festivals celebrating light overcoming darkness, which often featured the lighting of candles.She said: \"They seem to speak to every culture, and appeal to people of all faiths, and of none.\"They are lit on birthday cakes and to mark family anniversaries, when we gather happily around a source of light. It unites us.\"The monarch, who is head of the Church of England, said: \"As darkness falls on the Saturday before Easter Day, many Christians would normally light candles together. \"In church, one light would pass to another, spreading slowly and then more rapidly as more candles are lit. It's a way of showing how the good news of Christ's resurrection has been passed on from the first Easter by every generation until now.\"As far as we know, this is the first time the Queen has released an Easter message.And coming as it does less than a week since the televised broadcast to the nation, it underlines the gravity of the situation as it is regarded by the monarch.It serves two purposes really; it is underlining the government's public safety message, acknowledging Easter will be difficult for us but by keeping apart we keep others safe, and the broader Christian message of hope and reassurance. We know how important her Christian faith is, and coming on the eve of Easter Sunday, it is clearly a significant time for people of all faiths, but particularly Christian faith.She said the discovery of the risen Christ on the first Easter Day gave his followers new hope and fresh purpose, adding that we could all take heart from this. Wishing everyone of all faiths and denominations a blessed Easter, she said: \"May the living flame of the Easter hope be a steady guide as we face the future.\"The Queen, 93, recorded the audio message in the White Drawing Room at Windsor Castle, with one sound engineer in the next room. The Palace described it as \"Her Majesty's contribution to those who are celebrating Easter privately\". It follows a speech on Sunday, in which the monarch delivered a rallying message to the nation.In it, she said the UK \"will succeed\" in its fight against the coronavirus pandemic, thanked people for following government rules about staying at home and praised those \"coming together to help others\".She also thanked key workers, saying \"every hour\" of work \"brings us closer to a return to more normal times\"."}

Obviously I know that it doesn't match the criteria and thats why it is failing but I'm strugging to get the JSON to be in the correct format to pass the test.
Any help or pointers in the right direction would be greatly appreciated. Thanks


text:
Q: Getting the least common denominator of two decimals I am currently working on a text based web game, where in I simulate the battle sequences automatically like MyBrute and Pockie Ninja
So this is the situation.
We have 2 Players with different attack speed
attack speed(determines the number of seconds needed for a player to start attacking)
(Easy Example) Lets assume Player 1 has 6s and Player 2 has 3s
This means Player 2 will attack twice before Player 1 does
(its because if two player tied on a attack turn, the one with the better attack speed goes first)
(but if they have the same attack speed, the player who have not attack lately will go)
Now my problem is in the loop.
I'd like to determine who's turn it is with the minimum number of loops
for our Easy Example we could just create an infinite loop with a counter that increments 3 values to determine whos turn it's going to be and just check if every iteration if we have a winner and exit the loop. (this is my algo you can suggest better one)
The big problem for me is when i have decimal values now for attack speed
Realistic Example (assume that i only use 1 digit for decimal)
Player1 attack speed = 5.7
Player2 attack speed = 6.6
at worst we could have is 0.1 as a an LCD and use as subtrahend per loop but i want to determine the the best subtrahend(LCD) value.
Hope it makes sense.
Thank you. I appreciate you sharing your great minds.
UPDATE
    //THIS IS NOT THE ACTUAL CODES BUT THIS IS THE LOGIC
decimal Player1Turn = Player1.attackspeed;
decimal Player2Turn = Player2.attackspeed;
decimal LCD = GetLCD(Player1.attackspeed,Player2.attackspeed)  ***//THIS IS WHAT I WANT TO DETERMINE***
while (Player1.HP >0 && Player2.HP >0)
{
    Player1Turn -= LCD;
    Player2Turn -= LCD;
    if (Player1Turn<=0)
    {
        //DO STUFF
        Player1Turn = Player1.attackspeed;
    }
    if (Player2Turn<=0)
    {
        //DO STUFF
        Player2Turn = Player2.attackspeed;
    }
}

WE CAN USE A FUNCTION LIKE
public decimal GetLCD(decimal num1, decimal num2)
   {
        //returns the lcd
   }

A: The following code processes the battle sequence without using the lowest common denominator. It will also run about 1 million times faster than all possible attempts with using the lowest common denominator for player attack speeds equal e.g. 1000 and 1000.001 respectively.
decimal time = 0;
while (player1.HP > 0 && player2.HP > 0) {
    decimal player1remainingtime = player1.attackspeed - (time % player1.attackspeed);
    decimal player2remainingtime = player2.attackspeed - (time % player2.attackspeed);
    time += Math.Min(player1remainingtime, player2remainingtime);
    if(player1remainingtime < player2remainingtime) {
        //it is player 1 turn; do stuff;
    } else if(player1remainingtime > player2remainingtime) {
        //it is player 2 turn; do stuff;
    } else {
        //both player turns now
        if(player1.attackspeed < player2.attackspeed) {
            //player 1 is faster, its player 1 turn; do stuff
            //now do stuff for player 2
        } else {
            //player 2 is faster, its player 2 turn; do stuff
            //now do stuff for player 1
        }
    }
}

A: If you are using an object oriented language then you can do this:
Players will be objects of type Player and there will be a Timer object.
The Timer will use the Observer design pattern.
Players will register themselves to the Timer with their response time.
When their time is due then they are notified that they can take action.


text:
Q: Default page for unimplemented REST endpoints? I'm creating a REST service in Java. I use javax package. I have the following question:
is it possible to create something like "default page" for the unimplemented endpoints? I.e., let us suppose I implement the following endpoints:
localhost:8080/rest/a
localhost:8080/rest/b
And know I want some default page to be loaded if a user enters e.g. localhost:8080/rest/c (maybe some redirect for 404 error?). I looked for something like this in Google but with no success. I have no idea what I could start from. Thank you for any help!
EDIT:
I would like to mention that I tried to add to my web.xml something like this:
<error-page>
  <error-code>404</error-code>
  <location>/WEB-INF/errorpages/404.xhtml</location>
</error-page>

but unfortunately I doesn't work for REST addresses (localhost:8080/rest/something). However, it does work for any other addresses.
EDIT2:
I put some code snippets:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("rest")
public class JaxRsApplication extends Application {

}

===========================================================
@Path("/myview")
public class MyView {

    @GET
    @Path("/")
    public Response root() throws NotImplementedException {
        throw new NotImplementedException();
    }

    @POST
    @Path("/test")
    public Response test() throws NotImplementedException {
        throw new NotImplementedException();
    }
}

EDIT3:
@cássio-mazzochi-molin sorry for a delay, I couldn't check this. But now I have checked this and I'm not sure if this is what I want.
I've implemented EntityNotFoundExceptionMapper:
@Provider
public class EntityNotFoundExceptionMapper implements ExceptionMapper<EntityNotFoundException> {

    @Override
    public Response toResponse(EntityNotFoundException exception) {
        return Response.status(404).entity(exception.getMessage()).type("text/plain").build();
    }
}

and added it to the Application:
@ApplicationPath("rest")
public class JaxRsApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        return new HashSet<Class<?>>(Arrays.asList(EntityNotFoundExceptionMapper.class));
    }
}

But there is a problem - if I want it to work, I have to define an endpoint, let's say "C" and throw there EntityNotFoundException. But I want it to be thrown for every unimplemented endpoint. I'm afraid there is an infinite number of such cases...

A: Add the below method in your controller
@ExceptionHandler(ResourceNotFoundException.class)
        @ResponseStatus(HttpStatus.NOT_FOUND)
        public String handleResourceNotFoundException() {
            return "page not found";
        }

and below class to your code:
public class ResourceNotFoundException extends RuntimeException { }

Instead of returning page not found string, you can return a page by specifying some model in the method.

A: With JAX-RS, you can define an ExceptionMapper to map an exception to a Response:
@Provider
public class NotImplementedExceptionMapper
       implements ExceptionMapper<NotImplementedException> {

    @Override
    public Response toResponse(EntityNotFoundException ex) {
        String html = ...
        return Response.status(501).entity(html).type(MediaType.TEXT_HTML).build();
    }
}

For more details on handling errors in JAX-RS, refer to this answer.

Picking the right status code:

*

*If a resource cannot be found on the server, you should return a response with the 404 status code. It indicates a client error.

*If you actually want to indicate that something has not been implemented and the request cannot be handled, you should return a response with the 501 status code. It indicates a server error.


text:
Q: Android dependency 'io.reactivex.rxjava2:rxandroid' has different version When sync project with gradle files, Android Studio shows this error:
Android dependency 'io.reactivex.rxjava2:rxandroid' has different version for the compile (2.0.1) and runtime (2.1.0) classpath. You should manually set the same version via DependencyResolution

I have try to solve it with:
resolutionStrategy.force 'io.reactivex.rxjava2:rxandroid:2.1.0'

But with the same result.
This problem occurs when I change 'compile' with 'implementation' in the libraries definition
This is how I define the rest of the rx libraries:
buildscript {

    ext.retrofitVersion = '2.4.0'
    ext.rxVersion = '2.2.1'
    ext.rxAndroidVersion = '2.1.0'
    ext.okhttpVersion = '3.8.1'
    ext.rxKotlinVersion = '2.0.0'

    ...

    repositories {
        mavenCentral()
        jcenter()
    }

}
//Rx & Retrofit 2 **********************************
implementation("com.squareup.retrofit2:retrofit:$retrofitVersion") {
    // exclude Retrofit's OkHttp peer-dependency module and define your own module import
    exclude module: 'okhttp'
}
implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion"
implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion"
implementation "io.reactivex.rxjava2:rxkotlin:$rxKotlinVersion"
implementation "com.squareup.okhttp3:okhttp:$okhttpVersion"
implementation "com.squareup.okhttp3:logging-interceptor:$okhttpVersion"
implementation "io.reactivex.rxjava2:rxandroid:${rxAndroidVersion}"
implementation "io.reactivex.rxjava2:rxjava:$rxVersion"

Any ideas how can I solve this problem?

A: Ok, finally I solved the problem following the @yayo-arellano solution. I was to replace "implementation" by "api".


text:
Q: Pass CDN domain name to origin server I was wondering if Amazon Cloudfront can pass to the origin server the CDN domain name the request is coming from. Let me explain.

*

*I have an external LAMP server, associated to an origin domain (e.g., origin.mydomain.com)

*I've successfully set up Cloudfront, setting origin.mydomain.com as origin server

*Finally, I pointed 2 different (CDN) domains to Cloudfront (e.g., www.firstdomain.com and www.seconddomain.com)

Now, all this setup is working perfectly.
But there is 1 information I'm missing: when the origin server (origin.mydomain.com) receives a request, I haven't found a way to know if the request originally comes from www.firstdomain.com or www.seconddomain.com; cloudfront sends to the origin server all information about the request, except the original CDN domain - or if it does, I don't know how/where to get it.
So, resuming, I have this:
DNS domain(s) -> Cloudfront -> Origin domain -> LAMP Server
The question is: How can LAMP get the DNS domain name the request is originally coming from?
Do I miss any cloudfront setting, or there is some trick I can use to get that info?
Note: I know I can create several properties pointing to the same origin server, but that is not a viable solution for this project.

A: You'll have to use the logging in Cloudfront, because the only time that Cloudfront actually makes requests to your server is when they do not have a cached version of that particular file.
To turn on logging you need to log into the AWS Console and choose Edit in the Distribution Details for the distribution you want to enable access logs to be delivered. Then you set the target bucket and prefix for AWS to deliver log files to. The logging target should be another S3 bucket than the origin. Otherwise your report will include requests for log files delivered by Amazon and download requests for log files.
When you configure logging it will save logs in the bucket you specified in this format: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/AccessLogs.html#LogFileFormat