text:
Q: How to extract different metrics from source code in Enterprise Architect I have source code of a project (multiple files) that I have exported as source directory in the Enterprise Architect. I want to use the EA for the following.

*

*Extract different source code metrics such as LOC, Comments, No of classes etc.

*Extract function calls.

*Extract level of coupling between classes.

*Detect code smells.

However, I have been looking through different forums and documentation files for days and haven't found anything helpful.

A: Enterprise Architect doesn't have the functions you are looking for. It's basically not the right tool for that job.
You might be able to do something if you write a bunch of scripts, or an add-in. But in that case you would basically need to parse and interpret the code yourself.
What you are looking for is a static code analysis tool, not a modelling tool such as EA.

A: You can try JArchitect, it gives you all these metrics and features and it's free for open source contributors.


text:
Q: Inserting text with \cleardoublepage and memoir When I wrote my first template using book, I used the following macro to add text to blank pages:
\renewcommand{\cleardoublepage}{
  \clearpage\if@twoside \ifodd\c@page\else
  \hbox{}
  \vspace*{\fill}
  \begin{center}
    \textit{This page intentionally left blank}
  \end{center}
  \vspace*{\fill}
  \thispagestyle{empty}
  \newpage
  \if@twocolumn\hbox{}\newpage\fi\fi\fi
}

The same macro does not work under memoir, blank pages are not printed anymore. Even just copy-pasting the \cleardoublepage definition from the class' source (as opposed to the macro above) is enough to break it.
How can I port my macro to memoir?
Minimal (non-working) example:
\documentclass[a4paper,12pt,twoside,openright,final]{memoir}

\usepackage{fontspec}
\usepackage{microtype}

\usepackage{csquotes}
\usepackage{polyglossia}
\setdefaultlanguage{english}

\usepackage[backend=biber,style=authoryear,bibstyle=authoryear]{biblatex}
\addbibresource{references.bib}

\usepackage{lipsum}

\settrims{0pt}{0pt}
\setlrmarginsandblock{2.54cm}{2.54cm}{1.618}
\setulmarginsandblock{2.54cm}{2.54cm}{1.618}
\checkandfixthelayout

\title{StackExchange test}
\author{Amyspark}
\date{\today}

\renewcommand{\cleardoublepage}{
  \clearpage\if@twoside \ifodd\c@page\else
  \hbox{}
  \vspace*{\fill}
  \begin{center}
    \textit{This page intentionally left blank}
  \end{center}
  \vspace*{\fill}
  \thispagestyle{empty}
  \newpage
  \if@twocolumn\hbox{}\newpage\fi\fi\fi
}
\renewcommand{\cleartorecto}{\cleardoublepage}

\begin{document}
  \SingleSpacing
  \frontmatter

  \begin{titlingpage*}
    \maketitle
  \end{titlingpage*}
  \cleartorecto % the back side of the title page should be blank (but instead no page)

  \OnehalfSpacing
  \tableofcontents*
  \cleardoublepage % same as above

  \mainmatter
  \chapter{Test}
  \lipsum[1-6]

  \section{Objectives}
  \lipsum[7-8]

  \section{First section}
  \lipsum[2-3]
  \subsection{Sub}
  \lipsum[3]
  \subsubsection{Subsub}
  \lipsum[4]\Parencite[4]{Foley:2008:CGC:1481349} % or any suitable cite, just to generate bib

  \backmatter
  \printbibliography[heading=bibintoc] % this should go in a recto page (but it doesn't)
\end{document}

A: As explained in the manual, memoir includes commands \movetoevenpage, \cleartoevenpage, \movetooddpage and \cleartooddpage, each of which can take an optional argument which will be printed on the skipped page (if there is one). The \moveto... macros stop printing the current page and then continue typesetting on the next appropriate page; the \clearto... commands are similar except that they will flush any floats before continuing typesetting. For example:
\cleartooddpage[\vspace*{\fill}THIS PAGE LEFT BLANK\vspace*{\fill}]
will put THIS PAGE LEFT BLANK in the centre of any potential skipped (empty) even numbered page.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scala Dependency injection with generic class Using Guice in Scala, I'm trying to reproduce the following Java code.
Foo interface and class declaration:
public interface Foo[T] {}
public class FooImpl[T] implements Foo[T] {}

Guice binding code:
bind(Foo.class).to(FooImpl.class);

And one use example would be;
@Inject
public class Bar(Foo<String> foo) {}

In scala, my first bet was:
bind(classOf[Foo]).to(classOf[FooImpl])

But it's complaining about 'Type Foo takes type parameter'
How do I achieve this in scala?
Thank you

A: Your question has an error and thus it allows you for a wrong answer.
Let's first fix your concept idea. Having trait
trait Foo[T] { def hello: T }

works just fine. But then, the specific classes extending this trait will be, f.e.:
class FooImpl1 extends Foo[Int] { override def hello: Int = 42 }
class FooImpl2 extends Foo[String]{ override def hello: String = "test" }

And they could NOT be:
class FooImpl[Int] extends Foo[Int] { override def hello: Int = 42 }
class FooImpl[String] extends Foo[String]{ override def hello: String = "test" }

Because then, the Int or String is just the NAME for a generic parameter. It could be as well A and B, but you have just confused yourself.

Having this sorted out, you know know that you have FooImpl1 and FooImpl2.
They need different names because you can not have two classes named the same in the same scope!
And it is just fine. Because when you :
bind(classOf[X]).to(classOf[Y])

You are telling that whenever your class will call methods of the Interface or Trait X you want to provide the implementation of class Y.
You have to provide a class that you can instantiate! You could not instantiate a class with a generic parameter.
And, to finish, your proper binding would look like this:
bind(new TypeLiteral[Foo[Int]](){}).to(classOf[FooImpl1])
bind(new TypeLiteral[Foo[String]](){}).to(classOf[FooImpl2])


text:
Q: When can we inscribed sphere in tetrahedron? I'm wondering is there any conditions to do that. I believe propably there are but what ?

A: Given any tetrahedron with vertices $v_1,\ldots,v_4$. For $k = 1,\ldots 4$, let

*

*$h_k$ be the distance of $v_k$ to its opposite face.

*$\Delta_k$ be the area of the face opposite to $v_k$.

*$V$ and $\Delta = \sum_{k=1}^4 \Delta_k$ be the volume and surface area of the tetrahedron.

Consider following area weighted average of the vertices.
$$v = \frac{1}{\Delta}\sum_{k=1}^4 \Delta_k v_k$$
It is easy to see its distance to the face  opposite to vertex $v_k$ equals to
$$\frac1\Delta \Delta_k h_k = \frac{3V}{\Delta}$$
Since this is independent of $k$, this point $v$ is equal distance to all faces of the tetrahedron.
You can inscribe a sphere of radius $\frac{3V}{\Delta}$, centered at $v$ to the tetrahedron.

A: Here a "physical" proof that any tetrahedron has an inscribed sphere.
Let $\Delta$ be a tetrahedron.
Consider a vertex $v$ and the three planes containing the faces meeting at $v$. Consider the triangular infinite cone they form at $v$. Think of having it in a vertical position. Now put a unit sphere inside the cone. The sphere will fall until it touches the three faces.
Now consider the fourth face of $\Delta$, the one opposite to $v$, and consider the family of planes parallel to it. The higher planes won't touch the sphere, wile planes closer to the vertex will slice a circle on the sphere.
By continuity there is one of such plane $P$, which touches the sphere in one point (and having the sphere below $P$). It determines a tetrahedron where the unit sphere is inscribed. Since $P$ is parallel to the original face of $\Delta$, then the obtained tetrahedron is similar to $\Delta$. So by scaling you obtain a sphere inscribed in $\Delta$.


text:
Q: View related branches in issue On Github, if we go to a branch, and then look at the top right, we can links to related issues as in the screenshot below.
However, when I am in the issue, ie: https://github.com/Noitidart/The-My-App/issues/88. I don't see links to related branches. Is it possible to get this?

A: Blue label View 88 doesn't represent issue, it represents pull request.
For example, this branch on python-docs-samples has label 2091 which represents this pull request.


text:
Q: Converting a wire value in Verilog for further processing I'm new to Verilog.
I have written code to convert a wire value to an integer:
wire [31:0] w1;
integer k;
always @ (w1) k = w1;

Source: converting a wire value to an integer in verilog
Now, for the next part I get an ERROR!
wire [63:0] w2; // Suppose it contains some value
wire [63:0] w3;
assign w3[k-1:0] = w2[k-1:0]; // ERROR in this line

ERROR : k is not a constant.

How do I solve this issue?

A: Verilog requires that part selects (code like [msb:lsb] to select part of a vector) be constant. To access a variable-sized group of bits requires something more complicated. Here is one way to do it:
wire [63:0] src;
wire [6:0] k;

wire [127:0] mask = { { 64 { 1'b0 } }, { 64 { 1'b1 } } } << k;

wire [63:0] dest;

assign dest = mask[127:64] & src;

The technique here is to construct a vector of 64 zeros followed by 64 ones, shift that vector by a variable amount, and then use a portion of the vector as a qualifying mask to control which bits are transferred from src to dest.
A related concept which does not help in your example but which is worth being aware of: Verilog-2001 introduced the "indexed part-select". An indexed part select specifies a base index and a width. The width is required to be constant but the base index does not need to be constant. The syntax for an indexed part select is vec[base+:width] or vec[base-:width].

A: The part select operators in Verilog 2001 could be useful for what you want to achieve.
Basically verilog allows for the starting index to be variable but needs the width of the assignment to be constant. The "+:" operator indicates counting upwards from the index value and vice-versa for "-:".
You can do something like,
assign w3[k-1 -: 8 ] = w2[k-1 -: 8]; // Where 8 bits is copied downwards
Search for "+:" in the below document.
http://www.sutherland-hdl.com/papers/2001-Wescon-tutorial_using_Verilog-2001_part1.pdf
Word of caution, generally variable part selects is considered as bad verilog.


text:
Q: Why are Patience Kys and Kara Swole alive? I might be totally wrong, but:
Doesn't Kara Swole die in the last book of Ravenor?
Doesn't the same happen to Kys?
If the above are true, how are they alive again in Pariah?

A: Warning to those reading, this answer is almost entirely a spoiler of the last book of the Ravenor trilogy, as far as the characters Kara, Kys and Ravanor are concerned.
Both characters survive the events of the last book and are discussed in the epilogue.
kara is awaiting trial.

Kara, my dear Kara, remains under arrest. They are keeping her here,
  somewhere. Her hearing will follow mine and I hope by the Emporer's
  grace I will be there to testify for her. She doesn't deserve this.
- Page 888, Ravenor, the Omnibus, by Dan Abnett

Kys is in hiding, awaiting the outcome of Ravenor's trial:

And Kys. Kys haunts the dining houses of the hive, loitering quietly,
  waiting for me to be exonerated. I have no idea what she will do if
  the Inquisition demands my incarceration or death. I wish she would
  come and see me.
- Page 888, Ravenor, the Omnibus, by Dan Abnett


text:
Q: Using stackview for positioning I am new to swift development. In portrait mode I want to display two buttons in each row. Totally I have three rows. But in landscape mode I want to reposition the buttons three in one row. Where I will have two rows with three buttons each. To achieve this I have used stackview in storyboard. Using stackview horizontal, vertical axis I was able to achieve this in landscape mode (Displayed three buttons in single row). But I couldn't achieve it in portrait mode.
Storyboard View:

*

*In first stackview - contains two UIViews. First UIView will have button1, button2. Second UIView will have button3

*In second stackview - contains two UIViews. First UIView will have button4, button5. Second UIView will have button6.

With this existing project I am unable to size classes also. So is there any way to achieve for these buttons with equal spacing and alignment on both orientations?

A: With multi-tasking capabilities, you really need to think in terms of view size, not landscape or portrait orientations.
You'll need at least some code -- you won't be able to do this with Storyboard layout alone. Here is one approach:

*

*Use a "container" vertical stack view

*add 3 horizontal stack views

*in "Landscape" orientation (view is wider than tall)

*

*add 3 buttons to each of the first two horizontal stacks

*hide the 3rd horizontal stack

*in "Portrait" orientation (view is narrow)

*

*add two buttons to each of the 3 horizontal stacks

*show the 3rd horizontal stack

To update the layout on size change - device rotation or split-screen multi-tasking, implement
func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)

