text:
Q: How to get specific information from Firestore when specific row is tapped The goal here is to get specific information from Firebase Firestore when tapping on a specific row from Table View in Xcode. I have already found a way to store the data into a Table View:
func loadData() {
        FirebaseFirestore.root.collection("users").getDocuments { (snapshot, error) in
            if let error = error {
                print(error.localizedDescription)
            } else {
                if let snapshot = snapshot {

                    for document in snapshot.documents {

                        let data = document.data()
                        let name = data["name"] as? String ?? ""
                        let email = data["email"] as? String ?? ""
                        let phone = data["phone"] as? String ?? ""

                        let newPerson = Person(name: name, email: email, phone: phone)
                        self.people.append(newPerson)
                        print (self.people)

                        let newIndexPath = IndexPath(row: self.people.count - 1, section: 0)

                        self.table.beginUpdates()
                        self.table.insertRows(at: [newIndexPath], with: .automatic)
                        self.table.endUpdates()
                    }
                }
            }
        }
    }

And when running, this shows up:

When I tap row 1, for example, I want to segue into another view that displays the name, email, phone for each specific row. Is this possible? And if so, how would I do this?
------------------------------
So far, I thought of adding another variable to each row, but not displaying on the row. Since in Firebase, the document id is the email, I can set the var email to every row, and use getDocument() to retrieve the document by email, the document id.
All I've done was use the variable email to try to use getDocument on the didSelectRowAt function.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let tappedUser = FirebaseFirestore.root.collection("users").document(email)

        performSegue(withIdentifier: "toPersonDesc", sender: nil)
    }

But this doesn't work. I don't think I can use the email var since it gives an error for Person.email, and just email.
Any help would be appreciated.
-------------------------------
Entire code block if anyone needs it (updated to what I've tried):
import UIKit
import FirebaseFirestore

struct Person {
    let name, phone, email: String
}

class Cell: UITableViewCell {
    @IBOutlet weak var phone: UILabel!
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var email: UILabel!
}

class PeopleViewController: UITableViewController {

    @IBOutlet var table: UITableView!

    var people = [Person]()
    private var document: [DocumentSnapshot] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        table.tableFooterView = UIView(frame: CGRect.zero)
        self.table.delegate = self
        self.table.dataSource = self

        loadData()

    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.people.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let person = people[indexPath.row]
        let cell = self.table.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Cell

        cell.name.text = person.name
        cell.phone.text = person.phone
        cell.email.text = person.email

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let tappedUser = FirebaseFirestore.root.collection("users").document(Person.email)//Error here

        performSegue(withIdentifier: "toPersonDesc", sender: nil)
    }

    func loadData() {
        FirebaseFirestore.root.collection("users").getDocuments { (snapshot, error) in
            if let error = error {
                print(error.localizedDescription)
            } else {
                if let snapshot = snapshot {

                    for document in snapshot.documents {

                        let data = document.data()
                        let name = data["name"] as? String ?? ""
                        let phone = data["phone"] as? String ?? ""
                        let email = data["email"] as? String ?? ""

                        let newPerson = Person(name: name, phone: phone, email: email)
                        self.people.append(newPerson)
                        print (self.people)

                        let newIndexPath = IndexPath(row: self.people.count - 1, section: 0)

                        self.table.beginUpdates()
                        self.table.insertRows(at: [newIndexPath], with: .automatic)
                        self.table.endUpdates()
                    }
                }
            }
        }
    }

A: Hey this actually isn't that difficult fortunately.  All you need to do is something like this:
//Create a custom UIViewController class which has a property of type Person.
class CustomViewController : UIViewController {
    var person: Person?
    // You'll need to set this up using a .xib file
    weak var customView:CustomView?
}

class UsersViewController : UIViewController, UITableViewDelegate {
    var person:[Person]?

    //This method will be executed every time the user clicks on the row. Make sure that your current class adopts the UITableViewDelegate protocol.
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //Insert your functionality to get the correct person and set the person property in the new custom view controller.
        let viewController = CustomViewController()
        viewController.person = self.person?[indexPath.row]
        // Display the new custom view controller.
        self.navigationController?.pushViewController(viewController, animated: true)
    }
}

Explanation:

*

*Create a custom UIViewController class which has a property of type Person.

*This method - func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) - will be executed every time the user clicks on the row.  Make sure that your current class adopts the UITableViewDelegate protocol.

*Within the didSelectRow function, insert your functionality to get the correct person and set the person property in the new custom view controller.

*Display the new custom view controller.

You will need to make sure that you set up the view of the view controller to display the data in the person object.  Check out this video if you need to know how to do that.
If you want any clarification of this just let me know!
Edit:
There are multiple ways to do this.  Firebase has a functionality to watch a document and if there are changes to the document server-side than you can apply those changes in the app.  Check it out here.
I would probably look into using something like that.
Or you can fetch the data within the didSelectRow and than once the data is retrieved show the new view controller.


text:
Q: ¿Cómo obtener el total de entradas y salidas según el mes y año en una sola consulta sql? Tengo 3 tablas relacionadas:

*

*producto (id_producto, codigo_producto, nombre_producto, descripcion_producto)

*entradas (id_entrada, producto, cantidad_entrada, fecha_entrada)

*salidas (id_salida, producto, cantidad_salida, fecha_salida)

Me gustaría obtener el total de entradas y salidas (en un determinado mes y año) en una sola consulta para llenar una tabla html. Por ahora, tengo dos consultas:
SELECT producto.codigo_producto,
  SUM(entradas.cantidad_entrada) AS total_entradas,
  entradas.fecha_entrada
  FROM producto JOIN entradas
  ON producto.id_producto = entradas.producto
  WHERE MONTH(entradas.fecha_entrada)
  AND YEAR(fecha_entrada) = '2018'
  GROUP BY producto.codigo_producto
  ORDER BY producto.codigo_producto ASC;

SELECT producto.codigo_producto,
  SUM(salidas.cantidad_salida) AS total_salidas,
  salidas.fecha_salida
  FROM producto JOIN salidas
  ON producto.id_producto = salidas.producto
  WHERE MONTH(salidas.fecha_salida)
  AND YEAR(fecha_salida) = '2018'
  GROUP BY producto.codigo_producto
  ORDER BY producto.codigo_producto ASC;

Y necesito algo como esto (filtrado por mes y año):
SELECT producto.codigo_producto,
  SUM(entradas.cantidad_entrada) AS total_entradas,
  SUM(salidas.cantidad_salida) AS total_salidas
  FROM producto
  INNER JOIN entradas
  ON producto.id_producto = entradas.producto
  INNER JOIN salidas
  ON producto.id_producto = salidas.producto
  GROUP BY producto.codigo_producto
  ORDER BY producto.codigo_producto ASC;

Estos son algunos de los datos que estoy utilizando:
INSERT INTO `entradas`
(`id_entrada`, `producto`, `fecha_entrada`, `cantidad_entrada`)
VALUES
(1, 1, '2018-09-01', 55),
(2, 2, '2018-09-01', 82),
(3, 3, '2018-09-01', 25),
(4, 4, '2018-09-01', 52),
(5, 3, '2018-09-01', 25),
(6, 5, '2018-09-01', 12);

INSERT INTO `salidas`
(`id_salida`, `producto`, `fecha_salida`, `cantidad_salida`)
VALUES
(1, 1, '2018-09-30', 25),
(2, 2, '2018-09-30', 12),
(3, 3, '2018-09-30', 45),
(4, 8, '2018-09-30', 18);

Según esos datos, me gustaría obtener lo siguiente:

No sé si me estoy explicando bien, espero que alguien pueda ayudarme con esto...

A: Creo que te refieres a combinar las consultas que ya tienes, así:
SELECT * FROM (
    SELECT producto.codigo_producto,
      SUM(entradas.cantidad_entrada) AS total_entradas,
      entradas.fecha_entrada
      FROM producto JOIN entradas
      ON producto.id_producto = entradas.producto
      WHERE MONTH(entradas.fecha_entrada)
      AND YEAR(fecha_entrada) = '2018'
      GROUP BY producto.codigo_producto
  ) e LEFT JOIN (
    SELECT producto.codigo_producto,
      SUM(salidas.cantidad_salida) AS total_salidas,
      salidas.fecha_salida
      FROM producto JOIN salidas
      ON producto.id_producto = salidas.producto
      WHERE MONTH(salidas.fecha_salida)
      AND YEAR(fecha_salida) = '2018'
      GROUP BY producto.codigo_producto
  ) s USING(codigo_producto)
  ORDER BY codigo_producto ASC;

Si combinas las tres tablas con INNER JOIN te desaparecerán los artículos que aún no tengan salida y, si además haces un GROUP BY, sumarás los que hayan entrado con los que hayan salido. Supongo que es con lo que te has encontrado y por eso has pedido ayuda.
Espero que esto resuelva tu problema. Simplemente es un JOIN entre subconsultas en vez de el habitual entre tablas. Fíjate que no ha sido necesario tocar las consultas que ya tenías, simplemente las pones entre paréntesis y les asignas un alias.
El LEFT JOIN es para que te aparezcan los productos que tienen entradas, pero aún no tienen salidas. Si necesitas ver todos los productos, aunque no tengan entradas y salidas, utiliza LEFT JOIN en vez de JOIN justo después del FROM de cada subconsulta. E implementa un FULL JOIN mendiante una UNION de LEFT JOIN y RIGHT JOIN, tal que así:
SELECT codigo_producto,total_entradas,fecha_entrada,
  total_salidas,fecha_salida FROM (
    SELECT producto.codigo_producto,
      SUM(entradas.cantidad_entrada) AS total_entradas,
      entradas.fecha_entrada
      FROM producto LEFT JOIN entradas
      ON producto.id_producto = entradas.producto
      WHERE MONTH(entradas.fecha_entrada)
      AND YEAR(fecha_entrada) = '2018'
      GROUP BY producto.codigo_producto
  ) e LEFT JOIN (
    SELECT producto.codigo_producto,
      SUM(salidas.cantidad_salida) AS total_salidas,
      salidas.fecha_salida
      FROM producto LEFT JOIN salidas
      ON producto.id_producto = salidas.producto
      WHERE MONTH(salidas.fecha_salida)
      AND YEAR(fecha_salida) = '2018'
      GROUP BY producto.codigo_producto
  ) s USING(codigo_producto)
UNION
SELECT codigo_producto,total_entradas,fecha_entrada,
  total_salidas,fecha_salida FROM (
    SELECT producto.codigo_producto,
      SUM(entradas.cantidad_entrada) AS total_entradas,
      entradas.fecha_entrada
      FROM producto LEFT JOIN entradas
      ON producto.id_producto = entradas.producto
      WHERE MONTH(entradas.fecha_entrada)
      AND YEAR(fecha_entrada) = '2018'
      GROUP BY producto.codigo_producto
  ) e RIGHT JOIN (
    SELECT producto.codigo_producto,
      SUM(salidas.cantidad_salida) AS total_salidas,
      salidas.fecha_salida
      FROM producto LEFT JOIN salidas
      ON producto.id_producto = salidas.producto
      WHERE MONTH(salidas.fecha_salida)
      AND YEAR(fecha_salida) = '2018'
      GROUP BY producto.codigo_producto
  ) s USING(codigo_producto)
ORDER BY codigo_producto ASC;

Aporto la estructura de las tablas para facilitar comprobaciones:
CREATE TABLE `producto` (
  `id_producto` int(11) DEFAULT NULL,
  `codigo_producto` varchar(15) DEFAULT NULL
);

CREATE TABLE `entradas` (
  `id_entrada` int(11) DEFAULT NULL,
  `producto` int(11) DEFAULT NULL,
  `fecha_entrada` date DEFAULT NULL,
  `cantidad_entrada` int(11) DEFAULT NULL
);