Here is a quick example:
class TwoThreeViewController: UIViewController {

    var buttons: [UIButton] = []

    let containerStack: UIStackView = {
        let v = UIStackView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.axis = .vertical
        v.spacing = 8
        v.distribution = .fill
        return v
    }()

    let statusLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        for _ in 1...3 {
            let v = UIStackView()
            v.axis = .horizontal
            v.distribution = .fillEqually
            v.spacing = 8
            containerStack.addArrangedSubview(v)
        }

        for i in 1...6 {
            let b = UIButton()
            b.translatesAutoresizingMaskIntoConstraints = false
            b.setTitle("Button \(i)", for: [])
            b.setTitleColor(.white, for: [])
            b.setTitleColor(.gray, for: .highlighted)
            b.backgroundColor = .red
            b.addTarget(self, action: #selector(self.btnTapped(_:)), for: .touchUpInside)
            buttons.append(b)
        }

        view.addSubview(containerStack)
        view.addSubview(statusLabel)

        // respect safe area
        let g = view.safeAreaLayoutGuide

        NSLayoutConstraint.activate([

            // constrain containingStack
            //  top / leading / trailing
            //  with 20-pts "padding"
            containerStack.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            containerStack.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            containerStack.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),

            // center the status label
            statusLabel.centerXAnchor.constraint(equalTo: g.centerXAnchor),
            statusLabel.centerYAnchor.constraint(equalTo: g.centerYAnchor),

        ])

        arrangeStacks(view.frame.size)

    }

    func arrangeStacks(_ size: CGSize) -> Void {

        // unwrap and make sure things were setup correctly
        guard let stk1 = containerStack.arrangedSubviews[0] as? UIStackView,
            let stk2 = containerStack.arrangedSubviews[1] as? UIStackView,
            let stk3 = containerStack.arrangedSubviews[2] as? UIStackView else {
                fatalError("Setup was not done correctly!")
        }

        // if wide (landscape)
        //  3 buttons in the first 2 horizontal stacks
        //  hide the 3rd horizontal stack

        // if narrow (portrait)
        //  2 buttons in each horizontal stack
        //  show the 3rd horizontal stack

        if size.width > size.height {

            buttons[0...2].forEach {
                stk1.addArrangedSubview($0)
            }
            buttons[3...5].forEach {
                stk2.addArrangedSubview($0)
            }
            stk3.isHidden = true

        } else {

            buttons[0...1].forEach {
                stk1.addArrangedSubview($0)
            }
            buttons[2...3].forEach {
                stk2.addArrangedSubview($0)
            }
            buttons[4...5].forEach {
                stk3.addArrangedSubview($0)
            }
            stk3.isHidden = false

        }

        statusLabel.text = size.width > size.height ? "Width > Height" : "Height > Width"

    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: { [unowned self] _ in
            self.arrangeStacks(size)
        }) { [unowned self] _ in
            // if you want to do something after size change
        }
    }

    @objc
    func btnTapped(_ sender: Any?) -> Void {
        guard let b = sender as? UIButton, let t = b.currentTitle else {
            return
        }
        print("Tapped: \(t)")
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let vc = UIAlertController(title: "Please Note", message: "This is Example Code only. It should not be considered \"Production Ready\"!", preferredStyle: .alert)
        vc.addAction(UIAlertAction(title: "OK", style: .default))
        present(vc, animated: true, completion: nil)
    }

}

The results:


text:
Q: Nodemon server with axios - Unable to Send I have a React app and within this app a folder called backend. This folder contains 2 files:

Config contains a variable with email and password through nodemailer.
Index.js (which is what my server is supposed to run) has this:
const path = require("path");
const express = require("express");
const transporter = require("./config");
const dotenv = require("dotenv");
dotenv.config();
const app = express();

const buildPath = path.join(__dirname, "..", "build");
app.use(express.json());
app.use(express.static(buildPath));

app.post("/send", (req, res) => {
  try {
    const mailOptions = {
      from: req.body.email, // sender address
      to: process.env.email, // list of receivers
      subject: req.body.subject, // Subject line
      html: `

You have a new contact request.

Contact Details

Name: ${req.body.name}

Email: ${req.body.email}

Subject: ${req.body.subject}

Message: ${req.body.message}

      `,
    };

    transporter.sendMail(mailOptions, function (err, info) {
      if (err) {
        res.status(500).send({
          success: false,
          message: "Something went wrong. Try again later",
        });
      } else {
        res.send({
          success: true,
          message: "Thanks for contacting us. We will get back to you shortly",
        });
      }
    });
  } catch (error) {
    res.status(500).send({
      success: false,
      message: "Something went wrong. Try again later",
    });
  }
});

app.listen(3030, () => {
  console.log("server start on port 3030");
});

Then, within a different folder (components) I have a component file that takes the form information and it's supposed to take it to the server:
import React, { useState } from "react";
import axios from "axios";
import { Form, Button } from "react-bootstrap";
import Navbar from "../components/Navbar";
import BottomNav from "../components/BottomNav";

const Contact = () => {
  const [state, setState] = useState({
    name: "",
    email: "",
    subject: "",
    message: "",
  });

  const [result, setResult] = useState(null);

  const sendEmail = event => {
    event.preventDefault();
    axios
      .post("/send", { ...state })
      .then(response => {
        setResult(response.data);
        setState({
          name: "",
          email: "",
          subject: "",
          message: "",
        });
      })
      .catch(() => {
        setResult({
          success: false,
          message: "Something went wrong. Try again later",
        });
      });
  };

  const onInputChange = event => {
    const { name, value } = event.target;

    setState({
      ...state,
      [name]: value,
    });
  };

  return (

      <Navbar />
      {result && (
        <p className={`${result.success ? "success" : "error"}`}>
          {result.message}

      )}
      <form
        className="phs-form-wrapper mt-8 h-screen flex flex-col items-center "
        onSubmit={sendEmail}
      >
        <Form.Group
          className=" phs-form-group flex flex-col items-center"
          controlId="name"
        >
          <Form.Label className="phs-form-label mr-2">Full Name</Form.Label>
          <Form.Control
            type="text"
            name="name"
            value={state.name}
            onChange={onInputChange}
          />
        </Form.Group>
        <Form.Group
          className=" phs-form-group flex flex-col items-center"
          controlId="email"
        >
          <Form.Label className="phs-form-label mr-2">Email</Form.Label>
          <Form.Control
            type="text"
            name="email"
            value={state.email}
            onChange={onInputChange}
          />
        </Form.Group>
        <Form.Group
          className=" phs-form-group flex flex-col items-center"
          controlId="subject"
        >
          <Form.Label className="phs-form-label mr-2">Subject</Form.Label>
          <Form.Control
            type="text"
            name="subject"
            value={state.subject}
            onChange={onInputChange}
          />
        </Form.Group>
        <Form.Group
          className=" phs-form-group flex flex-col items-center"
          controlId="subject"
        >
          <Form.Label className="phs-form-label mr-2">Message</Form.Label>
          <Form.Control
            as="textarea"
            name="message"
            value={state.message}
            rows="3"
            onChange={onInputChange}
          />
        </Form.Group>
        <Button
          className="phs-form-submit-button bg-black text-white p-4 mt-4"
          variant="primary"
          type="submit"
        >
          Submit
        </Button>
      </form>
      <BottomNav />

  );
};

export default Contact;

I am getting an error on both servers.
On localhost:3000 which is where I run my react app whenever I try to submit the info I get a:
VM635:1 POST http://localhost:3000/send 404 (Not Found)
On localhost:3030:
GET http://localhost:3030/ 404 (Not Found)
localhost/:1 Refused to load the image 'http://localhost:3030/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.

I note that my axios has a .post("/send") but I tried to change this to localhost:3030/send and doesn't work either.
Additionally I have 2 package.json files, one within my react folder (web) and another one within my backend folder.
The backend one has a script like this:
"scripts": {
    "dev": "nodemon src/index.js"
  }

The web one has a different script so I run a different server:
"scripts": {
    "start": "npm run watch:css && react-scripts start",
    "build": "npm run watch:css && react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "watch:css": "postcss src/assets/tailwind.css -o src/assets/main.css"
  }

Any ideas?

A: When you're running both the backend and frontend servers on different ports (:3000 and :3030 in this case), you need to particularly mention the whole url in axios call. In this case, /send is considered as http://localhost:3000 where the POST method doesn't exists (The reason why you're getting 404). You must make the following axios call:
const sendEmail = event => {
    event.preventDefault();
    axios
      .post("http://localhost:3030/send", state, {
        headers: {
         'Access-Control-Allow-Origin' : '*'
        },
      })
      .then(response => {
        ...
      })
      .catch(() => {
        ...
      });
  };

Also you don't need to spread the state in axios call. The reason is axios call accepts second argument as object.

A: On your react app try sending it to  "http://localhost:3030/send" instead "/send".
I believe its because your server URL and your react dev server URL are different when you run it locally


text:
Q: Durandal.js: change navigation options per area I want to have different navigation per "area" of my durandal application.  I've achieved this with ASP.NET MVC when using Areas by defining a Nav section in the layout page and having nested layout pages which implement the nav for each area.  The view structure in durandal is as follows:
http://i1346.photobucket.com/albums/p697/user2269352/viewstructure_zps5e21e724.gif
I'm using the ASP.NET MVC4 durandal template and I am guessing that I might need to change the following segement from shell.html

I suppose that ideally I'd like to have separate html pages that could be loaded into this section depending on which area / page I am viewing.

A: You can accomplish this by adding a settings object to your route info, and specifying the area name there.  With that in place, create a computed observable against the router's visibleRoutes collection that selects only the routes for the current area.
Not sure what your route configuration looks like, but an example of adding settings would be something like this:
var routes = [
    { url: 'one/page1', moduleId: 'viewmodels/one/page1', name: 'Page 1', visible: true, settings: {area: 'one'} },
    { url: 'two/page1', moduleId: 'viewmodels/two/page1', name: 'Page 1', visible: true, settings: {area: 'two'} }
];
router.map(routes);

In your view model where you are controlling the navigation html:
//filter the visible routes for the current area
viewModel.areaRoutes = ko.computed(function () {
    var area = this.area;
    return ko.utils.arrayFilter(router.visibleRoutes(), function (route) {
        return route.settings.area === area;
    });
}, viewModel);

A: Joseph Gabriel based solution works for me and playing with router.activeItem.settings.areSameItem I can set every route's group anywhere at my layout.
router.activeItem.settings.areSameItem = function (currentItem, newItem, activationData) {
    return currentItem == newItem; //replace this with your own code
};


text:
Q: Grothendieck and Non-commutative Geometry? When Grothendieck and his followers were working on their profound progress of algebraic geometry, did they ever consider non-commutative rings? Is there anyway evidence that Grothendieck foresaw the developments that would later come in non-commutative geometry or quantum group theory?

A: No and yes, depending on the level of understanding. The consideration of noncommutative rings telling about geometry is almost nonexistent in Grothendieck's published opus. One of the exceptions is that he considered cohomologies for the possibly noncommutative sheaves of $\mathcal{O}$-algebras for commutative $\mathcal{O}$ (the latter is used in Semiquantum geometry). On the other hand, Grothendieck has been pioneer on abandoning the points of spaces as primary objects and promoting the category of sheaves over the space as defining the space. This is the point of view of topos theory which he invented; he noticed that the topological properties do not depend on a site but only on the associated topos of sheaves, and proposed a topos as a natural generalization of a topological space. Manin took Grothendieck's advice that one should consider the topos of sheaves as replacing the space, together with Serre's theorem that the category of quasicoherent modules determines a projective variety, as a motivation to his approach to noncommutative geometry and quantum groups. The modern view of noncommutative geometry is that it is about the presentation of space via the structures consisting of all possible objects of some kind living on a space (algebra of functions, some structures consisting of cocycles, like category of vector bundles, category of sheaves, higher category of higher stacks).
In late 1960s W. Lawvere, with help from Tierney, extended the Grothendieck topoi to the theory of elementary topoi. This was not the only contribution of Lawvere in the 1960s. Lawvere promoted also the duality between spaces and dual objects which he calls quantity (cf. space and quantity). While Lawvere's impact has been deep, I object to the terminology: in physics a quantity is normally a single observable; physicist do not consider the algebra of all observables a quantity, but rather a field of quantities, or algebra of quantities. But never mind the terminology, Lawvere went on very deeply in presenting this point of view, which is really generalized noncommutative geometry. Of course, neither Grothendieck nor Lawvere did not pay that particular attention to reconstructing the differential geometry and measure theory from the study of operator algebras, what is the huge contribution of Connes, or from the study of noncommutative rings, which was implicit in Gabriel 1961 and more explicit with works of J. S. Golan, van Oystaeyen (and P. M. Cohn with his affine spectrum) and others in mid 1970s, working with spectra of noncommutative rings and noncommutative localization theory as a noncommutative analogue of Zariski topology. One should mention that sporadic appearance of operator algebras from the noncommutative geometry point of view is present to some extent in 1970s book of Semadeni on Banach spaces of continuous functions (MR296671), where he studies, among other topics, the noncommutative analogues of many topological properties of topological spaces; in less explicit form there are also works of Irving Segal which had a similar motivation.
Grothendieck says in his memoirs that the concept of abelian category as he promoted it in Tohoku is part of the same philosophy -- abelian categories, possibly with additional axioms like AB5 are sort of categories of sheaves of modules, and should be viewed as an idea which is sort of abelian/stable version of Grothendieck topoi. More precisely, in this line, there is a recent Nikolai Durov's concept of a vectoid. Pierre Gabriel, who was close to Grothendieck's school in his early days, had in his prophetic work of 1961 reconstruction theorem for schemes and study of subcategories and localizations in abelian categories which represent open or closed subschemes and so on. Gabriel's work is in fact the first big work in noncommutative algebraic geometry and his reconstruction theorem is really the basic motivation in algebraic flavour of the theorem. In a sense, Gabriel's work is an abelian version of some Grothendieck's basic ideas of topos theory (cf. noncommutative scheme for one of the modern ideas along that line of thought) and Grothendieck was well aware of the abelian direction of this thinking from the Tohoku times.
For a general vista, I recommend

*

*Pierre Cartier, A mad day's work: from Grothendieck to Connes and Kontsevich The evolution of concepts of space and symmetry, Bull. Amer. Math. Soc. 38 (2001), 389-408, pdf.


text:
Q: Flask socket io not emitting any data to React frontend I am trying to emulate realtime terminal logs that comes from backend using Flask Socket IO and ReactJS.
It shows socket id and the connected status but no data from "output" not showing in the console. Is there anyway to solve this issue?
Thanks in advance!
Here's my Flask implementation
from flask import Flask, request, Response, jsonify
from flask_socketio import SocketIO, emit
import subprocess

app = Flask(__name__)
app.config["SECRET KEY"] = "mykey"

socketio = SocketIO(app, cors_allowed_origins="*")

def shell_run():
    try:
        # cmd = "seq 1 20"
        cmd = "ping www.google.lk"

        process = subprocess.Popen(
            cmd,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True,
        )

        while True:
            next_line = process.stdout.readline()
            if next_line:
                print(next_line)
                indices = [49, 63]
                parts = [next_line[i:j] for i, j in zip(indices, indices[1:] + [None])]
                # print(parts[0])
                # socketio.emit("output", "parts[0])")
                socketio.emit("output", next_line)
                socketio.sleep(2)
            elif not process.poll():
                break

    except Exception as e:
        print(e)

@socketio.on("connect")
def frontend_connection():
    print("Client is Connected")
    emit("status", "Connection Established")
    shell_run()

if __name__ == "__main__":
    socketio.run(app, host='0.0.0.0', debug = True)

Here's my ReactJS implementation
import React, { Component } from "react";
import Terminal from "react-terminal-view";
import { io } from "socket.io-client";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      lines: ["Terminal Logs"],
    };
  }

  componentDidMount() {
    console.log("componentDidMount");

    const socket = io.connect('http://127.0.0.1:5000/cmd/');

    socket.on("status", (data) => {
      console.log("socket connected - " + socket.connected);
      console.log("socket id - " + socket.id);
      console.log(data);
    });

    socket.on("output", (data) => {
      console.log(data);
    });
  }

  render() {
    return (
      <div>
        <Terminal lines={this.state.lines} />
      </div>
    );
  }
}


text:
Q: loop through results looking for a string using python i have a csv and i'd like to find every occurrence of 'http://'. using the code below i get nothing. at this point, i'd like to know why i'm not getting any results at all (not even the 'hi' is bring printed). i'm a noob and it's just not making sense to me. explanations are welcome, links are fine but only if they help me understand...
import csv

with open('a_bunch_of_urls_and_other_stuff.csv', 'rb') as f:
    reader = csv.reader(f, delimiter=',')

    # remove results that dont have 'http://'
    for result in reader:
        # print result      # this prints everything from the cvs
        # print result[2]   # this prints out the column with urls

        if result[2] == 'http://':
           print 'hi'

A: I am assuming you trying to check if result[2] contains 'http://'.
You can try:
if "http://" in result[2]:
    print result[2]


text:
Q: Wrong Number of attributes while running Model.all Query I have created a model to log all the activities from an API,the model looks like this
 class ApiLogInfo < ActiveRecord::Base
     attr_accessible :description, :parameters, :user_id
     validates :description,:presence => true

    def self.logger(description, parameters = nil, user_id = nil)
            api_log_info = ApiLogInfo.new
            api_log_info.description = description
            api_log_info.parameters = parameters.to_s
            api_log_info.user_id = user_id
            api_log_info.save!
    end
  end

When I run ApiLogInfo.all from the console it throws me an error like this

I cannot figure out what is wrong in there.It would be really helpful if someone can help me on this.Thanks in advance.

A: Change the name of logger.
There is a default logger method will be called for log SQL in ActiveRecord.
See this http://apidock.com/rails/ActiveRecord/Base/logger/class


text:
Q: SQLite - Order and Compare I want to take some columns which have specific values and order them by remaining day.Here's what i tried :
Statement state = con.createStatement();
ResultSet rs = state.executeQuery("SELECT * FROM Table WHERE text1 LIKE '%"book"%' "
                                   +"AND text2 LIKE '%"pencil"%' "
                                   +"AND CAST(replace(price,'.','') AS INTEGER) > 100 "
                                   +"AND ORDER BY CAST(remainingDay AS INTEGER)");
return rs;

But this gives (near "ORDER": syntax error) error.


text:
Q: Issue trying to Scaffold-DbContext When I attempt to Scaffold-DbContext from MSSQL server I am able to connect just fine, but I'm getting an error about a foreign key in a table that was deleted from the database several weeks ago. The table it is seeing is called ServiceTicket, I have a similar table named ServiceTickets and I've ensured all the foreign keys are set appropriately.
Exact error I'm getting:
The foreign key {'ServiceTypeId'} cannot be added to the entity type 'ServiceTicket' because a foreign key on the same properties already exists on entity type 'ServiceTicket' and also targets the key {'ServiceTypeId'} on 'ServiceType'.

the table names we actually have in the db are ServiceTickets and ServiceType