CREATE TABLE `salidas` (
  `id_salida` int(11) DEFAULT NULL,
  `producto` int(11) DEFAULT NULL,
  `fecha_salida` date DEFAULT NULL,
  `cantidad_salida` int(11) DEFAULT NULL
);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Id returned 1 exit status. C++ I'm very new to C++, so I've probably made some really stupid mistakes. But I've looked online to solutions for this error, and I tried all I can think of.
I'm trying to have my whole program in one function, because it's going to be merged with other programs. The id error is the only error I have so far.
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>

using namespace std;
int ninebooking(int Endor=0, int Naboo=0, int tatooine=0);
int sevenbooking(int Endor=0, int Naboo=0, int tatooine=0);
void BookingSystem(int time, int k);
int time;
int k = 0;

int main()
{
BookingSystem(time, k);
{
while (k==0)
{
printf("\n\nMeals are served at 9pm and 7pm, please enter what time you would like to book for");
scanf("You have selected to book your meal for %d", &time);
if (time!=7||time!=9)
{
        printf("Sorry, that was an incorrect time");
        time = 0;
}
}
return 0;
}

system ("pause");
return 0;
}

Any help is much appreciated, I've spent a long time trying to fix this on my own with no luck.
Thank you!

A: You make many mistakes in your program:
1) You mix C & C++ syntax.
using namespace std, is C++
2) You include useless header files
3) You declare variables that I don't understand what for
Why do you need this?
int ninebooking(int Endor=0, int Naboo=0, int tatooine=0);
int sevenbooking(int Endor=0, int Naboo=0, int tatooine=0);
You don't use the variables above anywhere !!!!
4) You try to write a function inside main (this is not Pascal).
So, if I understand what you want, look at this:
#include <stdio.h>

void BookingSystem() // this is the function who does all job
{
    int time = 0;

    while ((time != 7) && (time != 9))
    {
        printf("\n\nMeals are served at 9pm and 7pm, please enter what time you would like to book for");
        printf("\nYou have selected to book your meal for ");
        scanf("%d", &time); // read the time
        scanf("%*[^\n]");   // consume all caracters until the newline
        scanf("%*c");       // consume the newline
        if (time == 7)
        {
            printf("You have selected to book your slot at 7PM\n");
        }
        else if (time == 9)
        {
            printf("You have selected to book your slot at 9PM\n");
        }
        else
        {
            printf("You have selected an incorrect time, please try again\n");
        }

    } // end while
} // end function

int main(int argc, char *argv[])
{
    BookingSystem(); // this is the calling to your function

    return 0;
}

If I understand what you want, this works fine.

A: you can not to Define Function in to the main ..
you must to do like this...
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>

using namespace std;

int ninebooking(int , int , int );  //just say data type int or ....
int sevenbooking(int , int , int );
void BookingSystem(int , int);

int main() //and in to main just call he...
{
 int time;
 int k = 0;

 BookingSystem(time, k);//call ....and send parameter time and k

 system ("PAUSE");
 return 0;

}

void BookingSystem(int time,int k)
{
    while (k==0)
    {
        printf("\n\nMeals are served at 9pm and 7pm, please enter what time you would like to book for");
        scanf("You have selected to book your meal for %d", &time);
        if (time!=7||time!=9)
        {
            printf("Sorry, that was an incorrect time");
            time = 0;
        }
    }
    //  return 0;//if this function is void he can not to return any thing!!!!
}

int ninebooking(int Endor=0, int Naboo=0, int tatooine=0)
{
    //......
}

int sevenbooking(int Endor=0, int Naboo=0, int tatooine=0)
{
    //........
}


text:
Q: Adding Ng directives to Dynamically Created Buttons The goal of this code is to dynamically generate ng-containers that generate buttons with classes that either is active or inactive depending on a user's permissions list. Due to limitations currently, I can not retrieve the permissions list and need to create the buttons before the permissions list is pulled from the user token.
I am trying to create buttons on the OnInit() for the component, which has a series of ng-templates that are chosen between via ngIf directives according to the users permissions map which is stored locally.
I have looked around and understand that directives need to be compiled, but was wondering if there are any tricks or help I can be pointed to as my search has only pulled up common references to it not being possible or tricks that require already generating part of the html.
component.ts
import { KeyValuePipe } from '@angular/common';
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Route } from '@angular/router';
import { createPopper } from '@popperjs/core';
import * as libs from '../../../../assets/jsonFiles/libs.json';

@Component({
  selector: 'app-libs-view',
  encapsulation: ViewEncapsulation.None,
  templateUrl: './libs-view.component.html',
  styleUrls: ['./libs-view.component.css']
})
export class LibsViewComponent implements OnInit {

  hasLibraryAccess = new Map<String, boolean>();
  constructor(route: ActivatedRoute) {  }

  ngOnInit(): void {
    this.formatLibraryButtons()
  }

  formatLibraryButtons() {
    let btnLayoutHlpr = 0;

    // hard coded for now to test the original 12 buttons
    // should read json and get each library, and create a button correctly for it
    for (let eachLib in Libs) {
      let lib = Libs[eachLib].Name
      console.log(lib)
      // https://www.typescriptlang.org/docs/handbook/dom-manipulation.html
      if (btnLayoutHlpr < 2) {
        const btnGrp = document.getElementById("btnGrp1");
        //this.createButton(btnGrp!, lib)
        ++btnLayoutHlpr;
      } else if (btnLayoutHlpr < 4) {
        const btnGrp = document.getElementById("btnGrp2");
        //this.createButton(btnGrp!, lib)
        ++btnLayoutHlpr
      } else if (btnLayoutHlpr < 6) {
        const btnGrp = document.getElementById("btnGrp3");
        //this.createButton(btnGrp!, lib)
        ++btnLayoutHlpr
      } else if (btnLayoutHlpr < 9) {
        const btnGrp = document.getElementById("btnGrp4");
        //this.createButton(btnGrp!, lib)
        ++btnLayoutHlpr
      } else if (btnLayoutHlpr < 12) {
        const btnGrp = document.getElementById("btnGrp5");
        //this.createButton(btnGrp!, lib)
        ++btnLayoutHlpr
      } else {
        //console.log("check")
        ++btnLayoutHlpr
      }

     // setting all to true for dev purposes
      this.hasLibraryAccess.set(lib, true); all library names must start lowercase or angular's auto-sort method messes up btn placement

    }
    console.log("Button creation complete")
    console.log("Library Access Map Created")
 }

  createButton(btnGrp : Element, lib: string) {
    // create ng-content div to hold logic for if library is accessible
    const ngCont = document.createElement("ng-container")

    // create ngIf for checking if customer has access to library
    const ngIf = document.createElement("div")
    //ngIf add ngIf to the div such that ngIf=libraryAccess.value | then libAccessTrue else libAccessFalse
    ngCont.appendChild(ngIf)

   // create first template to add library access button
    const ngTemp = document.createElement("ng-template")
    //ngTemp.add add #LibraryAccessTrue

    // create div wrapper for btn
    const divWrapper = document.createElement("div")
    divWrapper.style.marginLeft = "1 px";

    // create accessible btn and add it to  divWrapper and add divWrp to template
    const libBtn = document.createElement("a");
    libBtn.classList.add('hexagon', 'd-flex', 'align-self-center');
    libBtn.textContent = lib;
    divWrapper.appendChild(libBtn)
    ngTemp.appendChild(divWrapper)

    // add first template for accessible library button to ng-content
    ngCont.appendChild(ngTemp);

    // create second template to add library access button
    const ngTemp2 = document.createElement("ng-template")
    //ngTemp.add add #LibraryAccessTrue

    // create second div wrapper for btn
    const divWrapper2 = document.createElement("div")
    divWrapper2.style.marginLeft = "1 px";

    // create disabled btn and add it to its divWrapper then to template
    const libBtn2 = document.createElement("a");
    libBtn2.classList.add('hexagon-disabled', 'd-flex', 'align-self-center');
    libBtn2.textContent = lib;
    divWrapper2.appendChild(libBtn2)
    ngTemp2.appendChild(divWrapper2)

    // add second template for disabled library button to ng-content
    ngCont.appendChild(ngTemp2);

    // add the entire ng-content div to the button group
    btnGrp?.appendChild(ngCont);
  }

}

component.html

component.css
.parent-hexagon {
  max-width: 90%;
  width: 40vw;
  height: 42vh;
  background: green;
  position: absolute;
  z-index: 0;
}

  .parent-hexagon::before {
    content: "";
    position: absolute;
    top: -20vh;
    left: 0;
    width: 0;
    height: 0;
    border-left: 20vw solid transparent;
    border-right: 20vw solid transparent;
    border-bottom: 20vh solid green;
  }

  .parent-hexagon::after {
    content: "";
    position: absolute;
    bottom: -25vh;
    left: 0;
    width: 0;
    height: 0;
    border-left: 20vw solid transparent;
    border-right: 20vw solid transparent;
    border-top: 25vh solid green;
  }

.hexagon {
  width: 7.5vw;
  min-width: 100%;
  max-width: 100%;
  height: 8.5vh;
  color: black;
  font-size: 90%;
  justify-content: center;
  text-align: center;
  text-decoration: none;
  background: #bfe8f7;
  position: relative;
  z-index: 1;
  margin-bottom: 28.865px;
}

  .hexagon::before {
    content: "";
    position: absolute;
    top: -28.8675px;
    left: 0;
    width: 0;
    height: 0;
    border-left: 3.75vw solid transparent;
    border-right: 3.75vw solid transparent;
    border-bottom: 28.8675px solid #bfe8f7;
  }

  .hexagon::after {
    content: "";
    position: absolute;
    bottom: -28.8675px;
    left: 0;
    width: 0;
    height: 0;
    border-left: 3.75vw solid transparent;
    border-right: 3.75vw solid transparent;
    border-top: 28.8675px solid #bfe8f7;
  }

  .hexagon:hover {
    background: #7fd1ef;
    z-index: 2;
    transform: scale(1.15)
  }

    .hexagon:hover:before {
      content: "";
      position: absolute;
      top: -28.8675px;
      left: 0;
      width: 0;
      height: 0;
      border-left: 3.75vw solid transparent;
      border-right: 3.75vw solid transparent;
      border-bottom: 29.8675px solid #7fd1ef;
    }

    .hexagon:hover:after {
      content: "";
      position: absolute;
      bottom: -28.8675px;
      left: 0;
      width: 0;
      height: 0;
      border-left: 3.75vw solid transparent;
      border-right: 3.75vw solid transparent;
      border-top: 29.8675px solid #7fd1ef;
    }

.hexagon-disabled {
  width: 7.5vw;
  height: 8.5vh;
  color: black;
  font-size: 90%;
  justify-content: center;
  text-align: center;
  text-decoration: none;
  background: #caced0;
  position: relative;
  z-index: 1;
  margin-bottom: 28.865px;
}

  .hexagon-disabled::before {
    content: "";
    position: absolute;
    top: -28.8675px;
    left: 0;
    width: 0;
    height: 0;
    border-left: 3.75vw solid transparent;
    border-right: 3.75vw solid transparent;
    border-bottom: 28.8675px solid #caced0;
  }

  .hexagon-disabled::after {
    content: "";
    position: absolute;
    bottom: -28.8675px;
    left: 0;
    width: 0;
    height: 0;
    border-left: 3.75vw solid transparent;
    border-right: 3.75vw solid transparent;
    border-top: 28.8675px solid #caced0;
  }

  .hexagon-disabled:hover {
    background: #caced0;
    z-index: 2;
    transform: scale(1.15)
  }

    .hexagon-disabled:hover:before {
      content: "";
      position: absolute;
      top: -28.8675px;
      left: 0;
      width: 0;
      height: 0;
      border-left: 3.75vw solid transparent;
      border-right: 3.75vw solid transparent;
      border-bottom: 29.8675px solid #caced0;
    }

    .hexagon-disabled:hover:after {
      content: "";
      position: absolute;
      bottom: -28.8675px;
      left: 0;
      width: 0;
      height: 0;
      border-left: 3.75vw solid transparent;
      border-right: 3.75vw solid transparent;
      border-top: 29.8675px solid #caced0;
    }

As shown above, the issue is the html is pretty sparse beyond setting up the button groups and the ngFor directives to iterate the libraryAccessPermissions map that tells the ng-containers being dynamically created which ng-template to show. If I could get the permissions, I would forgo the ngIf and just generate the buttons with css classes dependent on their permissions. But since they won't, for project reasons, be given till after the components Init(), I have to create templates and a permission map to track and properly show buttons.
Any help on how to generate these buttons would be welcome and grateful for.

A: no,no,no,no...
We are using Angular. Angular is related to use variables in .ts and show data in the .html. So you need "think in variables"
Imagine a variable like
groupButtons=[
   [{text:"one",level:0},{text:"two",level:1}],
   [{text:"three",level:0},{text:"four",level:0}],
   [{text:"five",level:99}]
]
user={name:"USER 1",level:99} //I imagine a variable "user"

You can easy use *ngFor and *ngIf (see the docs)
 to write

            <ng-container *ngFor="button of group">

                 <a [class.hexagon-disabled]="user.level<button.level"

                    (click)="user.level>=button.level && doSomething(button)">
                    {{button.text}}

            </ng-container>

See that you not create buttons in the javascript way, else allow Angular show the buttons (and add classes) using variables
NOTE: It's only an example


text:
Q: How to extract data from a single cell into multiple columns using scala in Spark I have a dataset with space delimiter in my column "_raw"
I need to extract data from this column into multiple columns
"_raw" column:
Device          rReq_PS      wReq_PS        rKB_PS        wKB_PS  avgWaitMillis   avgSvcMillis   bandwUtilPct

sda                7.00         0.00         64.00          0.00           8.71           8.43           5.90

sdc                0.00         0.00          0.00          0.00           0.00           0.00           0.00

sdb                5.00        10.00         32.00         40.00           2.67           2.67           4.00

dm-0               1.00         0.00          8.00          0.00           9.00           9.00           0.90

dm-1               6.00         0.00         56.00          0.00           8.67           8.33           5.00

dm-2               5.00        10.00         32.00         40.00           2.67           2.67           4.00
dm-3               0.00         0.00          0.00          0.00           0.00           0.00           0.00

dm-4               0.00         0.00          0.00          0.00           0.00           0.00           0.00

dm-5               0.00         0.00          0.00          0.00           0.00           0.00           0.00

dm-6               0.00         0.00          0.00          0.00           0.00           0.00           0.00

dm-7               0.00         0.00          0.00          0.00           0.00           0.00           0.00

dm-8               0.00         0.00          0.00          0.00           0.00           0.00           0.00

dm-9               0.00         0.00          0.00          0.00           0.00           0.00           0.00

I was able to extract with a specific string but unable to get it with all the strings
val log = spark.read.format("com.databricks.spark.csv")
      .option("inferSchema", "true")
      .option("header", "true")
      .option("sep", ",")
      .option("delimiter", "|")
      .option("multiLine", "true")
      .load("query4.csv").cache()

    log.createOrReplaceTempView("logs")
    val df = spark.sql("select _time, _raw, host from logs")

    import spark.implicits._
    val extractbandwUtilPct
    = udf{(raw: String) => raw
      .split("\n")
      .map(_.split(" +"))
      .find(_(0) == "sda")
      .map(_(7)).getOrElse("unknown")}

    val extractedData = df.filter(
      $"host" === "ausflscgap01.us.dell.com" ||
        $"host" ==="ausflscgap02.us.dell.com" ||
        $"host" === "ausplscgap01.us.dell.com" ||
        $"host" === "ausplscgap02.us.dell.com")
      .withColumn("bandwUtilPct", extractbandwUtilPct($"_raw")).drop("_raw").show()

I need to extract the _raw column with two new columns "Device" and "bandwUtilPct"
Device  bandwUtilPct
sda     5.90
sdc     0.00
sbd     4.00
dm-0    0.90
dm-1    5.00
dm-2    4.00
dm-3    0.00
'
'
'
dm-9    0.00

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions.{col, _}
import org.apache.spark.sql.functions._
object IOSTAT_extracted_data {

  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder()
      .appName("IOSTAT")
      .master("local[*]")
      .getOrCreate()

    import spark.implicits._

    val log = spark.read.format("com.databricks.spark.csv")
      .option("inferSchema", "true")
      .option("header", "true")
      .option("multiLine", "true")
      .load("query4.csv").cache()

   val df = log.select("_time", "_raw", "host").toDF()

    import spark.implicits._
    case class RawInfo(Device: String, bandwUtilPct: String)

    val extractRawInfo = udf{raw: String =>
      val all = raw
        .split("\n")
        .map(_.split(" +"))
        .find(_(0) == "sda")

      def getValue(pos: Int) = all.map(_(pos)).getOrElse("unknown")

      RawInfo(
        Device = getValue(0),
        bandwUtilPct = getValue(7))
    }

    val extractedData = df.filter($"host".isin("ausflscgap01.us.dell.com", "ausflscgap02.us.dell.com", "ausplscgap01.us.dell.com", "ausplscgap02.us.dell.com"))
      .withColumn("info", extractRawInfo($"_raw"))
      .select("info.device", "info.bandwUtilPct", "host", "time")
      .drop("info")
      .show()

//    extractedData.coalesce(1).write.format("csv").option("header", "true").option("sep", ",").option("multiLine", "true").save("IOSTAT_extracted_data")
  }
}

A: You can return several values from udf: Array[...] or case class.
Personaly, I prefer case classes like this:
case class RawInfo(device: String, bandwUtilPct: String)

val extractRawInfo = udf{(raw: String) =>
      val all = raw
        .split("\n")
        .map(_.split(" +"))
        .find(_(0) == "sda")

      def getValue(pos: Int) = all.map(_(pos)).getOrElse("unknown")

      RawInfo(
        device = getValue(0),
        bandwUtilPct = getValue(7))
    }

    df.filter($"host".isin("ausflscgap01.us.dell.com", "ausflscgap02.us.dell.com", "ausplscgap01.us.dell.com", "ausplscgap02.us.dell.com"))
      .withColumn("info", extractRawInfo($"_raw"))
      .select(......, "info.device", "info.bandwUtilPct")
      .show()


text:
Q: Is it possible to create Noobaa bucket without creating ObjectBucketClaim(OBC)? I am able to create noobaa bucket by creating OBC as shown below:
apiVersion: objectbucket.io/v1alpha1
kind: ObjectBucketClaim
metadata:
  name: my-obc1
spec:
  storageClassName: noobaa-test.noobaa.io
  bucketName: my-bucket
  additionalConfig: {}

Above OBC will create a noobaa bucket my-bucket.
But is there any way we can create noobaa bucket directly without having to create OBC?

A: There are several ways to create buckets in noobaa other than OBC:

*

*You can use the UI - open with noobaa ui.

*You can use the simple command - noobaa bucket create <name>.

*You can use the internal API - noobaa api bucket create_bucket '{ "name": "<name>" ... }' (see here the json schema of this api params)

*You can use S3 - take the endpoint and credentials from noobaa status.

Thanks! Guy

A: I have had the same issue as I want to be able to create a bucket and for it to have a Tier Policy and Tier associated with it which will point it to the correct backingstore which I had already created, just like you can in the management UI but from the command line. This is what I came up with:-
#!/bin/bash
BUCKET_NAME="my_bucket"
BACKINGSTORE="my_backing_store"

NOW=$(gdate +%s)
TIER_NAME=$(printf "%s.%x" ${BUCKET_NAME} ${NOW})
TIER_POLICY_NAME=$(printf "%s.%d" ${BUCKET_NAME} 1)
noobaa -n noobaa api tier create_tier "{\"name\": \"${TIER_NAME}\", \"attached_pools\": [\"${BACKINGSTORE}\"], \"data_placement\": \"SPREAD\"}"
noobaa -n noobaa api tiering_policy create_policy "{\"name\": \"${TIER_POLICY_NAME}\", \"tiers\": [{\"order\": 1, \"tier\": \"${TIER_NAME}\"}]}"
noobaa -n noobaa api bucket create_bucket "{\"name\": \"${BUCKET_NAME}\", \"tiering\": \"${TIER_POLICY_NAME}\"}"


text:
Q: Redirect a button from a mobile browser to a messaging app on phone Viewing on mobile browser: I have a contact page and i want to add a "SMS" button that when a user clicked it, it will redirect to the default messaging app on mobile together with a set contact number.
How can i achieve this?

A: A biref summary of the functioning of the code I have provided.
On the click of "SMS" button a javascript function will be called which would takeup the value of the contact_no field and redirect to page URL of your default messaging app.
You need to include jquery file on your page:
Here I am providing a baisc code of how the thing works:
HTML:
<input type="text" name="contact_no_input_field" id="contact_no_input_field">
<input type="button" value="SMS" onclick="call_fun()">
<script type="text/javascript">

JS:
function call_fun()
{
     var contact_no = $('#contact_no_input_field').val();
     window.location.href="path/to/default messaging app/?contact_no="+contact_no;
}


text:
Q: Sed Delete a line if a symbol after a pattern is NOT a number I have a text file, containing something like this
                ESSID:"228"
                Frequency:5.02 GHz (Channel 4)
                Quality=7/94  Signal level=-89 dBm  Noise level=-99 dBm

                ESSID:"1_156"
                Frequency:5.305 GHz (Channel 61)
                Quality=28/94  Signal level=-68 dBm  Noise level=-98 dBm

                ESSID:""
                Frequency:5.32 GHz (Channel 64)
                Quality=7/94  Signal level=-89 dBm  Noise level=-98 dBm

                ESSID:""
                Frequency:5.745 GHz (Channel 149)
                Quality=21/94  Signal level=-75 dBm  Noise level=-99 dBm

                ESSID:"Apsnyaimadara"
                Frequency:5.11 GHz (Channel 22)
                Quality=22/94  Signal level=-74 dBm  Noise level=-97 dBm

And i want to get rid of all ESSIDs that are not consist of numbers and a "_" sign. Can you please tell how can i delete a line if it contains ESSID:" and next symbol after that pattern won't be a number? =) In fact i'm looking to delete those blocks completely rather than just a line, but i can start from that, any help would be greatly appreciated =)
P.S. using Sed

A: With GNU sed:
sed -nE '/ESSID:"[0-9_]+"/,/^$/p' file

or with GNU grep:
grep -A3 -E 'ESSID:"[0-9_]+"' file

Output:

                ESSID:"228"
                Frequency:5.02 GHz (Channel 4)
                Quality=7/94  Signal level=-89 dBm  Noise level=-99 dBm

                ESSID:"1_156"
                Frequency:5.305 GHz (Channel 61)
                Quality=28/94  Signal level=-68 dBm  Noise level=-98 dBm


text:
Q: Which of the two population does new measurement belongs to? I have a sample of size 150K from one population of measurements, and another sample of size 1000 from a second population. I receive a new measurement and need to decide which population it is coming from? given the huge difference between the sample sizes, what is the best method to decide which population the new measurement belongs to?