Also I've already tried deleting and re-creating the relationship

A: After triple checking all the keys there was indeed a second key for the same relationship that was causing the issue.


text:
Q: External IP address doesn't change with VPN enabled My application start and automatically run a thread with this code that run every 5 seconds
string urlAddress = "http://icanhazip.com/";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream receiveStream = response.GetResponseStream();
                StreamReader readStream = null;

                if (String.IsNullOrWhiteSpace(response.CharacterSet))
                    readStream = new StreamReader(receiveStream);
                else
                    readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

                ip = readStream.ReadToEnd();

                response.Close();
                readStream.Close();
            }

After I run a vpn my ip is still the normal one, how can I get the new ip that was assigned by vpn? Are the request made by same ip, even after it was changed?


text:
Q: Capturing Screen from iPhone using QuickTime disables sounds on device I'm not able to play any sound on iPhone device after connecting it via lighting cable to Macbook Pro and enabling "Movie Recording" from this iPhone in QuickTime Player.
My goal is not to record movie just displaying on the screen what is going on iPhone but I with sound on device. After enabling screen capture session from iPhone to MacBook screen I can't hear any sound from my iPhone.
I can hear only audio when:
- I connect headset to iPhone then I can hear the sound in headphones.
- The sound is getting back after disabling capture screen session in QuickTime but this is not what I want because now I don't see iPhone screen on MacBook screen.
Am I doing something wrong?
My MacBook OSX: 10.11.6, iOS: 10.0.2

A: In order to record the sound from the mobile too, you have to enable the microphone
Make sure your phone is checked for both Camera and Microphone. If it crashes/ closes, do not worry. Launch the movie recording again. It should start recording both screen and sounds from your iPhone/ iPad.

A: You tried, true, but change cable then it works fine.
I think your cable is interrupted connection.


text:
Q: Extract data from ParametricPlot to a file I have a plot which is the output of a ParametricPlot command, and I want to save the data to a file, ideally with the columns x, y, parameter.
I'm aware of the methods in the answer to this question: Plot, extract data to a file, but I am having trouble adapting them to the parametric case - if I take only the first line of the Cases command, one coordinate seems to be missing, but taking all the lines, I have duplicate data, and I am not sure how the data are arranged.
Apologies if this is a stupid question, I am a Mathematica beginner.
EDIT 2: the simple, clean and robust solution posted by JimB in the comments solved my problem.  It was indeed a stupid question.
EDIT: I originally posted a MWE derived from my code, and the answers I got solved the MWE.  Unfortunately, my original code is still causing issues.  The original MWE is at the end of this question.
This code generates the plot:
Gamma = 0.5;
Beta = 1;
f[w_, T_] := Exp[(-T)*I*w]/(1 + Beta*I*w);
g[w_, T_] := Conjugate[1/f[w, T]] - Gamma*Exp[I*Arg[1/f[w, T]]];
h[w_, T_] := Conjugate[1/g[w, T]];
p = ParametricPlot[{Re[h[w, 1]], Im[h[w, 1]]}, {w, -Pi, 0},
   PlotRange -> {{-0.7, 2.1}, {0, 1.1}}]

This code extracts some of the data, but only the 3rd quadrant:
test1 = Cases[Normal[p], Line[pts_] :> pts, Infinity][[1]]

This code extracts all of the data, but out of order:
test2 = Reap[ParametricPlot[{Sow[{Re[h[w, 1]], Im[h[w, 1]]}]}, {w, -Pi, 0},
     PlotRange -> {{-0.7, 2.1}, {0, 1.1}}]];

This code gives an error about indices outside the range of the data:
pos = Append[Drop[Flatten[Position[p, Line]], -1], 1]
test3 = p[[Sequence @@ pos]]

Following is the original MWE
My codes is as follows:
k[w_] := Exp[(-I)*w]/(1 + I*w);
p = ParametricPlot[{Re[k[w]], Im[k[w]]}, {w, -Pi, 0},
    PlotRange -> {{-0.7, 2.1}, {0, 1.1}}];
data = Cases[Normal[p], Line[pts_] :> pts, Infinity];
Export["data.txt", data, "Table"]

My second attempt is to use the technique in the answer to this question: Extract data from a Parametric2D plot.  This is looking more hopeful, but the data is again in a weird order, I am not sure how to get it into a table.
data = Reap[
  ParametricPlot[{Sow[Re[k[w]]], Sow[Im[k[w]]]}, {w, -Pi,
    0}, PlotRange -> {{-0.7, 2.1}, {0, 1.1}}]]

A: In this case, I would do as follows.
Here is your plot:
k[w_] := Exp[(-I)*w]/(1 + I*w);
p = ParametricPlot[{Re[k[w]], Im[k[w]]}, {w, -Pi, 0},
  PlotRange -> {{-0.7, 2.1}, {0, 1.1}}];

This is the position of the line you are looking for in the form of a list:
Position[p, Line] // Flatten

(*  {1, 1, 1, 3, 1, 2, 0}  *)