A: So far, this seems to be an extremely vague question. Here is an experiment that might help
clarify the question. Are your histograms sufficiently different
for you to make reasonable choices? Mine are sufficiently different to
allow good choices in some cases.
First, two histograms (made using R):
par(mfrow=c(1,2))
  x1 = rgamma(150000, 10, 1)
   hist(x1, prob=T, col="skyblue2")
  x2 = rexp(1000, 2)
   hist(x2, prob=T, col="skyblue2")
par(mfrow=c(1,1))

If the new single observation is 10.17, then pick the first population.
If the new value is 0.53, then pick the second population.
It is possible, but very unlikely, that 10.17 came from the distribution that resulted in the second histogram. It is possible,
but very unlikely, that 0.53 came from the distribution that resulted in the first histogram. So the choices in
the previous paragraph are reasonable.


text:
Q: Janky pgfplot behaviour with arcsinh function I'm trying to draw a titration curve using pgfplot. Based off this paper, there is an equation for the titration curve:

I've attempted to implement this within pgfplots, and I get a very strange result:

I have no idea why this would occur; even attempting to recreate the exact formula I used within desmos did not work.
For reference, here is the code, and also a link to an overleaf project.
\documentclass{article}
\usepackage{pgfplots}

\begin{document}

\pgfkeys{
    /pgf/declare function={
        arcsinh(\x) = ln(\x + sqrt(\x^2+1));
    },
    /pgf/declare function={
        Va = 0.025;
        Ma = 0.1;
        Mb = 0.1;
        V(\x) = \x / 1000;
        Kw = 1*10^(-14);
        p(\o) = -ln(\o)/ln(10);
    }
}

\begin{center}
\begin{tikzpicture}
    \begin{axis}[
        xlabel = {Solution Added (mL)},
        ylabel = {pH},
        ymin=0,
        ymax=14,
        ytick distance=7,
        xtick distance=10,
    ]
    \addplot[%
        samples=100,
        color=red,
        domain=0:50,
    ]{%
    7 + 1/ln(10) * arcsinh( 1/(2*sqrt(Kw))  *  (Mb*V(x) - Ma*Va) / (Va + V(x)) )
    };
    \end{axis}
\end{tikzpicture}
\end{center}

\end{document}

endnote: if there's a way I can have variables e.g. V_a within the pgfplot function, that'd be much nicer than having constants throughout. thanks Torjorn

A: One gets this strange result because TeXs limits are reached -- as can also be seen by the dropped coordinates -- and thus the "zigzag" results from precision limits (red line). If you use either gnuplot (green dots) or Lua (blue line) as calculation engine, it works as expected. Of course for the Lua solution you have to use LuaLaTeX as TeX engine.

Sidenote:
If you want to avoid to use such a high number of samples, consider reformulating the eqution to make use of non-linear spacing. For that see e.g.

*

*https://tex.stackexchange.com/a/443731/95441

*https://tex.stackexchange.com/a/446727/95441
% used PGFPlots v1.17
\documentclass[border={5pt}]{standalone}
\usepackage{pgfplots}
    % use this `compat` level or higher to use LUA backend for calculation (if possible)
    \pgfplotsset{compat=1.12}
\begin{document}
    % for gnuplot solution
    \newcommand*{\Kw}{1e-14}
    \newcommand*{\Ma}{0.1}
    \newcommand*{\Mb}{0.1}
    \newcommand*{\Va}{0.025}
\begin{tikzpicture}[
    % from https://tex.stackexchange.com/q/144778
    /pgf/declare function={
        % for LUA solution
        arcsinh(\x) = ln(\x + sqrt(\x^2+1));
        Kw = 1e-14;
        Ma = 0.1;
        Mb = 0.1;
        Va = 0.025;
        V(\x) = \x / 1000;
        p(\o) = -0.5*ln(\o)/ln(10);
    },
]
    \begin{axis}[
        xlabel={Solution Added (mL)},
        ylabel={pH},
        domain=0:50,
        samples=201,
    ]
        % gnuplot
        \addplot+ [ultra thick,green,mark size=1pt,only marks,opacity=0.5] gnuplot
            {-0.5*log10(\Kw) + asinh(1/(2*sqrt(\Kw)) * (\Ma*\Va - \Mb*x/1000)/(\Va + x/1000) )/log(10)};
        % Lua(TeX)
        \addplot [thick,blue]
            {p(Kw) + arcsinh(1/(2*sqrt(Kw)) * (Ma*Va - Mb*V(x))/(Va + V(x)) )/ln(10)};
        % TeX
        \addplot [red,opacity=0.75]
            {p(\Kw) + arcsinh(1/(2*sqrt(Kw)) * (Ma*Va - Mb*V(x))/(Va + V(x)) )/ln(10)};
    \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: C# Adding and subtracting to characters in a string I'm reading from a text file and trying to replace all characters with new ones. Depending on what character I read I want to add 13 to it or subtract 13. My problem is that once I change 'a' to 'n' it changes back to 'a' when I get to 'n' and try to subtract. For ex all 'a' should be 'n' and all 'n' should be 'a'.
while ((inValue = inFile.ReadLine()) != null) {
    for (int letter = 'A'; letter < 'z'; letter++)
    {
        if (letter >= 'A' && letter <= 'M')
            inValue = inValue.Replace((char)letter, (char)    (letter + 13));
        else if (letter >= 'N' && letter <= 'Z')
            inValue = inValue.Replace((char)letter, (char)(letter - 13));
        else if (letter >= 'a' && letter <= 'm')
            inValue = inValue.Replace((char)letter, (char)(letter + 13));
        else if (letter >= 'n' && letter <= 'z')
            inValue = inValue.Replace((char)letter, (char)(letter - 13));
    }
}

A: You need to keep track of which character in your string has been changed so you don't change it again. Easier to step through each character in the input string and change it - that way you know it only gets changed once.
while ((inValue = inFile.ReadLine()) != null) {
    // convert to StringBuilder because you can't change the characters within a string
    var sb = new StringBuilder(inValue);
    for (int i = 0; i < inValue.Length; i++ )
    {
        char letter = sb[i];
        if (letter >= 'A' && letter <= 'M')
            sb[i] = (char)(letter + 13);

        else if (letter >= 'N' && letter <= 'Z')
            sb[i] = (char)(letter - 13);

        else if (letter >= 'a' && letter <= 'm')
            sb[i] = (char)(letter + 13);

        else if (letter >= 'n' && letter <= 'z')
            sb[i] = (char)(letter - 13);
        }
    }
    inValue = sb.ToString(); // Convert back to string
    // ... ... ... do something with `inValue`
}

A: It's because you are changing them while you are still inside of your for loop. Keep track of the index of each char that needs to be replaced and what needs to go there. After the loop ends, proceed to loop over a Dictionary which will contain
int: index; char: replacementChar.
So something along these lines:
for (int letter = 'A'; letter < 'z'; letter++)
{
    var charTracker = new Dictionary<int, char>();
    char replacement;
    if (letter >= 'A' && letter <= 'M')
        replacement = (char)(letter-13);
    else if (letter >= 'N' && letter <= 'Z')
       replacement = (char)(letter-13));
    else if (letter >= 'a' && letter <= 'm')
       replacement = (char)(letter + 13));
    else if (letter >= 'n' && letter <= 'z')
       replacement = (char)(letter - 13));

    charTracker.Add(letter, replacement);
}

for(var i = 0; i < charTracker.Length -1; i++)
{
    // Logic to replace chars here
}


text:
Q: How to lookup against a range and return count of a dimension in R I have the NYC Flights data in which one of the dimensions (see last column) is the destination
NYC Flights Data Snapshot
I've got another dataframe where I've got the distinct destinations
Distinct Destinations Data Snapshot
Now I want to add a 2nd column in this dataset which should be the count of flights for that destination as per earlier dataset. Think of countifand lookup equivalent of MS-Excel in R

A: If the first dataframe is called df1 and the second one is df2, you can use :
library(dplyr)
df1 %>% count(dest) %>% right_join(df2, by = 'dest')

This will return NA's for dest present in df2 which are not in df1. If you want to replace them with 0, you can do :
df1 %>%
  count(dest) %>%
  right_join(df2, by = 'dest') %>%
  mutate(n = replace(n, is.na(n), 0))


text:
Q: C++ Functions Select Behavior Based on Passed Parameter Derived Class? What I'm trying to do is to have a base class that has a primary functionality, as well as multiple derived classes that have various other additional functions/variables. The main functionality of all these derived classes will behave very similarly no matter what object of one of the derived classes is passed to it, but with slight changes based on what the derived class is.
So a background here is that I'm mostly experienced with Fortran programming but am trying to break into C++ more. I'm trying to do something here that is pretty easy in Fortran but am having trouble in C++. Basically my code defining my classes looks something like this
class base_class{
  public:
    void prim_func(base_class &my_obj);
};

class derived_class_1: public base_class{
  public:
    int a_func(int arg1);
};

class derived_class_2: public base_class{
  public:
    double a_func(double arg2);
};

And then the void class method looks something like (right now, I know this isn't right)
void base_class::prim_func(base_class &my_obj){
  // a bunch of stuff for all classes
  // if my_obj class is derived_class_1
    my_obj.a_func(1);
    // some more stuff specific to using derived_class_1
  // if my_obj class is derived_class_2
    my_obj.a_func(1.5);
    // some more stuff specific to using derived_class_2
  // a bunch of stuff for all classes
}

I want that prim_func to have (slightly) different behaviors based on what the actual derived class that is passed to it is. So the main code would look like this
derived_class_1 def_obj_1;
derived_class_2 def_obj_2;
main(){
  def_obj_1.prim_func(def_obj_1);
  def_obj_2.prim_func(def_obj_2);
}

So I would like to slightly modify the behavior in this primary functionality based on what the derived class of the passed object actually is. In Fortran there is a SELECT TYPE functionality (https://www.intel.com/content/www/us/en/develop/documentation/fortran-compiler-oneapi-dev-guide-and-reference/top/language-reference/a-to-z-reference/s-1/select-type.html) that allows this, but I can't seem to find something similar in C++?
I know one workaround could be to just make one big class that contains overloaded versions of all the different functions, and all the different variables that the various derived class objects would need, and then just have an indicator variable to let it know which functionality it should be using. But this would be extremely inelegant and would potentially cause some other issues, so I would like to avoid it.

A: You can't do that with plain C++.
You can't have derived classes with overriden functions with different signatures.
What you can do is using templates.
Use a templated Base Class that provides the base function as a pure virtual.
You can then write a wrapper around that function as a template:
template<typename T>
class Base {
    public:
    virtual T func(T param) = 0;
};

class DerivedA : public Base<int> {

    public:
    int func(int param) override {
        return param;
    };
};

class DerivedB : public Base<double> {

    public:
    double func(double param) override {

        return param;
    };
};

template<typename T>
T prim_func(Base<T>& base, T param) {
    return base.func(param);
}

int main() {
    DerivedA a;
    DerivedB b;

    auto c = prim_func(a,4);
    auto d = prim_func(b,4.0);
}

A: Ok, so it turns out there is a way to do this in C++ it just involves dynamic casting a pointer using the passed object (but it does have to be a polymorphic object). So the way I made it work was doing something like this (comparing to the previous incomplete code I had).
class base_class{
  public:
    virtual void a_func(){};
    void prim_func(base_class &my_obj);
};

class derived_class_1: public base_class{
  public:
    int a_func(int arg1);
};

class derived_class_2: public base_class{
  public:
    double a_func(double arg2);
};

void base_class::prim_func(base_class &my_obj){
  // a bunch of stuff for all classes
  if(derived_class_1* class_ptr = dynamic_cast<derived_class_1*>(&my_obj)){
    class_ptr.a_func(1);
    // some more stuff specific to using derived_class_1
  }
  else if(derived_class_2* class_ptr = dynamic_cast<derived_class_2*>(&my_obj)){
    class_ptr.a_func(1.5);
    // some more stuff specific to using derived_class_2
  }
  // a bunch of stuff for all classes
}

derived_class_1 def_obj_1;
derived_class_2 def_obj_2;
main(){
  def_obj_1.prim_func(def_obj_1);
  def_obj_2.prim_func(def_obj_2);
}

To be clear, this still won't compile/work since some of the functions need definitions and what not, but this is a general description of how to do it. A working example can be found in MFEM's code here: https://docs.mfem.org/4.5/amgxsolver_8cpp_source.html#l00859


text:
Q: ui-router/angular-hybrid - route not recognized on initial load/reload It seems that routes that are registered within ng2+ module using the @ui-router/angular-hybrid are not recognized on initial load/reload. The same route is working if e.g. navigated by typing the url.
I've followed the official upgrade docs from @ui-router/angular-hybrid
Here is the ng2+ AppModule code:
const states: NgHybridStateDeclaration[] = [
  {
    name: 'x',
    url: '/x',
    component: XComponent
  }
];

enableProdMode();

@NgModule({
  imports: [
    BrowserModule,
    UpgradeModule,
    UIRouterUpgradeModule.forRoot({states: states}),
    ComponentsModule,
    DirectivesModule
  ],
  declarations: [AppComponent],
  exports: [],
  entryComponents: [],
  providers: [],
  bootstrap: []
})
export class Ng2AppModule {
  constructor(
    @Inject(forwardRef(() => UpgradeModule)) private upgrade: UpgradeModule,
    @Inject(forwardRef(() => Config)) private config: Config
  ) {}

  ngDoBootstrap() {
    this.upgrade.bootstrap(document as any, ['app'], { strictDi: true });
  }
}

And the bootstrapping logic:
AppModule.config([
  '$urlServiceProvider',
  ($urlService: UrlService) => $urlService.deferIntercept()
]);

getConfig()
  .then((config: Config) => {
    console.log('CONFIG::::', config);
    AppModule.constant('config', config);

    setAngularLib(angular);

    platformBrowserDynamic([
      {
        provide: Config,
        useValue: config
      }
    ])
      .bootstrapModule(Ng2AppModule)
      .then(platformRef => {
        platformRef.injector.get<NgZone>(NgZone).run(() => {
          const urlService = platformRef.injector.get(UIRouter).urlService;

          urlService.listen();
          urlService.sync();
        });

        downgradeSharedComponents(AppModule);
      });
  })

P.S. Existing angularjs routes are working properly, the problem is with routes registered within the ng2+ module.
Any help is appreciated, thanks ^^

A: Managed to figure this out on my own and wanted to post the answer in case anyone encounter similar issue.
Turned out we had a weird logic in our old angularjs code that was deferring $urlRouter url synchronization:
$urlRouterProvider.deferIntercept();
...
$urlRouter.sync();

Once removed, issue described above disappeared.


text:
Q: Having Trouble Setting Background Image on Vaadin Login Form I'm trying to figure out how to put a background image in my login page of an application that I am making using Vaadin:
enter image description here
I am not familiar with CSS which is a reason why I am having trouble.
I have tried using the Vaadin Theme Assistant, looking up this question on StackOverflow and the Vaadin Forum but none of those have led me to a solution. When I run my program, no background image loads on the login screen.
Layout of my program:
enter image description here
The image I can trying to use as a background is prepbooks.jpg.
Styles.CSS class:
@import url('./views/list-view.css');
@import url('lumo-css-framework/all-classes.css');

a[highlight] {
    font-weight: bold;
    text-decoration: underline;
}

 .backgroundImage{

      background: url("images/prepbooks.jpg") ;
 }

LoginView. class (the page in which I want the background image to be on):
package com.example.application.views;

import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.html.Image;
import com.vaadin.flow.component.login.LoginForm;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;

@Route("login")
@PageTitle("Login | Sample App")
public class LoginView extends VerticalLayout implements BeforeEnterObserver {

   private final LoginForm login = new LoginForm();

   public LoginView(){

      addClassName("login-view");

      setSizeFull();
      setAlignItems(Alignment.CENTER);
      setJustifyContentMode(JustifyContentMode.CENTER);

      login.setAction("login");

      VerticalLayout header = new VerticalLayout();
      header.add(new H1("Sample App"));
      header.setAlignItems(Alignment.CENTER);

      add(header, login);
   }

   @Override
   public void beforeEnter(BeforeEnterEvent beforeEnterEvent) {
      // inform the user about an authentication error
      if(beforeEnterEvent.getLocation()
            .getQueryParameters()
            .getParameters()
            .containsKey("error")) {
         login.setError(true);
      }
   }
}

A: Place the prepbooks.jpg in the frontend/themes/flowcrmtutorial/images folder. Then you can reference it from the styles.css file.
frontend
└── themes
    └── flowcrmtutorial
        ├── images
        │   └── prepbooks.jpg
        └── styles.css

See the documentation for details: https://vaadin.com/docs/latest/styling/custom-theme/creating-custom-theme/#other-theme-assets
I assume you want to add the background image to the whole view. You already set a CSS class name on it with addClassName("login-view"), so we can use that in our CSS:
styles.css:
.login-view {
  background-image: url("images/prepbooks.jpg");
}


text:
Q: IIS url rewrite http to https subdomain 404 error I'm trying to get my site to go from http://sub.domain.com to redirect to https://sub.domain.com on a company intranet and I want it to work for pages below subdomain as well. I have the url rewrite module installed on IIS 8 and I've tried adding the following in my web.config
<rewrite>
    <rules>
        <rule name="Redirect to HTTPS" stopProcessing="true">
        <match url="(.*)" />
        <conditions>
            <add input="{HTTPS}" pattern="^OFF$" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
        </rule>
    </rules>
</rewrite>

But when I go to http://sub.domain.com I just get a 404 error, and I'm not sure how to debug this.
If I go to https://sub.domain.com I see the web page.
Thanks


text:
Q: How can everyone have doubles if some people were never born? I just finished watching Season 3 Episode 14, where an elderly man and woman had their respective spouses die in each Universe. Their elevated emotions created what was described as quantum entanglement (scientifically nonsense, of course, but that's not why we're here). This created a 'soft spot' and unexplained phenomena throughout the building. The way to stop this from tearing apart the Universe was to convince the elderly woman that her 'husband' was not really her husband, which she discovered after the other Universe's husband had told her that her children missed her, despite the fact that she never had children in her Universe.
How, then, does everyone currently have their own doubles? Are we to believe that every other person and couple had children the same between Universes?

A: There are some differences; Olivia's niece Ella doesn't have a double, for example. However she is an exception; most characters do have doubles. However, this isn't as far-fetched as it at first appears.
Here's the thing about alternate universes in Fringe: there are lots of them. Walter explains this in the first season episode "The Road Not Taken", the clip of which is helpfully on YouTube:

Transcript (with Walter's stammering removed for my own sanity in transcribing):

Walter: Most of us experience life as a linear progression, like this [draws a straight line on the chalkboard]. But this is an illusion because, every day, life presents us with an array of choices. As a result, life should look more like this [draws multiple branching paths from his original line]. And each choice leads to a new path; to go to work, to stay home, and each choice we take creates a new reality. Do you understand?
Fringe Season 1 Episode 19: "The Road Not Taken"

Unfortunately Fringe never really explored this idea, but the implication seems clear: there are literally an infinite number of alternate universes. I don't recall this ever being mentioned on the show, but it stands to reason that the Red Universe is just a universe that's "pretty close" to ours.


text:
Q: Batch script command only works once, the loop does not work I am making a simple script for a network where ever a homefolder is created for every user. Making the users + putting them in the correct group works perfectly but as soon as I add the homefolder part it only executes once.
This script is called 9 times in another script but it only works once.
rem ****** %1 username
rem ****** %2 password
rem ****** %3 group

net user %1 %2 /ADD
net user %1 /logonpasswordchg:no
net user %1 /active:yes
net user %1 /expires:NEVER
net user %1 /times:M-F,8-18
net user %1 /passwordchg:no

net group %3 %1 /add

C:
cd \School\Homefolders\Leerlingen
md %1
echo Y| cacls C:\School\Homefolders\Leerlingen\%1 /G %1:C administrators:F
cd..
cd..
cd..
cd..
C:

A: I just created a similar example and had the same problem caused by changing the directories. You also have an extra "cd .." statement. Try just using the following:
md C:\School\Homefolders\Leerlingen\%1
echo Y| cacls C:\School\Homefolders\Leerlingen\%1 /G %1:C administrators:F

I'm also assuming as it otherwise gets called multiple times that you've remembered to use a call statement in the batch file that calls that one.


text:
Q: Oracle SQL syntax issue - how do I correctly combine 2 queries without error So I have 2 queries. The first returns a list of grid sections, with the number of orders for that grid section:
SELECT DISTINCT customer.grid_section, count(orders.order_pk)
FROM customer INNER JOIN orders
    ON customer.customer_pk = orders.customer_fk
GROUP BY customer.grid_section;

This works fine and outputs (code_output_1):
code_output_1
The second query outputs the average quantity of orders per grid section:
SELECT ROUND(
        (COUNT(DISTINCT orders.order_pk)) /
        (COUNT(DISTINCT customer.grid_section))) as avg
FROM customer, orders;

Again, this works fine and outputs (code_output_2):
code_output_2
What I am trying to achieve is a query which outputs the contents of query 1, where the count(orders.order_pk) column in the main query 1 is equal to the average value calculated in the second query.
I have tried a number of approaches including :
SELECT DISTINCT customer.grid_section, count(orders.order_pk)
FROM customer INNER JOIN orders
    ON customer.customer_pk = orders.customer_fk
WHERE count(orders.order_pk)
    (SELECT ROUND(
        (COUNT(DISTINCT orders.order_pk)) /
        (COUNT(DISTINCT customer.grid_section))) as avg
    FROM customer, orders
    )
GROUP BY customer.grid_section;

which gives an error (error_1):
***ORA-00934: group function is not allowed here
00934. 00000 -  "group function is not allowed here"
*Cause:
*Action:
Error at Line: 4 Column: 7***

as well as:
SELECT DISTINCT customer.grid_section,
    COUNT(orders.order_pk) AS "tot_orders"
FROM customer, orders, (SELECT ROUND(
        (COUNT(DISTINCT orders.order_pk)) /
        (COUNT(DISTINCT customer.grid_section))) AS "avg_orders"
        FROM customer, orders) subq1
WHERE "tot_orders" = "avg_orders"

which gives me another error (error_2):
*ORA-00904: "tot_orders": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:
*Action:
Error at Line: 7 Column: 7*

If anybody could make any suggestions as to what I'm doing wrong or how to achieve the end result I would be most appreciative.
Thanks.

A: The intent of the second query is rather unclear to me, but I suspect that you are trying to filter the first resultset (the count of orders per grid section) for the records whose count matches the (rounded) average of the count.
If so, you can use window functions:
SELECT *
FROM (
    SELECT c.grid_section, COUNT(*) cnt_orders,
        AVG(COUNT(*)) OVER() avg_cnt_orders
    FROM customer c
    INNER JOIN orders o ON c.customer_pk = o.customer_fk
    GROUP BY c.grid_section
) t
WHERE cnt_orders = ROUND(avg_cnt_orders)

Note that I removed the DISTINCTs in your query; they are not needed in an aggregation query such as your first SQL - but your question does not give a lot of details on the cardinality between the different entities, so you might need to adapt this to your actual design.


text:
Q: Concatenating row values sql server 2008 r2 I have two tables register and att_bottom and I want to display only the students at a certain building who have been tardy based on today's date with the periods separated by a comma.
This is the way the data is displayed when joining both tables:
 Student ID |  Building | Period | Grade

   12345          2         1       11
   12345          2         5       11
   43210          2         1       12

I want this:
Student ID | <u>Building | Period | Grade

12345          2         1,5     11
43210          2         1       12

This is my query:
 select r.STUDENT_ID,
        r.BUILDING ,
        (select ab.attendancePeriod + ','
        from att_bottom ab
        where ab.STUDENT_ID = r.student_id
        and ab.building = '2'
        and ab.attendance_c ='T'
        and ab.SCHOOL_YEAR =2014
        CONVERT(date,ab.attendance_date,102) = convert(date,getdate(),102)
        FOR XML PATH ('') ) AS PERIODS,
        r.GRADE
        FROM register r
    where r.CURRENT_STATUS = 'A'
    and r.BUILDING ='2'

I'm getting all the students at building 2 and even if they don't have an attedance_c of T; a NULL value for Periods is being retrieved:
Student ID | Building  | Period | Grade

12345          2        1 , 5    11
43210          2        1  ,     12
95687          2        NULL     09
78417          2        NULL     10
20357          2        NULL     11

I have tried  and ab.attendancePeriod is Not NULL and I still get the same results.
Any thoughts?

A: Move the AS PERIODS select to be an inner join to r.

A: The outer query doesn't listen to any filters in the subquery; it will return NULL for any rows that aren't matched by the join conditions. You need to filter differently. Here is one way (this also eliminates the errant trailing comma, and avoids comparing dates by converting them expensively to strings):
;WITH x AS
(
  SELECT DISTINCT s = r.Student_ID, r.building,
    p = ab.attendancePeriod, r.grade
  FROM dbo.Register AS r
  INNER JOIN dbo.att_bottom AS ab
  ON r.Student_ID = ab.Student_ID
  AND r.building = ab.building
  WHERE ab.building = '2'
  AND ab.attendance_c = 'T'
  AND ab.SCHOOL_YEAR = 2014
  AND ab.attendance_date >= CONVERT(DATE, GETDATE())
  AND ab.attendance_date < DATEADD(DAY, 1, CONVERT(DATE, GETDATE()))
  AND r.building = '2'
  AND r.CURRENT_STATUS = 'A'
)
SELECT DISTINCT
  [Student ID] = x.s,
  x.building,
  Period = STUFF((SELECT ',' + x2.p FROM x AS x2 WHERE x2.s = x.s
    FOR XML PATH(''),
    TYPE).value(N'./text()[]',N'nvarchar(max)'),1,1,''),
  x.grade
 FROM x;

Another way:
 SELECT DISTINCT
   r.Student_ID,
   r.building,
   Period = STUFF(b.p.value(N'./text()[1]', N'nvarchar(max)'),1,1,''),
   r.grade
 FROM dbo.Register AS r
 CROSS APPLY
 (
   SELECT p = ',' + ab.attendancePeriod
     FROM dbo.att_bottom AS ab
     WHERE ab.building = '2'
     AND ab.attendance_c = 'T'
     AND ab.SCHOOL_YEAR = 2014
     AND ab.attendance_date >= CONVERT(DATE, GETDATE())
     AND ab.attendance_date < DATEADD(DAY, 1, CONVERT(DATE, GETDATE()))
     AND ab.student_id = r.student_id
     AND ab.building = r.building
     FOR XML PATH(''),TYPE
 ) AS b(p)
 WHERE b.p IS NOT NULL
  AND r.building = '2'
  AND r.CURRENT_STATUS = 'A';


text:
Q: Jenkins email plugin configuration using groovy script throws an error I am trying to configure SMTP on jenkins using the email plugin and groovy script call.
Here is the script I am trying to use:
import jenkins.model.Jenkins

def inst = Jenkins.getInstance()
def emailExt = instance.getDescriptor(
  "hudson.plugins.emailext.ExtendedEmailPublisher")

emailExt.setSmtpAuth("username",
                     "password")
emailExt.setDefaultReplyTo("jenkins@example.com")
emailExt.setSmtpServer("smtp.example.com")
emailExt.setUseSsl(true)
emailExt.setSmtpPort("587")
emailExt.setCharset("utf-8")
emailExt.setDefaultRecipients("someone@example.com")

emailExt.save()

When I try to run it using the script console on jenkins, Here is the error I get:
Result
groovy.lang.MissingPropertyException: No such property: instance for class: Script1
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
    at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:307)
    at Script1.run(Script1.groovy:5)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:585)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:623)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:594)
    at hudson.util.RemotingDiagnostics$Script.call(RemotingDiagnostics.java:143)
    at hudson.util.RemotingDiagnostics$Script.call(RemotingDiagnostics.java:113)
    at hudson.remoting.LocalChannel.call(LocalChannel.java:46)
    at hudson.util.RemotingDiagnostics.executeGroovy(RemotingDiagnostics.java:110)
    at jenkins.model.Jenkins._doScript(Jenkins.java:4698)
    at jenkins.model.Jenkins.doScript(Jenkins.java:4669)
    at java.base/java.lang.invoke.MethodHandle.invokeWithArguments(MethodHandle.java:710)
    at org.kohsuke.stapler.Function$MethodFunction.invoke(Function.java:393)
    at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:405)
    at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:208)
    at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:141)
    at org.kohsuke.stapler.MetaClass$11.doDispatch(MetaClass.java:536)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:766)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:898)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:694)
    at org.kohsuke.stapler.Stapler.service(Stapler.java:240)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:799)
    at org.eclipse.jetty.servlet.ServletHandler$ChainEnd.doFilter(ServletHandler.java:1626)
    at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:156)