One only needs to replace the figure 0 at the end of this list by 1 in order to point to the list staying under the Line, rather than the head Line:
pos = Append[Drop[Position[p, Line] // Flatten, -1], 1]

(*  {1, 1, 1, 3, 1, 2, 1}  *)

Now here is your data:
data = p[[Sequence @@ pos]]

You can export it in any form of your liking.
Have fun!
Edit:
In your edited case do the following:
pos1 = Append[Drop[Position[p, Line][[2]], -1], 1];
pos2 = Append[Drop[Position[p, Line][[3]], -1], 1];
data = Join[p[[Sequence @@ pos1]], p[[Sequence @@ pos2]]];

Let us check:
ListPlot[data]

yields

as expected.
Have fun!

A: You might consider just generating a table of points.  The downside is that the spacing of the points might not be as optimal as what you get with harvesting the points from ParametricPlot.
Using your example with 500 points:
k[w_] := Exp[(-I)*w]/(1 + I*w);
p = Table[{w, Re[k[w]], Im[k[w]]}, {w, -Pi, 0, Pi/500}];
p = Select[p, 0 <= #[[3]] <= 1.1 && -0.7 <= #[[2]] <= 2.1 &];
ListPlot[p[[All, {2, 3}]], Joined -> True]

You might have to play with the number of points as using just 50 points might not be adequate for the function of interest.  Here's what you get with your function and 50 points without connecting the points:
k[w_] := Exp[(-I)*w]/(1 + I*w);
p = Table[{w, Re[k[w]], Im[k[w]]}, {w, -Pi, 0, Pi/50}];
p = Select[p, 0 <= #[[3]] <= 1.1 && -0.7 <= #[[2]] <= 2.1 &];
ListPlot[p[[All, {2, 3}]], PlotStyle -> Red, PlotRangeClipping -> False]


text:
Q: Changing font name and size in HTML text area with ASP.net I have an empty div element and in which I am havin an HTMLtext area and now I have 2 drop down lists one is for font name and the other is for font size.
Now If I write something in the textarea and If I select some font name from the drop down list the text should immediately reflect within the textarea so how do I do that?
Here is my code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    For Each f As System.Drawing.FontFamily In System.Drawing.FontFamily.Families
        DropFont.Items.Add(f.Name)
    Next
End Sub

This is my design code:
<div class="exampe">
 <textarea name="TextBox1" rows="2" id="TextBox1" cols="20"></textarea>
</div>

  <asp:DropDownList ID="DropFontSize" runat="server">
                                    <asp:ListItem Value="6">6</asp:ListItem>
                                    <asp:ListItem Value="8">8</asp:ListItem>
                                    <asp:ListItem Value="10">10</asp:ListItem>
                                    <asp:ListItem Value="12">12</asp:ListItem>
                                    <asp:ListItem Value="14">14</asp:ListItem>
                                    <asp:ListItem Value="18">18</asp:ListItem>
                                    <asp:ListItem Value="24">24</asp:ListItem>
                                    <asp:ListItem Value="32">32</asp:ListItem>
                                    <asp:ListItem Value="36">36</asp:ListItem>
                                    <asp:ListItem Value="40">40</asp:ListItem>
                                    <asp:ListItem Value="48">48</asp:ListItem>
                                    <asp:ListItem Value="52">52</asp:ListItem>
                                    <asp:ListItem Value="56">56</asp:ListItem>
                                    <asp:ListItem Value="62">62</asp:ListItem>
                                    <asp:ListItem Value="68">68</asp:ListItem>
                                    <asp:ListItem Value="72">72</asp:ListItem>
                                </asp:DropDownList>

A: You are going to have to use a client side script to achieve what you want to do. Ideally I would suggest using jQuery to plug into the change event of your drop down list and based on the selecetion made either apply a css class to your textarea or use the css property of your textarea to change the font family.
In your header or stylesheet set:
<style>
   .arial {
       font-family: arial;
   }

   .verdana {
       font-family: verdana;
   }
</style>

For the following html:
<select id="fonts">
    <option value="arial">Arial</option>
    <option value="verdana">Verdana</option>
</select>

<textarea name="TextBox1" rows="2" id="TextBox1" cols="20"></textarea>

use this jQuery to change styles:
$('#fonts').change(function() {
    var fontfamily = $('#fonts').val();
    $('#TextBox1').removeClass();
    $('#TextBox1').addClass(fontfamily);
});

Alternatively, to avoid creating all the font classes, just use the css property:
$('.target').change(function() {
    var fontfamily = $('.target').val();
    $('#TextBox1').css('font-family', fontfamily);
});

One sticking point you may come across with asp.net is getting the drop down list id as this generated dynamically. You could use a class instead to identify it or use inline script to obtain it's client id propery within your javascript:
var ddlId = <%=DropFontSize.ClientID %>;
var fontfamily = $('#' + ddlId).val();

A: You should add the AutoPostBack to your textbox and as well as AutoPostBack to the dropdownlist.
By using SelectedIndexChanged Event of the dropdown you can match the text from text box and the value of dropdown list
Hope this helps

A: I have achieved in doing by this way
  <script type="text/javascript">
    $(document).ready(function () {
        $("#DropFont").change(
    function () {
        var fontname = $("#DropFont").val();
        $("#TextBox1").css("font-family", fontname);
    }
),

$("#DropFontSize").change(
    function () {
        var fontsize = $("#DropFontSize").val();
        $("#TextBox1").css("font-size", fontsize);
}
)
})
  </script>


text:
Q: Converting a decimal GPS time to UTC There's many similar questions out there but I haven't found one specific to the GPS output data I am receiving. The data from my GPS is in decimal form:
GPS Week: 2145 and GPS Time: 330374.741371   (the manual says this is a double that represents the "time of week in seconds")
I'm trying to convert this time into human readable UTC time. I'm using old C++14, not 20, so I can't just use the to_utc() function I don't think. I'm mostly confused about the decimal. On this website: https://www.labsat.co.uk/index.php/en/gps-time-calculator it looks like the data is "secondsOfTheWeek.secondsOfTheDay. I'm not sure how to convert this to UTC time...
I believe this output data is the number of seconds since the GPS epoch time of midnight, Jan. 6 1980. And I know it doesn't count leap seconds so that has to be taken into account too. If I had some guidance on how to start getting this into UTC time I think I could figure out the rest, but I'm not really sure where to start...
Eventually I want to convert the time into a string to set an OS system w that time using "date -s "16 AUG 2021 13:51:00" or something like that. But first I just need to convert this GPS time.

A: There exists a free, open-source preview to the C++20 chrono bits which works with C++14.
#include "date/tz.h"
#include <chrono>

date::utc_seconds
convert(int gps_week, double gps_time)
{
    using namespace date;
    using namespace std::chrono;

    int upper = static_cast<int>(gps_time);
    auto gps_t = gps_seconds{} + weeks(gps_week) + seconds{upper};
    return clock_cast<utc_clock>(gps_t);
}

This first forms a gps_time by adding the appropriate number of weeks to the gps epoch, and then the seconds.
Next you use clock_cast to transform this into utc_time (which does include leap seconds).
This can be used like so:
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std;

    cout << convert(2145, 330374.741371) << '\n';
}

Which outputs:
2021-02-17 19:45:56

The clock_cast changes the epoch from 1980-01-06 to 1970-01-01 and adds in the number of leap seconds that occur between the gps epoch and the utc time point.  If the gps input happens to correspond to a leap second, this will properly print "60" in the seconds field.  For example:
cout << convert(1851, 259216) << '\n';  // 2015-06-30 23:59:60

Some installation is required.
Further information
This Wikipedia article says that the time of week actually comes in units of 1.5 seconds, ranging in value from 0 to 403,199.
static_assert(403'200 * 1.5 == 7 * 24 * 60 * 60);

If one finds themself dealing with the data in this form, here is an alternate convert implementation which can deal with this input data directly:
using gps_tow = std::chrono::duration<int, std::ratio<3, 2>>;

auto
convert(date::weeks gps_week_num, gps_tow tow)
{
    using namespace date;
    return clock_cast<utc_clock>(gps_seconds{} + gps_week_num + tow);
}

The first step is to define a duration unit of 1.5 seconds.  This type is called gps_tow above.
The convert function now takes two strictly typed parameters:  a count of weeks, and a count of gps_tow.  Then one simply adds these parts together, along with the gps epoch, and clock_cast's it to utc_clock.
It can be used like so:
cout << convert(weeks{1851}, gps_tow{172811}) << '\n';

The output for this example is:
2015-06-30 23:59:60.5


text:
Q: How to port Javascript project to Coffeescript If I wanted to port an existing project from Javascript to Coffeescript (in my case, within a Rails application), would I need to convert existing Javascript files?  I'm worried about converting really large and CDN hosted files like jQuery and jQueryUI.  How would I work around that?

A: As @asawyer stated, you do not need to port existing JavaScript libraries and such to CoffeeScript.
CoffeeScript exists to add convenience for writing your own custom code. Because the CoffeeScript compiles into JavaScript, it plays nicely with other JavaScript libraries like jQuery without your needing to convert those libraries into CoffeeScript.
If you have your own code that you want to convert into CoffeeScript, I've found js2coffee.org very helpful. It also serves as a great learning tool for "thinking in JavaScript" and seeing how it would be done in CoffeeScript.

A: Within rails, coffeescript is run through a compiler and into javascript anyway.  You can include pure javascript files if you want (.js), or coffeescript (.js.coffee), which is compiled into js.  If you're just looking to include legacy files, you won't need to do any conversion at all -- Might not make sense to convert to coffeescript, just to have rails compiler convert back to javascript in the asset pipeline... See http://guides.rubyonrails.org/asset_pipeline.html#coding-links-to-assets for more from the rails team on how to use js in the asset pipeline.
jQuery is already included in newer versions of Rails (3.1 onward), so that shouldn't be an issue.  http://weblog.rubyonrails.org/2011/4/21/jquery-new-default/
Also, many other jQuery addons have a gem that you can simply include -- no need to reinvent the wheel there.


text:
Q: How to run executable (application/x-executable) I downloaded the linux version of this game and go a zip
inside the zip is a application/x-executable file which I can't run. ./filename does nothing as well as sh filename.
EDIT: I meant this game. the one above is already a bin
http://surger1.itch.io/chronoclysm

A: are you running a 64 bit platform of linux
as this is a 64 bit app?
i downloaded
chmoded the file
like so
chmod +x ToF_Beta2.065_linux64.bin

then i ran like this
./ToF_Beta2.065_linux64.bin

and it run perfect :)
but im 64 bit ubuntu
hope this helps

A: if you chmod it +x
you can also try
sh programname

A: It seems you are missing some corresponding libraries for the platform the game was compiled for. What distribution do you use? I'm asking because on Ubuntu 12.04 you could simply install the i386-libraries with
sudo apt-get install ia32-libs

On 14.04 LTS you have to do something like:
sudo -i
cd /etc/apt/sources.list.d
echo "deb http://old-releases.ubuntu.com/ubuntu/ raring main restricted universe multiverse" >ia32-libs-raring.list
apt-get update
apt-get install ia32-libs

Please note: The second example is only a dirty hack by forcing Trusty to use an older repository.


text:
Q: how to remove element in specified index without shiftingelements im using nsmutabltearray in my code base  and i want to remove an element within a specified index. i know that element will be shifted automatically.
but i want to stop this . elements shouldn't be shifted within the indexes.
ex - : arraylist in java
is thr any specied list tyoe in objc to do this
Thank you

A: I don't think this is possible with the default NS(Mutable)Array. Instead of removing, you could put [NSNull null] objects in there, but methods like count and objectAtIndex would still return the same values, so that may not be of much help either.

A: - (void)replaceObjectsAtIndexes:(NSIndexSet *)indexes withObjects:(NSArray *)objects

method can be used and put in a null object in the place of thte position where you want to remove the content


text:
Q: Do SQLDatabases get closed if an App crashes due to other unhanded Exceptions? After reading upon Database SQL best practices, i have extracted two try catches  into two separate methods. The only thing that I can think of which create a Database leak is if there is an external unhanded exception after doing getReadableDatabase(). So my question is, if an app crashes and restarts does the app clean itself up? For example help me closing this database session?  As you can see i don't fully quite understand what happens after an App crashes/ restarts.
  try {
            SQLiteDatabase database = helper.getReadableDatabase();
            doALongDatabaseTask(database);
            database.close();
        } catch (SQLException e){
            Log.w(Util.TAG, "getButtonPairsForSending db cannot be opened " + e);
        }

public void doALongDatabaseTask(SQLiteDatabase database){
 try
 {
   // Do long database query task
   } catch(Exception e) {

    }

}

A: In your example method doALongDatabaseTask(SQLiteDatabase database) the exception is handled, its just nothing is done with it, so in this case your database would call close()
However, if your method was defined to throw an exceptions
public void doALongDatabaseTask(SQLiteDatabase database) throws Exception{...}

then your call to close would be skipped, as it goes into the catch block in the first part of the example given.
Provided your using a high enough sdk version: If you look at the docs for SQLiteDatabase you can see that it implements the interface AutoCloseable.
This means that you can use a try with resources which looks like this
try(SQLiteDatabase database = helper.getReadableDatabase()){
    doALongDatabaseTask(database);
} catch (Exception e) {
    e.printstacktrace();
}

This is the equivalent of calling database.close() in a finally block (which you should be doing anyway) but much more readable. This then should in most cases clean up the connections when your app crashes and on a restart fresh connections can be obtained.


text:
Q: cloudant nosql db query with regex I have a cloudant nosql db with some records like this:
{
 "role": "utente",
 "nome": "Rocco",
 "cognome": "Di Vitto",
 "team": "sap pm-cs",
 "company": "wrestling",
 "appManager": "john Ford",
 "teamLeader": "Rendy Orton, Colombo M.R."
}

I would like to query my db with a $regex the teamLeader field, passing a single string that matches either with "Randy Orton" or "Colombo M.R." but I can't figure out the regex for matching two comma-delimited strings. I've tried reading Erlang queries structure but I didn't find the solution. Some help would be very useful. thanks in advance

A: when supplying regular expressions you should be using the $regex operator. have you tried something like this:
{
   "selector": {
      "teamLeader": {
         "$regex": "(Colombo M.R.)|(Rendy Orton)"
      }
   }
}


text:
Q: Python - How to access Instance variables? I recently stumbled upon a problem, How do i access a class's instance variables (aka the variables inside __init__) from outside/inside the file without creating an instance of a class (i.e main = main.foo()).
Example:
class foo:
       def __init__(self,name):
           self.name = name
class bar:
    os.mkdir(foo.name)

A: you can set the variable as global, and then you will be able to access this variable from everywhere. and also modifying it.
Not sure why you are using nested classes, but:
foo_name = None
class main:
    class foo:
       def __init__(self,name):
           global foo_name
           foo_name = self.name = name
    class bar:
       def __init__(self):
           print(foo_name)

main.foo("Jonathan")
main.bar()

Prints out "Jonathan"


text:
Q: How to two SELECT queries as a single table with one table having an aggregate column I have two different SQL queries and they are generating below results.
SELECT dbo.HomeUnit.unit_id
     , dbo.HomeUnit.type_id
     , dbo.UnitType.[type]
     , HomeUnit.unitqty
FROM dbo.HomeUnit
    INNER JOIN dbo.UnitType ON dbo.HomeUnit.type_id = dbo.UnitType.type_id
WHERE home_id='H2L54'

This delivers a result like below
unit_id | type_id | type         | unitqty
UG4LG   |  UTUEP  | Driver's Bed |    6
UQTK6   |  UTFX5  | Normal Unit  |   14
UQTJ6   |  UTFG5  | Normal Unit  |   12

This is the second query:
SELECT unit_id
     , home_id
     , SUM(numberofunits) as totalunitsbooked
FROM View_Reservation_With_Unit
WHERE home_id = 'H2L54'
    AND reservation_status='1'
    AND (NOT (fromdate > '2017-09-25' OR todate < '2017-09-26'))
GROUP BY home_id, unit_id

Output of above query gets me this
unit_id | home_id | totalunitsbooked
U3CFF   |  H2L54  |  5
UFRXJ   |  H2L54  |  1

My question is: How can I put the column "totalunitsbooked" in the first result set as an column, and assigning 0 if there's no units are booked.

A: This should work:
SELECT h.unit_id
     , h.type_id
     , u.[type]
     , h.unitqty
     , SUM(ISNULL(v.reservation_status,0)) as totalunitsbooked
FROM dbo.HomeUnit h
    INNER JOIN dbo.UnitType u ON h.type_id = u.type_id
    LEFT JOIN View_Reservation_With_Unit v ON v.unit_id = h.unit_id
        AND v.reservation_status = '1' AND (NOT (fromdate > '2017-09-25' OR todate < '2017-09-26'))
WHERE home_id='H2L54'
GROUP BY h.unit_id, h.type_id, u.[type], h.unitqty

What I did was to include your second query as a LEFT JOIN (or else all units not in the view wouldn't get displayed) and then made use of the ISNULL function to simply display 0 for all units that are not booked.
The aliases are just for readability.

A: I've not tested this, but the quick and easy way of doing this is a join on the second query:
SELECT dbo.HomeUnit.unit_id
     , dbo.HomeUnit.type_id
     , dbo.UnitType.[type]
     , HomeUnit.unitqty
FROM dbo.HomeUnit
    INNER JOIN dbo.UnitType ON dbo.HomeUnit.type_id = dbo.UnitType.type_id
    LEFT JOIN (
        SELECT unit_id
             , home_id
             , SUM(numberofunits) as totalunitsbooked
        FROM View_Reservation_With_Unit
        WHERE home_id = 'H2L54'
            AND reservation_status='1'
            AND (NOT (fromdate > '2017-09-25' OR todate < '2017-09-26')
    )
    ON dbo.HomeUnit.unit_id = unit_id
GROUP BY home_id, unit_id)
WHERE home_id='H2L54'

It would probably be more efficient to join them properly and have the group-by outside the "subquery" (like the other answer!)


text:
Q: carousel bootstrap 4 somente no modo mobile Dada a imagem a baixo que representa o modo desktop, gostaria de saber como faz para virar um carousel somente no modo mobile.

!--- Team ----->

Meet our team

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

A: Fiz esse modelo com apenas algumas linhas de CSS. A ideia é deixar o "componente" do time estático apenas em telas grandes, e em telas pequena eu dou um display:none nele enquanto dou um display:block no Slider. Logo com essa opção vc tem dois "componentes" ok.
Veja o Exemplo funcionando: (quando a tela for menor que 790px ele vai mostrar o Slider, mas se for maior ele mostra a lista estática.) Clique em "Página toda" para o slider sumir e ele ficar estático.

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name=
 content=
>
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous" />
    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

Meet our team

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                    CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                    CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                    CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                    CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe 2

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

John Doe 3

                CEO and Founder

Lorem Ipsum passages, and more recently with desktop publishing software

          Previous

          Next

OBS1: para controlar a largura de tela onde o Slider aparece configure aqui
@media (max-width: 790px) { /* largura que vc quer que apareça */
    .carousel {
        display: block;
        text-align: center;
    }
    etc.....
}

OBS2: Aqui vc controla a velocidade do Slider
$('.carousel').carousel({
    interval: 500 /* quanto maior o número mais devagar a transição */
})


text:
Q: Extract SOAP/XML namespaces as a list of key/value pairs using JavaScript Here's a SOAP response that I want to use javascript to extract a list of key value pairs where the key is the local namespace element prefix, such as:
SOAP-ENVns98ns70
and the value is the namespace definition, such as:
http://schemas.xmlsoap.org/soap/envelope/urn:vertexinc:enterprise:platform:security:messages:1:0urn:vertexinc:enterprise:platform:security:1:0
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
     <ns98:ExecuteLoginResponse
        xmlns:ns70="urn:vertexinc:enterprise:platform:security:1:0"
        xmlns:ns98="urn:vertexinc:enterprise:platform:security:messages:1:0">
        <ns70:UserLoginConfirmation>
            <ns70:UserName>platformadmin</ns70:UserName>
            <ns70:LoginResult>SUCCESS</ns70:LoginResult>
            <ns70:LastLoginDate>2016-01-26T17:28:02.109</ns70:LastLoginDate>
            <ns70:DefaultAsOfDate>2016-01-26</ns70:DefaultAsOfDate>
            <ns70:ForcePasswordChange>false</ns70:ForcePasswordChange>
        </ns70:UserLoginConfirmation>
    </ns98:ExecuteLoginResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

My research thus far indicates a general lack of need to do something like this, most people either strip the name space from the elements of the part of the document that they care about, or they simply ignore the namespace. At the moment I am stripping the namespace values, but for debugging purposes would like to inspect the namespaces that were used in the response.
An interesting aspect of the service being used is that the nsXX values can vary for each invocation (e.g. ns70 could be ns78 next time the method is invoked). This means that I cannot key on a fixed namespace value. Additionally, the namespace values for these messages in the WSDL don't seem to have any correspondence to the namespace values in the response.
XPath seems like it might be able to help here, or I could just write my own, but I'd prefer to leverage an existing approach. At this point I'm just trying to understand the problem space and would appreciate some guidance with regard to where to start my education process. (please point me in the right direction)

A: The approach I took was to fork angular-soap and add the ability to build a list of response namespaces as the XML response is converted into an object tree:
SOAPClient._node2object = function (node, wsdlTypes, namespaces) {
    var namespaceURI = node.namespaceURI;
    var prefix = node.prefix;

    if ('undefined' != typeof namespaceURI) {
        namespaces[prefix] = namespaceURI;
    }

    ...
}

To get the list of namespaces a namespaces object must be passed to the $soap.post() method, as follows.
    var namespaces = new Object();
...
    $soap.post(webserviceurl, "SomeWebservice", parameters, namespaces).then(function (response) {
...
    }

The alteration to the angular-soap code required modification of all functions between the $soap.post(url, action, parameters, namespaces) method and SOAPClient._node2object(node, wsdlTypes, namespaces) function to propagate the namespaces parameter.
http://www.w3schools.com/xml/dom_element.asp


text:
Q: "Tracing" a tkinter listbox I'm having a bit of trouble with tracing listbox changes in tkinter. I've managed to trace widgets that have variables associated to them, like scales, but that doesn't work with listboxes.
I've tried associating StringVar to it, but that doesn't work since you can't give a "variable=" argument to a Listbox widget. I've also tried the "command=" argument but it doesn't seem to work either.
This is my primary trouble, though it's not a vital function for my program. I have tried to implement this without the tracing, and thus calling the function I would call with trace after I change the Listbox, but I can't access the widget that is defined inside another class than the one I'm working in.
Here is the code:
class GUI:
    def __init__(self, master):
       ...
       GUI.NetworkLayout = Listbox(master, exportselection=False)
       GUI.NetworkLayout.insert(END, "Ellipse", "Random", "Form 3", "Form 4")
       GUI.NetworkLayout.select_set(0)
       GUI.NetworkLayout.grid(row=2, column=0, padx=5, pady=5)
       ...
class NetworkFrame:
    def __init__(self,master):
       ...
       def update_canvas(*args):
        """
        Redraws the shapes child to the canvas as follows:
            - Adapts them to match the node size slider.
            - Adapts them to match the bond width slider.
            - Adapts them to match the number of people.
        """
        pts = points(720, 320, GUI.NetworkLayout.get())
        NetworkFrame.DisplayFrame.delete("all")

        for i in range(GUI.number_of_people_var.get()-1):
            Link(NetworkFrame.DisplayFrame, pts, i)

        for i in range(GUI.number_of_people_var.get()):
            person_id = Person(NetworkFrame.DisplayFrame, pts, i)
            if i % 2 == 0:
                Person.change_color(person_id, GUI.hex_rumor)
            else:
                pass

As you can see, I try to access the GUI.NetworkLayout object by writing GUI.NetworkLayout, however I get this error when trying to execute the program-
AttributeError: type object 'GUI' has no attribute 'NetworkLayout'

Thank you


text:
Q: using temporary files vs pipes advantages and disadvantages Say I have a file named jobs.csv and I would like to get the top 50k jobs done by Foo
I can either do:
# cat jobs.csv | sort -u | head -n 50000 > /tmp/jobs.csv
# cat /tmp/jobs.csv | while read line; do Foo --job=$line; done

Or
# cat jobs.csv | sort -u | head -n 50000 | while read line; do Foo --job=$line; done

Can one tell which one is better in terms of system's IO/Memory efficiency?
Or even better, can one come up with a better solution for this?

A: I normally go for the second option (pipes all the way) unless one of the intermediate outputs is useful to me for another task. For example, if after running Foo against 50k jobs, you then wanted to run Bar against the same jobs, it would be useful to have /tmp/jobs.csv available.
Using pipes all the way gives the system the ability to forget about data at the earliest possible time, so it is a more efficient use of memory. It also bypasses the VFS and tmpfs stacks and so it uses marginally less CPU. The overall performance of the chain is faster as well because you don't need to wait for one step to finish before starting the next step (except if the particular program requires it).
By the way, in your example the biggest user of memory would be the sort stage because it needs to keep the entire contents of jobs.csv in memory in order to sort it. You can make it more efficient by improving whatever creates jobs.csv in the first place so that you no longer need the sort -u.


text:
Q: 'ref' not working like I think it should I have the following code which when looking at it while it's running shows that the initial 'myInt' and 'myFloat' do not change their values until the method call returns back.  Shouldn't their values change each time they are altered within the called methods since they are passed as 'ref' each time?
class Tester
{
    public void Run()
    {
        int myInt = 42;
        float myFloat = 9.685f;
        Console.WriteLine("Before starting: \n value of myInt: {0} \n value of myFloat: {1}", myInt, myFloat);
        // pass the variables by reference
        Multiply( ref myInt, ref myFloat );
        Console.WriteLine("After finishing: \n value of myInt: {0} \n value of myFloat: {1}", myInt, myFloat);
     }
     private static void Multiply (ref int theInt, ref float theFloat)
     {
        theInt = theInt * 2;
        theFloat = theFloat *2;
        Divide( ref theInt, ref theFloat);
     }
     private static void Divide (ref int theInt, ref float theFloat)
     {
        theInt = theInt / 3;
        theFloat = theFloat / 3;
        Add(ref theInt, ref theFloat);
     }
     public static void Add(ref int theInt, ref float theFloat)
     {
        theInt = theInt + theInt;
        theFloat = theFloat + theFloat;
     }
     static void Main()
     {
        Tester t = new Tester();
        t.Run();
     }
}

A: EDIT: Okay, having seen the description in your comments...
If you put a breakpoint in (say) Add then your watch variables won't change unless you get them to be re-evaluated - which has to be done in the right stack from. When the breakpoint has been hit, go to the Call Stack view, double click on the "Run" method (which doesn't change where you've got to, just which stack frame you're looking at) and you'll see the values update.

A: It's a debugger anomaly, the values change right away, as per Jon's and jamietre's comments.

A: You placed a Watch on the expressions myInt and myFloat rather than the expressions theInt and theFloat, thus you no longer see their values. myInt and myFloat do not exist in the current scope.

You can back up in the call stack to observe their values, or place a watch on all four of the expressions you care about.


text:
Q: Creating very large sprite sheets for video I've been working with the video/canvas capabilities of the new browsers I haven't been impressed.
I was thinking I could get better results making large sprites containing each frame of my videos. I want full screen video, so I guess I would have to scale the images, or canvas accordingly.
Of course, to limit the http requests I want a very limited number of sheets. But, that also means they will be extremely large. Let's say 1280x720.
Is it insane to use that large of sheets?
Are there any automated scripts that will make these sheets since they will be frames of rows and columns?
Lastly, I'm finding compressed video of better quality than compressed images of equivalent size. Why is that? Is it possible to yield similar results with images or is Photoshop's save for web not as good?
Thanks

A: At it's most basic, video compression works by taking keyframes every so often and then storing frames between keyframes as the change between it and the last frame. That means if things don't move between frames they are not stored again. This cuts down the file size significantly. There are other things done, but that's the simplest. This means that no matter how good the compression on a set of individual frames, as long as there is some similarity between the frames the video compression will always achieve a better result.
As a question, why can you not just use the HTML5 video tag?


text:
Q: Python JSON decoding error TypeError: can't use a string pattern on a bytes-like object Hi there i am coding in python trying to make a user friendly currency exchange app for a school project but have encountered and error with trying to decode json for the exchange rates.
The code i'm using is:
import urllib.request
import json
(str) = "http://rate-exchange.appspot.com/currency?from=FRM&to=TO&q=AM";
(str) = (str.replace("FRM", "GBP"))
(str) = (str.replace("TO", "USD"))
url = (str.replace("AM", "20"))
f = urllib.request.urlopen(url)
data = (f.read(100))
print (data)
json_input = data
decoded = json.loads(json_input)
print ("conversion is: ", decoded["v"])

and the error that i am getting is:
b'{"to": "USD", "rate": 1.66215, "from": "GBP", "v": 33.243000000000002}'
Traceback (most recent call last):
File "C:\Users\jay\My Cubby\get qure.py", line 12, in <module>
decoded = json.loads(json_input)
File "C:\Python33\lib\json\__init__.py", line 309, in loads
return _default_decoder.decode(s)
File "C:\Python33\lib\json\decoder.py", line 352, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: can't use a string pattern on a bytes-like object

So i was just wondering if anyone had any ideas of how to fix this error? Or if anyone has seen this error before?
Thanks in advance for any help
J.Rymer

A: In Python 3, you need to decode the bytes return value from urllib.request.urlopen() to a unicode string:
decoded = json.loads(json_input.decode('utf8'))

This makes the assumption that the web service you are using is using the default JSON encoding of UTF-8.
You could check the response for a character set if you don't want to assume:
f = urllib.request.urlopen(url)
charset = f.info().get_param('charset', 'utf8')
data = f.read()
decoded = json.loads(data.decode(charset))


text:
Q: How do I switch Bootswatch themes in Meteor? I am building an app for the first time using Meteor. Due to an accessibility issue, we would like to offer two different Bootswatch themes to the users.  I found a very useful explanation of how to switch Bootswatch themes here:
How to dynamically change themes after clicking a drop down menu of themes
(which references a handy fiddle in the accepted answer:  http://jsfiddle.net/82AsF/)
I have tried placing the provided javascript inside myapp.html in the <head> tag.  I also tried placing it inside the myapp.js file. (Then I tried placing in many assorted places just to see what would happen ;-) )
Nothing I have tried is working and it seems that it is the Meteor framework that is, understandably, "getting in the way".  Is there an approach that will work for switching Bootswatch themes in a Meteor app?

A: Dynamically switching bootswatch themes is easily done as demonstrated in the originally referenced question:  How to dynamically change themes after clicking a drop down menu of themes
Meteor (plus iron-router in my case) complicates this a little through the event maps and the simple fact that the dynamic change is occurring in the <head>.
Another answered question explains how to handle an event in jQuery directly (bypassing Meteor event maps):  How to handle custom jQuery events in Meteor?
The code snippet below shows how I put the two ideas together.  It's all working as expected.
var themes = {
  "default": "bootstrap311/css/bootstrap.default.min.css",
  "readable" : "bootstrap311/css/bootstrap.readable.min.css",
  "slate" : "bootstrap311/css/bootstrap.slate.min.css"
}

$(function(){
  var themesheet = $('<link href="'+themes['default']+'" rel="stylesheet" />');
  themesheet.appendTo('head');
  $('body').on('click', '.theme-link', function (e) {
    var themeurl = themes[$(this).attr('data-theme')];
    themesheet.attr('href',themeurl);
  });
});


text:
Q: Python logger exception to file I use logging. The logger writes to file only. (and not to standard output.) In some cases logger raises exception from inside a logger method.
My goal is say to logger not to write anything on to standard out/err, in case of any error at all. All internal exception should be handled internally, and should be written into the log file.

Details:
My logger raised charmap error. This particular issue has been solved based on this thread.
But I afraid of that in a specific case, other exception can occur (file IO error, etc), on the field, which is very frustrating, that the logger fails, while the system works. I want to ensure that the logger don't print anything on standard out/err at all.

My expected behavior is something like this:
try:
    logger.debug('Some error maker')
except:
    try:
        logger.debug('Error during log')
    except:
        pass

Just, of course, I don't want to write try-except around all of my logger statement.
Is there anything similar feature in the logger? Something quiet mode?

A: What about a function like this?
def my_logger(thing_to_log):
    try:
        logger.debug(thing_to_log)
    except Exception:
        try:
            logger.debug('Error during log')
        except Exception:
            pass

In the rest of the code you'll only need:
my_logger(thing_to_log)

A: To improve over @mdgm answer you can use the built-in features of logging to log stack trace and details of the exception:
def my_logger(thing_to_log):
    try:
        logger.debug(thing_to_log)
    except Exception:
        try:
            logger.debug('Error during log', exc_info=True, stack_info=True)
        except Exception:
            pass


text:
Q: MapBox not working with huge amount of Data | Javascript I tried to parse a 10Mb CSV file using papa parse, which contains data about longitude and latitude.
I used the step function to plot these points on MapBox.
fileInput = async e => {
        const file = e.target.files[0];
            Papa.parse(file,
                {
                    download: true,
                    worker: true,
                    header: true,
                    step: function (row) {
                        let from_lat = parseFloat(row.data.from_lat);
                        let from_long = parseFloat(row.data.from_long);
                        let to_lat = parseFloat(row.data.to_lat);
                        let to_long = parseFloat(row.data.to_long);
                        if ( (!(Number.isNaN(from_lat))) && (!(Number.isNaN(from_long)))  ) {
                        new mapboxgl.Marker()
                        .setLngLat([from_lat,from_long])
                        .addTo(map);
                        }
                        if ( (!(Number.isNaN(to_lat))) && (!(Number.isNaN(to_long)))  ) {
                        new mapboxgl.Marker()
                        .setLngLat([to_lat,to_long])
                        .addTo(map);
                        }
                    },
                });
    }

If I reduce the size of data in CSV, MapBox works fine but when I used the 10Mb CSV, No points were plotted on MapBox and the browser(Chrome) crashed.


text:
Q: preferredStatusBarHidden in custom cell and object class Since setStatusBarHidden is deprecated, we will be using preferredStatusBarHidden in UIViewControllers. But, how do I hide and show easily in a object class or custom UITableviewCell class. We used to hide show using UIApplication like this
[[UIApplication sharedApplication] setStatusBarHidden:YES];

Now it is deprecated and it can be used only in UIViewControllers, is there a way to hide them in custom tableview cells and NSObject classes?

A: prefersStatusBarHidden is a method of UIViewController objects, not UIApplication. So you should set it on UIViewController. Like this.
- (BOOL)prefersStatusBarHidden {

   return NO;
}

Note:

*

*If you change the return value for this method, call the setNeedsStatusBarAppearanceUpdate method.

*For childViewController, To specify that a child view controller should control preferred status bar hidden/unhidden state, implement the childViewControllerForStatusBarHidden method.

if you want to more dynamically hide or show the status bar
You can apply logic like this,
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { shouldHideStatusBar = (shouldHideStatusBar)? NO: YES; [self setNeedsStatusBarAppearanceUpdate]; }

You can add this code to your button event as well
make sure to add to your info.plist "View controller-based status bar appearance" set to YES otherwise things just don't seem to work.

A: Basically all you need is a Base VC that you will be subclassing in the VC's you want to control the status bar.
In there you will be subscribing for a given Notification, which when sent will control the status bar of the VC.
Here is the code:
extension Notification.Name {
    static var statusBarShowHide: Notification.Name {
        return .init(rawValue: "StatusBar.showHide")
    }
}

class StatusBarControllableVC : UIViewController {

    private var statusBarHidden = false

    private func topViewController() -> UIViewController? {
        var topController = UIApplication.shared.keyWindow?.rootViewController
        while topController?.presentedViewController != nil {
            topController = topController?.presentedViewController
        }
        return topController
    }

    override var prefersStatusBarHidden: Bool {
        return statusBarHidden
    }

    @objc func statusBarShowHide(notification: NSNotification) {
        guard let userInfo = notification.userInfo else {return}
        let topController = topViewController()

        if let hidden = userInfo["hidden"] as? Bool, self == topController {
            statusBarHidden = hidden
            self.setNeedsStatusBarAppearanceUpdate()
        }
    }

    override func viewDidLoad() {
        NotificationCenter.default.addObserver(self, selector: #selector(statusBarShowHide(notification:)), name: .statusBarShowHide, object: nil)
        super.viewDidLoad()
    }
}

Now whenever you need to show or hide the Status Bar, you will post a Notification like this:
NotificationCenter.default.post(name: .statusBarShowHide, object: nil, userInfo: ["hidden":true])

I believe this is the simplest approach.
In the code above I'm only showing/hiding the Status Bar on the Top Most View Controller, but obviously you can change that


text:
Q: In SSRS, how can I add a row to aggregate all the rows that don't match a filter? I'm working on a report that shows transactions grouped by type.
  Type    Total income
 ------- --------------
  A                575
  B                244
  C                128
  D                 45
  E                  5
  F                  3
  Total           1000

I only want to provide details for transaction types that represent more than 10% of the total income (i.e. A-C). I'm able to do this by applying a filter to the group:
  Type    Total income
 ------- --------------
  A                575
  B                244
  C                128
  Total           1000

What I want to display is a single row just above the total row that has a total for all the types that have been filtered out (i.e. the sum of D-F):
  Type    Total income
 ------- --------------
  A                575
  B                244
  C                128
  Other             53
  Total           1000

Is this even possible? I've tried using running totals and conditionally hidden rows within the group. I've tried Iif inside Sum. Nothing quite seems to do what I need and I'm butting up against scope issues (e.g. "the value expression has a nested aggregate that specifies a dataset scope").
If anyone can give me any pointers, I'd be really grateful.

EDIT: Should have specified, but at present the dataset actually returns individual transactions:
  ID   Type   Amount
 ---- ------ --------
   1   A           4
   2   A           2
   3   B           6
   4   A           5
   5   B           5

The grouping is done using a row group in the tablix.

A: One solution is to solve that in the SQL source of your dataset instead of inside SSRS:
SELECT
  CASE
    WHEN CAST([Total income] AS FLOAT) / SUM([Total income]) OVER (PARTITION BY 1) >= 0.10  THEN [Type]
    ELSE 'Other'
  END AS [Type]
  , [Total income]
FROM Source_Table

See also SQL Fiddle

A: Try to solve this in SQL, see SQL Fiddle.
SELECT I.*
,(
  CASE
    WHEN I.TotalIncome >= (SELECT Sum(I2.TotalIncome) / 10 FROM Income I2) THEN 10
    ELSE 1
  END
) AS TotalIncomePercent

FROM Income I

After this, create two sum groups.

*

*SUM(TotalIncome * TotalIncomePercent) / 10

*SUM(TotalIncome * TotalIncomePercent)

Second approach may be to use calculated column in SSRS. Try to create a calculated column with above case expression. If it allows you to create it, you may use it in the same way as SQL approach.

A: 1) To show income greater than 10% use row visibility condition like
=iif(reportitems!total_income.value/10<= I.totalincome,true,false)
here reportitems!total_income.value is total of all income  textbox value which will be total value of detail group.
 and I.totalincome is current field value.
2)add one more row to outside of detail group to achieve other income and use expression as
  = reportitems!total_income.value-sum(iif(reportitems!total_income.value/10<= I.totalincome,I.totalincome,nothing))


text:
Q: How to fetch records from another database using postgres_fdw in postgresql My case I have connected to another GP DB to import data into my PostgreSQL tables and written Java schedulers to refresh it Daily. But when I'm trying to fetch the records everyday by using SQL functions, it's giving me an error Greenplum Database does not support REPEATABLE READ transactions. So, Can anyone suggest me how can I load the data in frequent from GP to postgres without isolation hassle.
I knew to execute to refresh the tables by
START TRANSACTION ISOLATION LEVEL SERIALIZABLE;

But, I'm not able to use the same in the functions due to transactions blocks.

A: Unlike Oracle database, which uses locks and latches for concurrency control, Greenplum Database (as does PostgreSQL) maintains data consistency by using a multiversion model (Multiversion Concurrency Control, MVCC). This means that while querying a database, each transaction sees a snapshot of data which protects the transaction from viewing inconsistent data that could be caused by (other) concurrent updates on the same data rows. This provides transaction isolation for each database session. In a nutshell, readers don't block writers and writers don't block readers. Each transaction sees a snapshot of the database rather than locking tables.
Transaction Isolation Levels
The SQL standard defines four transaction isolation levels. In Greenplum Database, you can request any of the four standard transaction isolation levels. But internally, there are only two distinct isolation levels — read committed and serializable:

*

*read committed — When a transaction runs on this isolation level, a SELECT query sees only data committed before the query began. It never sees either uncommitted data or changes committed during query execution by concurrent transactions. However, the SELECT does see the effects of previous updates executed within its own transaction, even though they are not yet committed. In effect, a SELECT query sees a snapshot of the database as of the instant that query begins to run. Notice that two successive SELECT commands can see different data, even though they are within a single transaction, if other transactions commit changes during execution of the first SELECT. UPDATE and DELETE commands behave the same as SELECT in terms of searching for target rows. They will only find target rows that were committed as of the command start time. However, such a target row may have already been updated (or deleted or locked) by another concurrent transaction by the time it is found. The partial transaction isolation provided by read committed mode is adequate for many applications, and this mode is fast and simple to use. However, for applications that do complex queries and updates, it may be necessary to guarantee a more rigorously consistent view of the database than the read committed mode provides.

*serializable — This is the strictest transaction isolation. This level emulates serial transaction execution, as if transactions had been executed one after another, serially, rather than concurrently. Applications using this level must be prepared to retry transactions due to serialization failures. When a transaction is on the serializable level, a SELECT query sees only data committed before the transaction began. It never sees either uncommitted data or changes committed during transaction execution by concurrent transactions. However, the SELECT does see the effects of previous updates executed within its own transaction, even though they are not yet committed. Successive SELECT commands within a single transaction always see the same data. UPDATE and DELETE commands behave the same as SELECT in terms of searching for target rows. They will only find target rows that were committed as of the transaction start time. However, such a target row may have already been updated (or deleted or locked) by another concurrent transaction by the time it is found. In this case, the serializable transaction will wait for the first updating transaction to commit or roll back (if it is still in progress). If the first updater rolls back, then its effects are negated and the serializable transaction can proceed with updating the originally found row. But if the first updater commits (and actually updated or deleted the row, not just locked it) then the serializable transaction will be rolled back.

*read uncommitted — Treated the same as read committed in Greenplum Database.

*repeatable read — Treated the same as serializable in Greenplum Database.
The default transaction isolation level in Greenplum Database is read committed. To change the isolation level for a transaction, you can declare the isolation level when you BEGIN the transaction, or else use the SET TRANSACTION command after the transaction is started.
enter link description here


text:
Q: Can't create handler inside thread Thread[create_react_context,5,main] that has not called Looper.prepare() How do I really call a handler inside a method in React-Native Java Module ? I am trying to use Handler in React native Java Module but it is throwing error as
The printData is calling from React-native through its NativeModule.
Seems the Native bridge is working perfectly but only getting the error when including the Handler
Here is my module Class  `
package com.mosabeeapp;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.printer.sdk.PrinterConstants;
import com.printer.sdk.PrinterInstance;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.io.File;

public class CalendarModule extends ReactContextBaseJavaModule {
    public PrinterInstance myPrinter;

    private String devicesName;
    private String devicesAddress;
    private Integer baudrate;
    private Boolean isConnected;

    private Handler mHandler = new Handler() {
        @SuppressLint("ShowToast")
        @Override
        public void handleMessage(Message msg) {

            System.out.println("@@@@@@@@@@@@" + msg.what);
            switch (msg.what) {
                case PrinterConstants.Connect.SUCCESS:
                    isConnected = true;
                    System.out.println("isConnected status:::;" + isConnected);
                    break;
                case PrinterConstants.Connect.FAILED:
                    isConnected = false;
                    System.out.println("Connection failed");
                    break;
                case PrinterConstants.Connect.CLOSED:
                    isConnected = false;
                    System.out.println("Connection closed");
                    break;
                case PrinterConstants.Connect.NODEVICE:
                    System.out.println("There is no device");
                    isConnected = false;
                    break;
                case 0:
                    System.out.println("0");
                    break;
                case -1:
                    System.out.println("-1");

                    break;
                case -2:
                    System.out.println("-2");

                    break;
                case -3:
                    System.out.println("-3");

                    break;
                default:
                    break;
            }
        }
    };

    CalendarModule(ReactApplicationContext context) {
       super(context);
   }

    @Override
    public String getName() {
    return "CalendarModule";
    }

    @ReactMethod
    public void printData(String data) {

        System.out.println("----------buttonPrint--------");
        devicesName = "Serial device";
        devicesAddress = "/dev/ttyMT2";
        String com_baudrate = "115200";
        baudrate = Integer.parseInt(com_baudrate);

        myPrinter = PrinterInstance.getPrinterInstance(new File(devicesAddress), baudrate,0,8, mHandler);

        System.out.println("myPrinter.getCurrentStatus()-" + myPrinter.getCurrentStatus());
        boolean b = myPrinter.openConnection();
        System.out.println("-----------" + b);
        if (b && myPrinter != null) {
            System.out.println("Printer is ready");
        } else {
            System.out.println("Can not made a connection to the device");
        }

    }
}

`


text:
Q: extracting variables from an array JSON, Xcode im very new to this XCODE objective C, browse through the forum cant get what i need. im trying to extract a specific value from an array. im using teleduino, web service, just incase you know about it. so ermm.. im not sure why im not getting the output for this value "328-0.6.9" as shown in the figure attached. i dont need the other data just that one data.
Output from xcode

2015-03-20 01:17:19.987 APItest[1686:56954] Succeeded! Received 100 bytes of data
2015-03-20 01:17:19.988 APItest[1686:56954] key: status
2015-03-20 01:17:19.988 APItest[1686:56954] value: 200
2015-03-20 01:17:19.989 APItest[1686:56954] key: message
2015-03-20 01:17:19.989 APItest[1686:56954] value: OK
2015-03-20 01:17:19.989 APItest[1686:56954] key: response
2015-03-20 01:17:19.990 APItest[1686:56954] value: {
    result = 1;
    time = "0.57582592964172";
    values =     (
        "328-0.6.9"
    );

my code

    // convert to JSON
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];

    // show all values
    for(id key in res) {

        id values = [res objectForKey:key];

        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)values;

       NSLog(@"key: %@", keyAsString);
        NSLog(@"value: %@", valueAsString);
    }

     //extract specific value...
    NSArray *value = [res objectForKey:@""];

    for (NSDictionary *values in value) {
        NSString *icon = [values objectForKey:@"icon"];
        NSLog(@"icon: %@", icon);
        }

A: Looking at your logs, values is an array of strings. Please try following:
//extract specific value...
NSArray * values = [res objectForKey:@"values"];

for (NSString *value in values) {

    NSLog(@"icon: %@", value);
}