Any help is super appreciated!


text:
Q: How to get column in Laravel junction table I implemented Many-To-Many Eloquent relationship between products and properties by three table. (like this)
I can access product properties using the following code :
App\Product::find(1)->properties;

but how to get other column in junction table (such as "value" in this case)?
I have attached my database schema image here

A: Any column that is not a foreign key is not added by default in the relationship object. You need to specify the extra columns you want with withPivot.
# App\Product model
public function properties()
{
    return $this->belongsToMany(...)->withPivot('value');
}

To access the intermediate table, use pivot->
App\Product::find(1)->properties->pivot->value;


text:
Q: How to delete calendar events faster? Following code works and deletes all calendar events from iPhone calendar database.
But events are deleting very slow: 2 events per second on iPhone 3GS.
So if you have 3000 events - then it's 25 minutes to erase them...
How would you optimize this code? Maybe I am doing something wrong? Thanks.
- (void)deleteAllCalendarEventsFromIPhone:(NSError **)error {
    EKEventStore *store = [[EKEventStore alloc] init];

    NSUInteger beginYear = 1900;
    NSUInteger endYear = 2100;

    while (beginYear < endYear) {
        NSPredicate *predicate =
            [store predicateForEventsWithStartDate:[self createDateWithYear:beginYear month:1 day:1]
                                           endDate:[self createDateWithYear:beginYear + 4 month:1 day:1]
                                         calendars:nil];
        NSArray *eventList = [store eventsMatchingPredicate:predicate];
        for (EKEvent *event in eventList) {
            success = [store removeEvent:event span:EKSpanThisEvent error:nil];
        }
        beginYear += 4;
    }
    [store release];
}

A: iOS 5.0 has a new removeEvent: method that allows you not to commit changes until the very end. I haven't tested it yet, but that sounds to be exactly what you need here.

A: Maybe because it is not the usage of EKEventStore !
Removing all user event is quite dangerous ...

A: -(void)deleteElementFromCalendarDB {
    CFGregorianDate gregorianStartDate, gregorianEndDate;
    CFGregorianUnits startUnits = {-2, 0, 0, 0, 0, 0};
    CFGregorianUnits endUnits = {1, 0, 0, 0, 0, 0};
    CFTimeZoneRef timeZone = CFTimeZoneCopySystem();
    gregorianStartDate =  CFAbsoluteTimeGetGregorianDate(
        CFAbsoluteTimeAddGregorianUnits(CFAbsoluteTimeGetCurrent(),
        timeZone,startUnits),timeZone);
    gregorianStartDate.hour = 0;
    gregorianStartDate.minute = 0;
    gregorianStartDate.second = 0;
    gregorianEndDate = CFAbsoluteTimeGetGregorianDate(
        CFAbsoluteTimeAddGregorianUnits(CFAbsoluteTimeGetCurrent(),
        timeZone, endUnits),timeZone);
    gregorianEndDate.hour = 0;
    gregorianEndDate.minute = 0;
    gregorianEndDate.second = 0;
    NSDate* startDate = [NSDate dateWithTimeIntervalSinceReferenceDate:
    CFGregorianDateGetAbsoluteTime(gregorianStartDate, timeZone)];
    NSDate* endDate =   [NSDate dateWithTimeIntervalSinceReferenceDate:
    CFGregorianDateGetAbsoluteTime(gregorianEndDate, timeZone)];
    CFRelease(timeZone);
    NSError *err;
    NSPredicate *predicate = [self.eventStore predicateForEventsWithStartDate:startDate
        endDate:endDate
        calendars:nil];
    NSArray *eventListS = [self.eventStore eventsMatchingPredicate:predicate];
    for (EKEvent *event in eventListS) {
        [self.eventStore removeEvent:event span:EKSpanFutureEvents error:&err];
    }
    if (err == noErr) {
        UIAlertView *alert =[[UIAlertView alloc]itWithTitle:@"All Events were deleted"                                              message:@"How about that?"
            delegate:nil
            cancelButtonTitle:@"Okay"
            otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}


text:
Q: how to write and read .xlsb file in C# without using Excel Interop I have multiple .xlsb templates that have 5-6 sheets in them.
First, 2-3 sheets are where I need to add data dynamically so that the 4th and 5th sheets can generate data based on the macro/formulas written in them.
Can you guys help me out with what can be used for this?
What I have already tried?

*

*ExcelDataReader - But it did not work for xlsb consistently

*LinqToExcel - I could read the data from the custom templates by creating the models and fetch the related data through Linq

I am not finding anything that I use to write/export data to xlsb to specific sheets
Can anyone help me out here as I cannot convert the template to another format, it has to be xlsb.


text:
Q: How to convert the number of matrix to fraction not decimal in python? I have one matrix in python:
aa = np.array([[1, -2], [1, 1]])

Then, I want to compute the inverse of this matrix aa:
bb = inv(aa)
Finally, I got the result:
print("bb: ", bb)
array([[ 0.33333333,  0.66666667], [-0.33333333,  0.33333333]]))

But I want to print the results in fraction format, not decimal/float:
array([[ 1/3,  2/3], [-1/3,  1/3]]))

Here is my original codes:
import numpy as np
from numpy.linalg import inv
from fractions import Fraction

aa = np.array([[1, -2], [1, 1]])
bb = inv(aa)
print("bb: ", bb)

How can I get this print result by python?
array([[ 1/3,  2/3], [-1/3,  1/3]]))

A: you could use sympy:
from sympy import Matrix

aa = Matrix([[1, -2], [1, 1]])
bb = aa.inv()
print(bb)  # Matrix([[1/3, 2/3], [-1/3, 1/3]])


text:
Q: accessing viewController property from SceneDelegate - Swift - Programmatically I have a blurEffect in a camera ViewController that I use to blur the cameraView whenever I pass from a viewController to another.
I do that, animating the alpha value of it.
These are the blur effect variables:
var blur = UIBlurEffect(style: .dark)
var blurView = UIVisualEffectView()

I want that when the app enters in background or in foreground I can access the properties and change the alpha value.
This is what I did in SceneDelegate:
func sceneWillEnterForeground(_ scene: UIScene) {

    guard let cameraViewController = tabbarviewcontroller.viewControllers[1].viewControllers.first as? CameraViewController else{
        print("there is an error in retrieving the cameraController")
        return
    }

    UIView.animate(withDuration: 0.25, delay: 0.2, options: [.curveEaseOut,. allowUserInteraction], animations: {
        cameraViewController.blurView.alpha = 0
    })
}

func sceneDidEnterBackground(_ scene: UIScene) {

    guard let cameraViewController = tabbarviewcontroller.viewControllers[1].viewControllers.first as? CameraViewController else{
               print("there is an error in retrieving the cameraController")
               return
           }

    cameraViewController.blurView.alpha = 1

}

I can access the cameraViewController correctly but the blurView.alpha animation doesn't work, any suggestions on what could cause this problem?


text:
Q: How to push a table in another table by ascend sorting withput using sort or asort? what i want to do is that i want to rewrite te table in another table by sorting it
I TRIED THESE TWO WAY AND SO MANY WAY BUT IT SEEMS NOT WORKING , HOPE YOU GUYS CAN HELP
$data = [3, 4, 54, 7, 9, 34, 5, 6, 7, 3, 5];

$res1 = [];

for ($i = 0; $i < count($data); $i++) {

    for ($l = 0; $l < count($data); $l++) {
        if ($data[$l] < $data[$i]) {
            array_push($res1, $data[$l]);
            array_shift($data);
        }
    }

}

for ($s = 0; $s < count($res1); $s++) {
    echo $res1[$s] . ' / ';
}

A: Use PHP built-in sort function
<?php $arr = [8,7,17,3];
$sortedArr = sort($arr);
echo $sortedArr; ?>

There are a lot of variations of sort you can learn about them here


text:
Q: jQuery Fullscreen Overlay Effect only works once I'm coding a Fullscreen Overlay Effect by following Codrops recent tutorial. However, since I don't use the Modernizr-plugin, which the jQuery-script does, I tried removing it from the code. It works, but only once. When I close the overlay the button doesn't work anymore until I refresh the page.
You can see the example live at my clients website, which is currently in development - http://www.sk-inspection.com. Click the navigation point "Kontakt" to see it in action.
The jQuery I have:
(function() {
var triggerBttn = document.getElementById( 'trigger-overlay' ),
    overlay = document.querySelector( 'div.overlay' ),
    closeBttn = overlay.querySelector( 'button.overlay-close' );
    transEndEventNames = {
        'WebkitTransition': 'webkitTransitionEnd',
        'MozTransition': 'transitionend',
        'OTransition': 'oTransitionEnd',
        'msTransition': 'MSTransitionEnd',
        'transition': 'transitionend'
    }

function toggleOverlay() {
    if( classie.has( overlay, 'open' ) ) {
        classie.remove( overlay, 'open' );
        classie.add( overlay, 'close' );
        var onEndTransitionFn = function( ev ) {
            classie.remove( overlay, 'close' );
        };
    }
    else if( !classie.has( overlay, 'close' ) ) {
        classie.add( overlay, 'open' );
    }
}

triggerBttn.addEventListener( 'click', toggleOverlay );
closeBttn.addEventListener( 'click', toggleOverlay );
})();

The original jQuery from Codrops tutorial:
(function() {
var triggerBttn = document.getElementById( 'trigger-overlay' ),
    overlay = document.querySelector( 'div.overlay' ),
    closeBttn = overlay.querySelector( 'button.overlay-close' );
    transEndEventNames = {
        'WebkitTransition': 'webkitTransitionEnd',
        'MozTransition': 'transitionend',
        'OTransition': 'oTransitionEnd',
        'msTransition': 'MSTransitionEnd',
        'transition': 'transitionend'
    },
    transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ],
    support = { transitions : Modernizr.csstransitions };

function toggleOverlay() {
    if( classie.has( overlay, 'open' ) ) {
        classie.remove( overlay, 'open' );
        classie.add( overlay, 'close' );
        var onEndTransitionFn = function( ev ) {
            if( support.transitions ) {
                if( ev.propertyName !== 'visibility' ) return;
                this.removeEventListener( transEndEventName, onEndTransitionFn );
            }
            classie.remove( overlay, 'close' );
        };
        if( support.transitions ) {
            overlay.addEventListener( transEndEventName, onEndTransitionFn );
        }
        else {
            onEndTransitionFn();
        }
    }
    else if( !classie.has( overlay, 'close' ) ) {
        classie.add( overlay, 'open' );
    }
}

triggerBttn.addEventListener( 'click', toggleOverlay );
closeBttn.addEventListener( 'click', toggleOverlay );
})();

And finally Classie.js, which is a class helper function.
    /*!
 * classie - class helper functions
 * from bonzo https://github.com/ded/bonzo
 *
 * classie.has( elem, 'my-class' ) -> true/false
 * classie.add( elem, 'my-new-class' )
 * classie.remove( elem, 'my-unwanted-class' )
 * classie.toggle( elem, 'my-class' )
 */

/*jshint browser: true, strict: true, undef: true */
/*global define: false */

( function( window ) {

'use strict';

// class helper functions from bonzo https://github.com/ded/bonzo

function classReg( className ) {
  return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}

// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;

if ( 'classList' in document.documentElement ) {
  hasClass = function( elem, c ) {
    return elem.classList.contains( c );
  };
  addClass = function( elem, c ) {
    elem.classList.add( c );
  };
  removeClass = function( elem, c ) {
    elem.classList.remove( c );
  };
}
else {
  hasClass = function( elem, c ) {
    return classReg( c ).test( elem.className );
  };
  addClass = function( elem, c ) {
    if ( !hasClass( elem, c ) ) {
      elem.className = elem.className + ' ' + c;
    }
  };
  removeClass = function( elem, c ) {
    elem.className = elem.className.replace( classReg( c ), ' ' );
  };
}

function toggleClass( elem, c ) {
  var fn = hasClass( elem, c ) ? removeClass : addClass;
  fn( elem, c );
}

var classie = {
  // full names
  hasClass: hasClass,
  addClass: addClass,
  removeClass: removeClass,
  toggleClass: toggleClass,
  // short names
  has: hasClass,
  add: addClass,
  remove: removeClass,
  toggle: toggleClass
};

// transport
if ( typeof define === 'function' && define.amd ) {
  // AMD
  define( classie );
} else {
  // browser global
  window.classie = classie;
}

})( window );

A: I included Modernizer like used in the original example supplied by Codrops.


text:
Q: Pygame mainloop qiuting exception handling Hi I am writing a simple chess program, unfortunately I have run in some unexpected problems, namely. After I added a list which keeps track of all the figures positions, I cannot close the window using the method which I till now used. which was:
  for event in pygame.event.get():
    # print(event)
    # Checking if the user clicks the red quit cross
    if event.type == pygame.QUIT:
        # run control the mainloop, wheather True or not
        run = False

After adding the list, this stopped working, so I use now:
for event in pygame.event.get():
    # print(event)
    if event.type == pygame.QUIT:
        pygame.display.quit()
        pygame.quit()

I tried to add some exception handling:
try:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.display.quit()
except pygame.error():
    print('Program closed')

However the except statement is not reached and an error is printed: (pygame.error: video system not initialized)
Can You please tell me how to handle this exception properly, or suggest a different way of braking the mainloop.

A: remove the () from the exception catching, namely:
except pygame.error instead of except pygame.error()

A: I acctually figured it out on my own, so just in case someone is looking for the anwser. The issue was that I was trying to call the redraw function after pygame.display.quit(). Thus after moving both the redraw call and the keys = pygame.key.get_pressed() [wich also utilises the module pygame] the program terminates without any error call. The code should look as follows:
while run:
    pygame.time.delay(100)
    window_redrawing()

    # Gathering user keyboard input
    keys = pygame.key.get_pressed()

    # making sure the window can be closed
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.display.quit()
            run = False

    fig_pos.clear()


text:
Q: What is the story behind Chell? I completed Portal 2 three times, and now I know all the history, except Chell's history.
Can somebody tell me if there's a story behind Chell?

A: Players wake up as Chell, in Portal 1. The game is quite short, however, and there is not much in the way of character progression. Prior to these events, there is not much, in the way of back story.
Chell wakes up inside of a Relaxation Vault, inside the Aperture Science laboratory. She is informed that she is a test subject. Using the Portal Gun and the Advanced Knee Replacement, Chell completes the tests, with the promise of being rewarded cake for completing the exercise.
Instead of cake, GLaDOS attempts to dump Chell into an incinerator. Chell manages to escape, and goes on to defeat GLaDOS. Moments after her escape from the Aperture Science laboratory, Chell is captured, and taken back into the laboratory.
At this point, the Lab Rat comic takes over. Long story short, an escaped engineer by the name of Doug Rattman witnesses Chells escape and quick recapture. After realising Chell is to be put inside an Extended Relaxation Vault, which has lost its life support capabilities due to the explosion, Rattman patches Chell's vault into the reserved power grid.
As a result, Chell survives suspended animation, and wakes up to the events of Portal 2.
While there is not much backstory to Chell, prior to Portal 1, there is speculation that she is the daughter of an Aperture Science employees. This is hinted at in Portal 1, where GLaDOS remarks ""Well done, remember, the Aperture Science Bring Your Daughter to Work Day is the perfect time to have her tested.", and again in Portal 2, where a "Bring Your Daughter To Work Day" science-fair entry features a potato-generator experiment, signed by Chell.


text:
Q: WP Add Media Button - Can I set the default size to Original/Full Size So when I am adding pictures to a blog post [directly to the 'main content area', below the text], they have the 'Medium' Size.... so I have to go to every single picture and change it to Full Size .... is there a way to set Full Size as default.... so that I just need to hit Add Media and all the pictures would display in Full Size?
Cheers,
Peter

A: WordPress will remember the last size you used - just make sure to insert a large media once, and then it will be selected by default for every subsequent item.

A: You can set the default in the database. Go to the options table and look for "image_default_size". As value you put "full" (without ""; or thumbnail, medium or large). As I understand it, it will set the default for every user, not just you.


text:
Q: Can I set priority of transactional function of a Grails service? Is there a way to set the priority of a Grails service's functions? Specifically, I have a void transactional function that is very low priority, and I would like it to run only when no other functions require attention... is there a way to do this in Grails?
For example:
@Transactional
class SomeService {
    void nonUrgentFunction() {
    }
    Object functionThatNeedsToHappenFast() {
    }
}

The non-urgent function updates my database with a few objects that are useful for looking back and determining what has happened. But this function can wait. And it is also slow because it requires pessimistic locking, and can be called simultaneously by hundreds of devices hitting my web service.
The urgent function helps in the rendering of a response from my web service, which needs to be fast. If 100 devices are hitting my service concurrently, I need this function to take precedence...
Is there a way set priority for service functions in Grails?

A: Grails has no concept of a priority in a Service or Service method call. This falls outside the scope of the Grails framework core features.
However, there are many ways to accomplish this. All of which depend upon your specific requirements.
For instance, you could use a ThreadPoolExecutor and a PriorityBlockingQueue to implement your own means of giving priority to specific requests.
You could also use a JMS message broker and messages with various queues and listeners to distribute these requests and manage their priority based on the queue. This would allow you to scale the processing beyond a single JVM.
These are just two examples, there are many other ways to implement this.
While both of these approaches would enable you to accomplish what you are looking to do, they are vastly different when it comes to their implementation and overall capabilities. Ultimately your requirements are going to dictate what type of solution fits your needs.


text:
Q: Oracle null check for string field In this below example why other than "NAME1" all giving null as result in oracle 11g.
If I mention space explicitly it takes space otherwise null only not empty string.Please help me to clarify this.
In NAME2 I specify the empty space but still it gives null.
select
NVL(NAME,' ') AS NAME1,
NVL(NAME,'') AS NAME2,
NVL(NAME,NULL) AS NAME3,
NAME AS NAME4
from employee

OUTPUT :
(space),null,null,null

A: Because in Oracle a ZERO length varchar is treated as NULL.
In your example
NVL(NAME, ' ') AS NAME1 will evaluate to either NAME or ' ' - empty string.
NVL(NAME, '') as NAME2 will evaluate to either NAME or a zero length string

A: Because '' is equal with null in oracle. For example these two queries are same:
update  test set name=''  where id = 15
update  test set name=null   where id = 15

A: The reason is that in Oracle an empty string is equivalent to NULL.
You can see that this is true by executing the followig query
SELECT 'x' FROM DUAL WHERE '' IS NULL

This should return a single row, meaning that the condition '' IS NULL is true.


text:
Q: Migrating Windows CE 5.0 user account credentials during update How are the credentials stored on a Windows CE 5.0 device? The user accounts are stored in the registry at [HKLM\Comm\Security\UserAccounts]. While it was possible with Windows CE 3.0 to copy the accounts from one registry to another this does not work anymore with Windows CE 5.0. Instead one have to register the credentails with NTLMSetUserInfo on each device.
I need to save the credentials, upgrade to the next version of the Windows CE 5.0 platform and restore the credentials. Unfortunately they are not valid anymore. Is there another way to store and/or migrate the credentials? The platform GUID at [HKEY_LOCAL_MACHINE\Windows CE Tools] is unchanged.


text:
Q: getting the request object in connect router Hi i have a connect middleware which uses the connect router to handle request for methods like get,post etc.I want to throw error if a person chooses methods other than these two.I do not have scope for the request object inside the router function.Below is my code
var connectDomain = require('connect-domain'),
connectRoute = require('connect-route'),
connect = require('connect'),
app = connect();
app.use(connectDomain()) // For error handling
.use(connect.query())// To use automatic query
.use(connectRoute(function (router) {
    // To Handle Get request
    router.get('/aaa', function (req, res, next) {
        console.log ("Got Trigger request to GET");
    })
    // To Handle POST request
    router.post('/aaa', function (req, res, next) {

        console.log ("Got Trigger request to POST);

    })
}))

I have scope for the request object inside router.get and router.post.I need to check for the req.method before these and throw an error.I am unable to proceed further.Any help will be much helpful

A: You could use a middleware for that:

app.use(connectDomain())
.use(connect.query())
.use(function(req, res, next) {
  if (req.method !== 'GET' && req.method !== 'POST') {
    res.writeHead(405);
    res.end('You are not allowed to use this method!');
  } else {
    next();
  }
})
.use(connectRoute(function (router) {
   ...
}));


text:
Q: Understanding disk usage My Ubuntu server is installed on hard drive with very simple partitioning
/dev/sdd1   *           1        1824    14647296   83  Linux
/dev/sdd2            1824        3283    11718656   83  Linux
/dev/sdd3            3283        4864    12702720   82  Linux swap / Solaris

So about 14GB is allocated for / and about 12GB for /home. The rest is swap.
Today I noticed when I login I got a warning that running out of space. df shows the following
Filesystem            Size  Used Avail Use% Mounted on
/dev/sdd1              14G   13G  619M  96% /
none                  2.9G  260K  2.9G   1% /dev
none                  2.9G     0  2.9G   0% /dev/shm
none                  2.9G  852K  2.9G   1% /var/run
none                  2.9G     0  2.9G   0% /var/lock
none                  2.9G     0  2.9G   0% /lib/init/rw
/dev/sdd2              12G  2.6G  8.0G  25% /home

At this point I am trying to understand what eats 13G on my root partition. du shows the following output
$ sudo du -hxL --exclude="/home" --max-depth=1 / # excluding home because
                                                  it's other partition

0       /sys
4.0K    /selinux
4.0K    /mnt
447M    /lib
4.0K    /opt
1.9G    /usr
64M     /etc
447M    /lib64
31M     /boot
8.2M    /sbin
8.0K    /man
48K     /root
358M    /var
0       /proc
0       /dev
4.0K    /srv
16K     /lost+found
28K     /tmp
12M     /bin
3.2G    /

parted
Disk /dev/sdd: 40.0GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type     File system     Flags
 1      1049kB  15.0GB  15.0GB  primary  ext4            boot
 2      15.0GB  27.0GB  12.0GB  primary  ext4
 3      27.0GB  40.0GB  13.0GB  primary  linux-swap(v1)

The sum is far not 13G, in fact it's around 5G. So what exactly takes space on my root partition?

A: I bet if you umount /dev/sdd2, you will see another 12GB /home folder

A: Try the following in a terminal
$ sudo apt-get autoclean

OR Try to kill updatedb process
$ ps aux | grep updatedb

Note the PID.
$ kill PID


text:
Q: Paperclip and Heroku without s3? I'm trying to upload a file using paperclip in a production environment in Heroku and the log files show:
Errno::EACCES (Permission denied - /app/public/system/photos/1/small/081811-2012-honda-cbr1000rr-leaked-003.jpg):

Will I have to use s3 or similar to handle file uploads, or can I configure path permissions to store the files on Heroku?

A: Yes Heroku does not allows you to add files dynamically to its server.
Though if you need upload feature on a app on heroku you need to configure s3 or other similar services
Refer this for details
http://devcenter.heroku.com/articles/read-only-filesystem

A: Yes, you must use S3 or another persistent store like Rackspace cloudfiles, Dropbox etc.
Whilst you can write to the tmp on all the stacks, the Cedar stack does let you write to the file system but it's not shared across dynos or dyno stop/restarts.
See http://devcenter.heroku.com/articles/dyno-isolation#ephemeral_filesystem

A: Yeah, it is true that Heroku does not allow you to upload files directly onto their servers.  However, you can shove your files into your database. I used a gem created by Pat Shaughnessy:
http://patshaughnessy.net/2009/2/19/database-storage-for-paperclip
It worked well.


text:
Q: How to display top 10 based on total amount in SSRS 2012
I need to display only top 10  Class based on Total (SUM(Premium)) column.
I go to group ClassCode properties --> Filters and setting top 10 by SUM(NetWrittenPremium) but it doesnt work.
I need to display only top 10 and also the total amount should be for only those 10.
Cant understand how to achieve it.

here is my query:
;WITH cte_TopClasses
AS  (
SELECT

        c.YearNum,
        c.MonthNum,
        DD.ClassCode,
        ISNULL(SUM(prm.Premium),0) as NetWrittenPremium

FROM    tblCalendar c
LEFT JOIN  ProductionReportMetrics prm ON c.YearNum = YEAR(prm.EffectiveDate) and c.MonthNum = MONTH(prm.EffectiveDate)
           AND CompanyGUID = '18E04C99-D796-4CFA-B1E7-28328321C8AD'
LEFT JOIN [dbo].[Dynamic_Data_GLUnitedSpecialty] DD on prm.QuoteGUID = DD.QuoteGuid
WHERE   ( c.YearNum = YEAR(GETDATE())-1 and c.MonthNum >= MONTH(GETDATE())+1 ) OR
        ( c.YearNum = YEAR(GETDATE()) and c.MonthNum <= MONTH(GETDATE()) )
GROUP BY    c.YearNum,
            c.MonthNum,
            DD.ClassCode--,prm.Premium

    )
SELECT   ROW_NUMBER() OVER (PARTITION BY ClassCode ORDER BY NetWrittenPremium DESC),*
FROM cte_TopClasses

and my outcome from the query:

@Alan
Thanks.
Query output look like that:

If I add ClassCode in order by in dense_rank  then $142,000 is not gonna be in a query. Which is not good.
Any other ideas? Maybe I can use partition function?

A: In Group Properties add a sort and set
Sort by expression "=Sum(NetWrittenPremium)"
Order = "Z to A"

Them in the filter as follows:
Expression = "=Sum(NetWrittenPremium)"
Operator = Top N
Value = 10

Actually I've just noticed the Total row.... This will not calculate the total correctly and you cannot use aggregations in filters on the tablix (which would have worked otherwise).
You best bet would be to push this back to the server and do it there.
I can't test this on your data directly but it should work, I tested on someting similar...
SELECT r.* FROM
    (SELECT d.*
            , dense_rank() OVER(ORDER BY TotalNWP Desc) AS rnk
        FROM
            (SELECT DISTINCT
                ClassCode, YearNum, MonthNum
                , SUM(t.NetWrittenPremium) OVER (PARTITION BY ClassCode, YearNum, MonthNum) AS NetWrittenPremium
                , SUM(t.NetWrittenPremium) OVER (PARTITION BY ClassCode) AS TotalNWP
             FROM cte_TopClasses t
            ) d
    ) r
    WHERE rnk <=10

Now there should be no need to do any filtering in SSRS, just sorting by the rnk column.
You only remaining problem is how to determine which of the last results (which all have the same total) take precedent over the others. You could do something like adding ClassCode to the dense_rank function to the are chosen alphabetically but that;s for yo to decide I guess.


text:
Q: How to programmatically change label and font size I am building an RPN calculator in xCode v6.1.1, and am trying to modify the x register label size and font size, and be able to toggle between the x register label and the four x-y-z-t label registers.  I've tried this code and it works with one line but not both.
I've found that with both lines in the method, if I press the toggle button twice, the function will work.
self.xReg.frame = CGRectMake(188, 206, 385, 70);
[self.xReg setFont:[UIFont systemFontOfSize:70]];


text:
Q: How is caffe input_shape actually work? I'm confused about the followinng block in a caffe implemented prj of obj detection with Faster-RCNN in the begining of test.prototxt:
input: "data"
input_shape {
  dim: 1
  dim: 3
  dim: 224
  dim: 224
}

input: "im_info"
input_shape {
  dim: 1
  dim: 3
}

but actually the input is not the specified size of 224*224, and does not need to be 224*224, I see in the test code, images are just read with out resize and then pass through the network, very confused, and did not find reference of how caffe define these blocks, can someone help?

A: Turns out the input shape is not determined by the terms here:
input: "data"
input_shape {
  dim: 1
  dim: 3
  dim: 224
  dim: 224
}

input: "im_info"
input_shape {
  dim: 1
  dim: 3
}

after I change input dim to arbitrary size, like 424:
input: "data"
input_shape {
  dim: 1
  dim: 3
  dim: 424
  dim: 424
}

input: "im_info"
input_shape {
  dim: 1
  dim: 3
}

the test AP does not change a bit, indicates there is some modification done so that image size is not determined here by the input_shape in test.prototxt, then I dive into the code, found lines here:
net.blobs['data'].reshape(*(blobs['data'].shape))

before the :
forward_kwargs = {'data': blobs['data'].astype(np.float32, copy=False)}
if cfg.TEST.HAS_RPN:
    forward_kwargs['im_info'] = blobs['im_info'].astype(np.float32, copy=False)
else:
    forward_kwargs['rois'] = blobs['rois'].astype(np.float32, copy=False)
blobs_out = net.forward(**forward_kwargs)

and the blobs['data'].shape is the size of input image with resize process so that the width is 600:(I don't post all lines here)
im_scale = float(cfg.TEST.MAX_SIZE) / float(im_size_max)
im = cv2.resize(im_orig, None, None, fx=im_scale, fy=im_scale,
                        interpolation=cv2.INTER_LINEAR)