How to reload UITableView header using Swift

Question: I have a question about my code.
I want to change the view in my UITableView header when I click my button.
But I don't know how to reset the header view.
And I also don't how to remove previous header view and set new header view.
I want to switch the header view when I click the button.
Have any idea to me?
Thanks.

I have tried to write an example code.
And how to change the header view in the function "btnClicked".
enum ChartType {
    case triangle
    case circle
}

class ViewController: UIViewController {

    let tableView: UITableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()

        let sectionHeader: UIView = creatChartView()
        sectionHeader.backgroundColor = .white
        tableView.tableHeaderView = sectionHeader

        tableView.dataSource = self
        tableView.delegate = self
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 50

        view.addSubview(tableView)

        tableView.snp.makeConstraints { (make) in
            make.top.left.right.bottom.equalToSuperview()
        }
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        if let headerView = tableView.tableHeaderView {

            let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
            var headerFrame = headerView.frame

            //Comparison necessary to avoid infinite loop
            if height != headerFrame.size.height {
                headerFrame.size.height = height
                headerView.frame = headerFrame
                tableView.tableHeaderView = headerView
            }
        }
    }

    func creatChartView(type: ChartType = .circle) -> UIView {

        let view = UIView()

        switch type {
        case .circle:

            let titleLabel: UILabel = { () -> UILabel in
                let ui = UILabel()
                ui.text = "circle"
                ui.textAlignment = .center
                return ui
            }()

            let button: UIButton = { () -> UIButton in
                let ui = UIButton()
                ui.setTitle("Switch type", for: .normal)
                ui.addTarget(self, action: #selector(btnClicked), for: .touchUpInside)
                ui.setTitleColor(.red, for: .normal)
                return ui
            }()

            let circleView = UIView()

            let circlePath = UIBezierPath(arcCenter: CGPoint(x: UIScreen.main.bounds.size.width/2,y: 0), radius: CGFloat(20), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)
            let shapeLayer = CAShapeLayer()
            shapeLayer.path = circlePath.cgPath
            shapeLayer.fillColor = UIColor.clear.cgColor
            shapeLayer.strokeColor = UIColor.red.cgColor
            shapeLayer.lineWidth = 3.0
            circleView.layer.addSublayer(shapeLayer)

            view.addSubview(titleLabel)
            view.addSubview(button)
            view.addSubview(circleView)

            titleLabel.snp.makeConstraints { (make) in
                make.top.left.equalTo(15)
            }

            button.snp.makeConstraints { (make) in
                make.right.equalTo(-15)
                make.width.equalTo(titleLabel.snp.width)
                make.height.equalTo(titleLabel.snp.height)
            }

            circleView.snp.makeConstraints { (make) in
                make.top.equalTo(titleLabel.snp.bottom)
                make.left.right.bottom.equalToSuperview()
                make.height.equalTo(50)
            }

            return view

        case .triangle:

            let titleLabel: UILabel = { () -> UILabel in
                let ui = UILabel()
                ui.text = "triangle"
                ui.textAlignment = .center
                return ui
            }()

            let triangleView = UIView()

            let triangle = TriangleView(frame: CGRect(x: 10, y: 20, width: 25 , height: 30))
            triangle.backgroundColor = .red
            triangleView.addSubview(triangle)

            view.addSubview(titleLabel)
            view.addSubview(triangleView)

            titleLabel.snp.makeConstraints { (make) in
                make.top.left.equalTo(15)
                make.right.equalTo(-15)
                make.height.equalTo(20)
            }

            triangleView.snp.makeConstraints { (make) in
                make.top.equalTo(titleLabel.snp.bottom).offset(5)
                make.left.right.bottom.equalToSuperview()
            }

            return view
        }
    }

    @objc func btnClicked(sender: UIButton) {
        //How to refresh the headerView
    }
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = UITableViewCell()
        cell.textLabel?.text = "Hello \(indexPath.row)"

        return cell
    }

}

class TriangleView : UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func draw(_ rect: CGRect) {

        guard let context = UIGraphicsGetCurrentContext() else { return }

        context.beginPath()
        context.move(to: CGPoint(x: rect.minX, y: rect.maxY))
        context.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
        context.addLine(to: CGPoint(x: (rect.maxX / 2.0), y: rect.minY))
        context.closePath()

        context.setFillColor(red: 1.0, green: 0.5, blue: 0.0, alpha: 0.60)
        context.fillPath()
    }
}

Comment: `tableView.reloadData()`  have you tried this function ?
Answer: First of all you need a flag to check out what headerView you are currently on.
And within this flag you can use the property observer didSet to reload tableView  whenever this flag changes, something like this
var isNewHeaderView = false {
        didSet {
            tableView.reloadData()
        }
    }

Now inside the delegate method viewForHeaderInSection you can check on this flag and return the headerView desired  something like this,
   func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if isNewHeaderView {
            return UIView() // first View for header in section
        } else {
            return UIView() // second View for header in section
        }
    }

And inside your btn action you can just toggle the value of the flag like this,
 @objc func btnClicked(sender: UIButton) {
      isNewHeaderView = !isNewHeaderView
    }

UPDATE

In Swift 4.2 you can use isNewHeaderView.toggle()

Now each time across the your UIViewController the flag changes it will reload the tableView automatically.
Comment: In Swift 4.2 you can use isNewHeaderView.toggle()
Comment: @LloydKeijzer considering this might be a lower version but i'll add that to the answer thank you


Fail hudson build if loglevel set too low

Question: I'd like to fail the build for live jobs of some java applications if their log4j loglevel is set too low.
Is this possible? I'm guessing what I'm maybe looking for is some kind of hudson plugin which could grep the log4j.properties. Or is this something I should somehow be doing in maven?
Comment: Why not just set the log level to the right level?
Comment: You could parse the log configuration provided by your application (and even correct it, as Peter said), but keep in mind that there might be situations in which log configuration can be changed at runtime (e.g. when using an application/web server).
Comment: @PeterLawrey Because I'm not the developer of the applications
Comment: Ah sorry, I understand now - yes, correcting the loglevel would be even better. The problem I've got though is that the applications have been setup to use parameterized logging, but there are a number of naughty developers who replace the parameter placeholder in their application with a hardcoded value and forget to change it back before committing.
Answer: You could write a simple utility app that will configure it's log4j system from the target properties file. After that using the Log4j API you can loop through all appenders and check the log level. If its too low - throw an exception. Run this tool before building the app. If it fails - Jenkins job will fail.


How can I tell, in hook_form_alter(), if a node form is for the node in its default language or a translation?

Question: I'm implementing hook_form_BASE_FORM_ID_alter() in a custom module. I'd like to know if my form is for the node in its default language, or a translation of that original node.
Answer: It looks like I can get it from the form's object, i.e. the form's node, and then use the node's isDefaultTranslation() method.
For example:
<code>use Drupal\Core\Form\FormStateInterface;

function MY_MODULE_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  /** @var \Drupal\node\NodeInterface $node */
  $node = $form_state->getFormObject()->getEntity();
  if ($node->isDefaultTranslation()) {
    // The node form is for the node in its default language.
  }
  else {
    // The node form is for a translation of the node.
  }
}
</code>


Getting error Element type is invalid while learning React Routing

Question: I am new to React. And I am learning React Routing. I created a simple App. Here is my code

        <title>React Routing</title>

        <link href="/Ch13-01-DisplayInitialFrame/resources/css/reactRouting.css" rel="stylesheet">

Here is my reactRouting.js
var destination = document.querySelector("#container");
var App = React.createClass({
    render: function() {
        return (

Simple SPA

Home

Stuff

Contact

        );
    }
});

ReactDOM.render(

        <App/>

,
    destination
);

This code works fine. But when I changed my Render to use ReactRouter I am start getting errors
ReactDOM.render(
    <ReactRouter.Router>
        <ReactRouter.Route path="/" component={App} />
    </ReactRouter.Router>,
    destination
);

The errors are
You are using the in-browser Babel transformer. Be sure to precompile your     scripts for production - https://babeljs.io/docs/setup/
babel.js (60774,4)
Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).
react.js (20483,9)
Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).
react.js (20483,9)
SCRIPT5022: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
react.js (20157,5)

What I am doing wrong ? I am using React v15.3.1. Do I need any more js to run this code?
Thanks
Answer: You are using ReactRouter 4 that has a completely different api then previous version please use new documentation.
I also recommend using a bundler specially when you're getting started with React. create-react-app is a good boilerplate generator for example that takes care of bundler configuration, babel, etc.
Finally in ReactRouter v4 you should use ReactRouter.BrowserRouter component based on doc.
If you insist to try react by script tags add ReactRouter using the script link provided in their npm page. I strongly recommend not to use this configuration in a production application.


The boxes of doom

Question: Say that you have two boxes, both of which contain one red ball and two green balls. You draw one ball out of each, one at a time, except that you stop drawing as soon as you get a red ball. So, if the ball you get out of box 1 is red, you don't get anything out of box 2. If the ball you get out of box 1 is green, you move on to box two and draw a ball out.
What's the chance of getting the red ball? A table reveals that it should be $\frac{3}{7}$:

+---------+---------+-------------------+
|  BOX 1  | BOX 2   | AT LEAST ONE RED? |
+---------+---------+-------------------+
| RED     | -       | Y                 |
| GREEN 1 | GREEN 1 |                   |
| GREEN 1 | GREEN 2 |                   |
| GREEN 1 | RED     | Y                 |
| GREEN 2 | GREEN 1 |                   |
| GREEN 2 | GREEN 2 |                   |
| GREEN 2 | RED     | Y                 |
+---------+---------+-------------------+

That is, 3 favourable cases out of seven possible ones.
However, I need to generalise this to a case of $n$ boxes and a variable mix of red and green balls, and that's when things start breaking down.
So now you have $n$ boxes. Each contains a mix of green balls and red balls. Let $r_i$ be the chance to get a red ball from box $i$, and $g_i = 1 - r_i$ the chance to get a green ball.
As before, you draw only one ball out of each box, and one at a time. Green ball, you move on to the next box; red ball, you stop drawing immediately. You can ever get at most one red ball.
Say that $R_i$ is the event of getting the green ball out of the first $i-1$ boxes and the red one out of box $i$; it has probability $P(R_i)= g_1g_2\cdots g_{i-1}r_i$. This means that, if you do get the red ball, only one of the following events happened:
$R_1$, or
$R_2$ (i.e., a green ball out of box 1 and red ball out of box 2), or
$R_3$ (a green ball out of the first two boxes and a red ball out of box 3), or
$\dots$
$R_{n-1}$ (a green ball out of the first $n-2$ boxes and a red one out of box $n-1$), or
$R_{n}$ (a green ball out of the first $n-1$ boxes and a red one out of box $n$).
Say that $R$ is the event of getting a red ball. The probability $P(R)$ of getting the red ball should be the chance of any of these events happening, and since they're all mutually exclusive, I thought that
$$P(R) = \sum_{i=1}^n P(R_i).$$
Except it doesn't quite seem to work.
If we try the above formula in the case of two boxes with one one red ball and two green balls each, we get
$$P(R) = P(R_1) + P(R_2) = r_1 + g_1r_2 = \frac{1}{3} + \frac{2}{3}\frac{1}{3} = \frac{1}{3} + \frac{2}{9}= \frac{5}{9}.$$
That's too much, and as you can see by making a table, that's actually the chance of getting at least a red ball without stopping at all at the first red ball.

+---------+---------+-------------------+
|  BOX 1  | BOX 2   | AT LEAST ONE RED? |
+---------+---------+-------------------+
| RED     | GREEN 1 | Y                 |
| RED     | GREEN 2 | Y                 |
| RED     | RED     | Y                 |
| GREEN 1 | GREEN 1 |                   |
| GREEN 1 | GREEN 2 |                   |
| GREEN 1 | RED     | Y                 |
| GREEN 2 | GREEN 1 |                   |
| GREEN 2 | GREEN 2 |                   |
| GREEN 2 | RED     | Y                 |
+---------+---------+-------------------+

As you can see, nine combinations total, five of which have at least a red ball. The formula is counting cases where the red ball was drawn first as separate, while they should all count as one. I have been thinking about this for a while, but I was unable to find the right formula.
Any help would be much appreciated!
Answer: Your second table is the relevant one. Think of it like this: even if you draw a red ball from the first box of doom, you might as well draw a ball from the second box of doom too, just for fun. This way, each of the nine possible outcomes has the same probability.
The problem with your first table is that not all outcomes have the same probability. The probability of the first outcome is $\frac13$, but the probability of each subsequent item is $\frac19$. So you get $\frac13+\frac19+\frac19=\frac59$, the same as the second table.
Comment: The TonyKs of doom!
Comment: Looks like you accidentally double-posted? (I'm upvoting the first version :-)
Comment: @joriki: yes, it looks like it, doesn't it? But how could that happen? I would have to edit, copy the text, cancel the edit, and post a new answer! (Which I promise you I didn't do.)
Comment: No, I'm sure you didn't :-) Perhaps a glitch in the system where you hit exactly the right microsecond where one thread didn't know yet that another one had already created the answer, or something like that...
Comment: Or perhaps there are two of me?
Comment: Bwahaha${}{}{}$

The boxes of doom


How I can repaint a JSVGCanvas after editing the SVGDocument? using Apache Batik

Question: I'm trying to modify the SVG document in runtime and go repainting the modifications performed to the SVG:
I need your help, i'm trying with repaint method, but is not posible refresh the SVG Canvas.
this is the code:
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.*;
import java.io.StringReader;

import javax.swing.*;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;

import org.apache.batik.swing.*;
import org.apache.batik.svggen.*;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.util.XMLResourceDescriptor;

import org.w3c.dom.*;
import org.w3c.dom.svg.*;

public class BatikViewGeneratedSVGDemo extends JFrame implements MouseListener, MouseMotionListener{

    String xmlSVG;
    SVGDocument svgDoc;
    Element svgRoot;
    JSVGCanvas canvas;

    public BatikViewGeneratedSVGDemo() throws HeadlessException {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(600, 600));
        setMinimumSize(new Dimension(600, 600));

        String xmlSVG = ""
                + "<?xml version=\"1.0\" standalone=\"no\"?>\n" +
                "<svg "
                + "contentScriptType=\"text/ecmascript\" "
                + "xmlns:xlink=\"http://www.w3.org/1999/xlink\" "
                + "xmlns=\"http://www.w3.org/2000/svg\"\n"
                + "baseProfile=\"full\"\n "
                + "zoomAndPan=\"magnify\" "
                + "contentStyleType=\"text/css\" "
                + "preserveAspectRatio=\"xMidYMid meet\" "
                + "width=\"600\"  "
                + "height=\"600.0px\"  "
                + "viewBox='0 0 716.3783 753.51105'"
                + " version=\"1.0\"  >\n "
                + " <ellipse id='circulo1' fill-opacity=\"0.5\" fill=\"#ff0033\" rx=\"58.0\" cx=\"238.0\" ry=\"45.5\" cy=\"180.5\" stroke=\"#000000\"/>\n "
                + "</svg>";

        StringReader reader = new StringReader(xmlSVG);
        String uri = "nothing";
        try {
            String parser = XMLResourceDescriptor.getXMLParserClassName();
            SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
            svgDoc = f.createSVGDocument(uri, reader);
            Element circulo = svgDoc.getElementById("circulo1");
            System.out.println("opacidad: " + circulo.getAttribute("fill-opacity"));

            svgRoot = svgDoc.getDocumentElement();
            // Display the document.
            canvas = new JSVGCanvas();
            System.out.println("doc.width: " + svgRoot.getAttribute("width"));
            getContentPane().add(canvas, BorderLayout.CENTER);
            canvas.setSVGDocument(svgDoc);

            JButton btn = new JButton("Crear Circulo");
            btn.addMouseListener(this);
            getContentPane().add(btn, BorderLayout.SOUTH);
            System.out.println("ancho: " + canvas.getSize().width + " alto: " + canvas.getSize().height);
        } catch (Exception ex) {
            System.out.println("ocurrió un error");
        } finally {
            reader.close();
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        crearCirculo();
    }

    @Override
    public void mousePressed(MouseEvent e) {}

    @Override
    public void mouseReleased(MouseEvent e) {}

    @Override
    public void mouseEntered(MouseEvent e) {}

    @Override
    public void mouseExited(MouseEvent e) {}

    @Override
    public void mouseDragged(MouseEvent e) {}

    @Override
    public void mouseMoved(MouseEvent e) {}

    public void crearCirculo() {
        Element newCircle = svgDoc.createElement("ellipse");
        newCircle.setAttribute("id", "circulo2");
        newCircle.setAttribute("fill-opacity", "0.5");
        newCircle.setAttribute("fill", "#990055");
        newCircle.setAttribute("rx", "100");
        newCircle.setAttribute("cx", "150");
        newCircle.setAttribute("ry", "100");
        newCircle.setAttribute("cy", "150");
        newCircle.setAttribute("stroke", "#990055");
        System.out.println("XML: "+svgDoc.getRootElement().getXMLbase());

        svgRoot.appendChild(newCircle);
        canvas.setSVGDocument(svgDoc);
        System.out.println("opacidad2: " + svgDoc.getElementById("circulo2").getAttribute("fill-opacity"));
        System.out.println("entra");
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                BatikViewGeneratedSVGDemo obj = new BatikViewGeneratedSVGDemo();
                obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                obj.setVisible(true);
            }
        });
    }
}

Answer: You should create a Runnable with all modifications to the SVG document and then use JSVGCanvas Update Manager's Runnable Queue to call this Runnable and all changes to take effect.
public Runnable r = new Runnable() {

        @Override
        public void run() {
            value = value + 10;
            svgCanvas.evaluate("setlevel(" + value + ",'Text')");
        }
    };

And then,
svgCanvas.getUpdateManager().getUpdateRunnableQueue().invokeLater(r);

Everything done outside this queue will not take effect inmediatly.
Answer: For your new ellipse to be rendered it has to be recognized by namespace. This does currently not happen due to you using:
public void crearCirculo() {
    Element newCircle = svgDoc.createElement("ellipse");
    // ...
}

If you instead change to the following:
public void crearCirculo() {
    Element newCircle = svgDoc.createElementNS("http://www.w3.org/2000/svg", "ellipse");
    // ...
}

Your new ellipsis is rendered with no further changes needed.


Convertendo String para date Swfit 3

Question: Olá, estou tentando converter uma String em Date em Swift 3. Porém a data sempre esta me retornando com duas horas a mais. Segue abaixo meu código.
let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
    dateFormatter.locale =  Locale(identifier: "pt_BR")
    let date:Date = dateFormatter.date(from:"12-12-2017 16:49:19")!

Saída: 2017-12-28 18:49:19 +0000
Comment: Aqui parece ok: http://tpcg.io/bhwp9W. Talvez esteja conceituando errado o que precisa fazer ou tem configuração errada no computador Outro: https://swift.sandbox.bluemix.net/#/repl/5a311de352fd1304fcf3a6c0.
Comment: Estranho, pois estou  compilado no iphone e quando pego a timezone, aparece America/Sao Paulo, tudo certinho.
Answer: Para que seu código funcione com o Locale do BR, é necessário alterar a string "pt_BR" para "pt-br", com isso você verá que a exibição da data ficará correta.
Você pode testar melhor esta exibição informando algum valor para a propriedade timeZone do dateFormatter, veja o código abaixo:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
dateFormatter.locale = Locale.init(identifier: "pt-br")
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let date:Date = dateFormatter.date(from:"12-12-2017 16:49:19")!

Neste exemplo, a saída será -3h (ou -2h no horário de verão) para a TimeZone que segue o horário de Brasília.

Convertendo String para date Swfit 3


Unable to launch express with npm start

Question: How do I correctly create and launch express with npm start? When I do "npm start" I get the following error. Failed at the email@example.com start script. I see the following in the error log that hints to the app.js but what is it about the app.js that is incorrect? Thank you.
20 error code ELIFECYCLE
21 error errno 126
22 error firstname.lastname@example.com start: `./src/app.js`
22 error Exit status 126
23 error Failed at the firstname.lastname@example.com start script.

I have the following package.json file.
{
    "name": "webserver",
    "preferGlobal": true,
    "version": "1.0.0",
    "author": "Milton Centeno <firstname.lastname@example.com>",
    "description": "a simple express web server",
    "license": "MIT",
    "main" : "./src/app.js",
    "engines": {
        "node": ">=0.10"
    },
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "dependencies": {
        "express": ">=4.15.3"
    }
}

Here is the output of the tree command that shows where my app.js file is relative to package.json.
.
├── node_modules
├── package-lock.json
├── package.json
└── src
    └── app.js

And this is what I have for my app.js
// Load the Express package as a module
const express = require("express");

// Access the exported service
const app = express();

// Return a string for requests to the root URL ("/")
app.get("/", (request, response) => {
  response.send("Hello from Express!");
});

// Start listening to incoming requests
// If process.env.PORT is not defined, port number 3000 is used
const listener = app.listen(process.env.PORT || 3000, () => {
  console.log(`Your app is listening on port ${listener.address().port}`);
});

Answer: You need to define a start script: "start": "node src/app.js",.
From the NPM docs:

This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.
Comment: Thanks Daniel. I had to add node before the src/app.js.

Unable to launch express with npm start


Testar conexao com a internet de uma aplicação

Question: Tenho um app que conecta com a webservice mas o problema é que quando estou com o 3G, ele dá erro.
Quando a conexão esta boa, com uma wi-fi por exemplo funciona perfeitamente.
Tenho alguns algoritmos que testam a conexão, mas todos valida somente se esta conectado, e as vezes o 3G tem rede mas não conecta com a internet, gerando erro no app.
Alguém poderia me ajudar a verificar a internet antes do app tentar consumir a webservice?
Comment: Opa, espero que te ajude: https://pt.stackoverflow.com/questions/111898/identificar-o-tipo-de-conex%C3%A3o-3g-4g-e-ou-wifi
Answer: Esse método faz a validação se existe conexão.
public static boolean isOnline(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected())
            return true;
        else
            return false;
 }

Durante o consumo ao web service, vc pode adicionar um try catch e pegar a execption UnknownHostException e tratá-la.
  try {
    //seu código
  } catch(UnknownHostException e) {
   // trata o erro de conexão.
  }

Answer: Primeiro, não se esqueça da permissão no Manifest. Se não, sua aplicação não conseguirá conectar.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Depois, crie um método em algum local de sua preferência e onde faça sentido na sua aplicação.
public boolean isOnline() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return manager.getActiveNetworkInfo() != null &&
       manager.getActiveNetworkInfo().isConnectedOrConnecting();
}

Um "if" básico te devolve o status da conexão.
if(isOnline()) {
    //faz algo :)
}


NFS kerberos not working

Question: I'm trying to authenticate to another server with kerberos and I'm getting the following response:
[root@ip-10-1-5-59 nfs-test-1]#  mount -t nfs4 -o sec=krb5  kbserver.example.com:/ /home/ec2-user/nfs-test-1 --verbose
mount.nfs4: timeout set for Thu Aug 23 00:59:58 2018
mount.nfs4: trying text-based options 'sec=krb5,vers=4.1,addr=10.1.5.21,clientaddr=10.1.5.59'
mount.nfs4: mount(2): Permission denied
mount.nfs4: trying text-based options 'sec=krb5,vers=4.0,addr=10.1.5.21,clientaddr=10.1.5.59'
mount.nfs4: mount(2): Permission denied
mount.nfs4: access denied by server while mounting kbserver.example.com:/

If I tail /var/log/messages I see the following log, but not sure if this is relevant.
[ec2-user@ip-10-1-5-21 anypoint-nfs-share]$ sudo tail -f /var/log/messages | grep warn
Aug 23 00:59:28 localhost kernel: NFSD: warning: no callback path to client Linux NFSv4.1 ip-10-1-5-59.us-east-2.compute.internal: error -22

In my client, the klist -ke outputs the following:
[root@ip-10-1-5-59 nfs-test-1]# klist -ke
Keytab name: FILE:/etc/krb5.keytab
KVNO Principal
---- --------------------------------------------------------------------------
   8 firstname.lastname@example.com (aes256-cts-hmac-sha1-96)
   8 firstname.lastname@example.com (aes128-cts-hmac-sha1-96)
   8 firstname.lastname@example.com (des3-cbc-sha1)
   8 firstname.lastname@example.com (arcfour-hmac)
   8 firstname.lastname@example.com (camellia256-cts-cmac)
   8 email@example.com (camellia128-cts-cmac)
   8 firstname.lastname@example.com (des-hmac-sha1)
   8 email@example.com (des-cbc-md5)
   7 firstname.lastname@example.com (aes256-cts-hmac-sha1-96)
   7 firstname.lastname@example.com (aes128-cts-hmac-sha1-96)
   7 firstname.lastname@example.com (des3-cbc-sha1)
   7 email@example.com (arcfour-hmac)
   7 email@example.com (camellia256-cts-cmac)
   7 email@example.com (camellia128-cts-cmac)
   7 email@example.com (des-hmac-sha1)
   7 firstname.lastname@example.com (des-cbc-md5)
   8 firstname.lastname@example.com (aes256-cts-hmac-sha1-96)
   8 firstname.lastname@example.com (aes128-cts-hmac-sha1-96)
   8 email@example.com (des3-cbc-sha1)
   8 email@example.com (arcfour-hmac)
   8 firstname.lastname@example.com (camellia256-cts-cmac)
   8 email@example.com (camellia128-cts-cmac)
   8 email@example.com (des-hmac-sha1)
   8 email@example.com (des-cbc-md5)
   8 email@example.com (aes256-cts-hmac-sha1-96)
   8 firstname.lastname@example.com (aes128-cts-hmac-sha1-96)
   8 firstname.lastname@example.com (des3-cbc-sha1)
   8 firstname.lastname@example.com (arcfour-hmac)
   8 email@example.com (camellia256-cts-cmac)
   8 email@example.com (camellia128-cts-cmac)
   8 firstname.lastname@example.com (des-hmac-sha1)
   8 firstname.lastname@example.com (des-cbc-md5)
   8 firstname.lastname@example.com (aes256-cts-hmac-sha1-96)
   8 email@example.com (aes128-cts-hmac-sha1-96)
   8 email@example.com (des3-cbc-sha1)
   8 email@example.com (arcfour-hmac)
   8 firstname.lastname@example.com (camellia256-cts-cmac)
   8 firstname.lastname@example.com (camellia128-cts-cmac)
   8 email@example.com (des-hmac-sha1)
   8 email@example.com (des-cbc-md5)

The following nfs/rpc services are enabled in my server:
[ec2-user@ip-10-1-5-21 ~]$ systemctl list-unit-files | grep enabled | grep -E "(nfs|rpc)"
nfs-server.service                            enabled
nfs.service                                   enabled
rpcbind.service                               enabled
rpcbind.socket                                enabled
nfs-client.target                             enabled

And the following nfs/rpc services are enabled in my client:
[ec2-user@ip-10-1-5-59 nfs-test-1]$ systemctl list-unit-files | grep enabled | grep -E "(nfs|rpc)"
rpcbind.service                               enabled
rpcbind.socket                                enabled
nfs-client.target                             enabled

Just noticed that the following is throwing an error:
[root@ip-10-1-5-59 nfs-test-1]# sudo systemctl status nfs-secure.service
● rpc-gssd.service - RPC security service for NFS client and server
   Loaded: loaded (/usr/lib/systemd/system/rpc-gssd.service; static; vendor preset: disabled)
   Active: active (running) since Thu 2018-08-23 00:35:16 UTC; 31min ago
 Main PID: 32200 (rpc.gssd)
   CGroup: /system.slice/rpc-gssd.service
           └─32200 /usr/sbin/rpc.gssd -vvv

Aug 23 00:59:29 ip-10-1-5-59.us-east-2.compute.internal rpc.gssd[32200]: No key table entry found for email@example.com while gett...PLE.COM'
Aug 23 00:59:29 ip-10-1-5-59.us-east-2.compute.internal rpc.gssd[32200]: Success getting keytab entry for firstname.lastname@example.com
Aug 23 00:59:29 ip-10-1-5-59.us-east-2.compute.internal rpc.gssd[32200]: INFO: Credentials in CC 'FILE:/tmp/krb5ccmachine_EXAMPLE.COM' are good until 1535070934
Aug 23 00:59:29 ip-10-1-5-59.us-east-2.compute.internal rpc.gssd[32200]: INFO: Credentials in CC 'FILE:/tmp/krb5ccmachine_EXAMPLE.COM' are good until 1535070934
Aug 23 00:59:29 ip-10-1-5-59.us-east-2.compute.internal rpc.gssd[32200]: creating tcp client for server kbserver.example.com
Aug 23 00:59:29 ip-10-1-5-59.us-east-2.compute.internal rpc.gssd[32200]: creating context with server firstname.lastname@example.com
Aug 23 00:59:29 ip-10-1-5-59.us-east-2.compute.internal rpc.gssd[32200]: WARNING: Failed to create krb5 context for user with uid 0 for server firstname.lastname@example.com
Aug 23 00:59:29 ip-10-1-5-59.us-east-2.compute.internal rpc.gssd[32200]: WARNING: Failed to create machine krb5context with cred cache FILE:/tmp/krb5ccmachine_EXAMPLE.CO...mple.com
Aug 23 00:59:29 ip-10-1-5-59.us-east-2.compute.internal rpc.gssd[32200]: WARNING: Failed to create machinekrb5 context with any credentialscache for server kbserver.example.com
Aug 23 00:59:29 ip-10-1-5-59.us-east-2.compute.internal rpc.gssd[32200]: doing error downcall

The following logs show up on jourtanctl:
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: Success getting keytab entry for email@example.com
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: INFO: Credentials in CC 'FILE:/tmp/krb5ccmachine_EXAMPLE.COM' are good until 1535070934
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: INFO: Credentials in CC 'FILE:/tmp/krb5ccmachine_EXAMPLE.COM' are good until 1535070934
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: creating tcp client for server kbserver.example.com
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: creating context with server firstname.lastname@example.com
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: WARNING: Failed to create krb5 context for user with uid 0 for server email@example.com
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: WARNING: Failed to create machine krb5context with cred cache FILE:/tmp/krb5ccmachine_EXAMPLE.COM for server kbserver.example.com
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: WARNING: Machine cache prematurelyexpired or corrupted trying torecreate cache for server kbserver.example.com
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: Full hostname for 'kbserver.example.com' is 'kbserver.example.com'
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: Full hostname for 'kbclient.example' is 'kbclient.example'
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: No key table entry found for email@example.com while getting keytab entry for 'firstname.lastname@example.com'
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: No key table entry found for email@example.com while getting keytab entry for 'email@example.com'
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: No key table entry found for firstname.lastname@example.com while getting keytab entry for 'firstname.lastname@example.com'
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: No key table entry found for firstname.lastname@example.com while getting keytab entry for 'email@example.com'
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: No key table entry found for email@example.com while getting keytab entry for 'email@example.com'
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: Success getting keytab entry for firstname.lastname@example.com
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: INFO: Credentials in CC 'FILE:/tmp/krb5ccmachine_EXAMPLE.COM' are good until 1535070934
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: INFO: Credentials in CC 'FILE:/tmp/krb5ccmachine_EXAMPLE.COM' are good until 1535070934
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: creating tcp client for server kbserver.example.com
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: creating context with server firstname.lastname@example.com
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: WARNING: Failed to create krb5 context for user with uid 0 for server email@example.com
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: WARNING: Failed to create machine krb5context with cred cache FILE:/tmp/krb5ccmachine_EXAMPLE.COM for server kbserver.example.com
Aug 23 01:09:48 kbclient.example rpc.gssd[32200]: WARNING: Failed to create machinekrb5 context with any credentialscache for server kbserver.example.com

Answer: Hard to tell. Just in case, did your check your /etc/exports? It should have at least "sec=krb5", e.g:
/  10.1.5.0/24(rw,sec=krb5:krb5i:krb5p)

Comment: Yeah, it's there. [ec2-user@kbserver ~]$ sudo cat /etc/exports
/home/ec2-user/anypoint-nfs-share     *(rw,sec=krb5,fsid=0,sync,no_root_squash)
Answer: The problem was that I needed to have a keytab file with the hosts added. I couldn't get it to use kadmin.local to use ktadd to add it, so I copied it manually.
In the client:
echo $BASE_64_ENCODED_FILE_FROM_SERVER | base64 -d > /etc/krb5.keytab
kinit -k -t /etc/krb5.keytab
mkdir -p /home/root/nfs-test/2
sudo mount -t nfs4 -o sec=krb5 kbserver.example.com:/ /home/root/nfs-test/2 --verbose
mount.nfs4: timeout set for Fri Aug 24 01:02:58 2018
mount.nfs4: trying text-based options 'sec=krb5,vers=4.1,addr=10.1.5.21,clientaddr=10.1.5.59'

NFS kerberos not working


What does the term 'Bootstrap' mean?

Question: Referring to https://www.drupal.org/project/health_check
I am confused as to what 'If Drupal fails to bootstrap' means.
What is term 'bootstrap' referring to? Does it make a database call? From what I have read bootstrap can mean from the Drupal core.
So if the healthcheck module fails is it because it cannot see the database, will the module render a 200 or some other response code?
Answer: In computing, "bootstrapping" refers to software getting to a state to where it can perform the task being requested.
In the context of Drupal, it means the code starts and does everything up to the point where it generates the page.  It more-or-less includes

connecting to the database
reading configuration
loading modules

The bootstrap process is pretty much the same for everything request; what happens when a page gets rendered and sent to the browser differs page-to-page.
So, when "Drupal fails to bootstrap", it means that it wasn't able to get to a point to figure out what to do, and is considered a Fatal Error.  In my experience nine times out of ten when it happens in a production environment, it is because there was a problem connecting to the database.

What does the term 'Bootstrap' mean?


The two projection maps are different?

Question: I'm reading Vistoli's notes, and I came across something on the bottom of page 31, starting with "The reader might find our definition of sheaf pedantic..."
Essentially my problem is the following claim: Let $V \xrightarrow{i} U$ a morphism of schemes and consider the two projections $V \times_{U} V \xrightarrow{p_{i}} V$ for $i=1,2$. If $i$ is not injective, "the two projections will be different".
This seems crazy to me given the symmetry in the construction, can someone please comment?
Comment: Dear martin,  there is no site in sight here ...
Comment: ok, I realize that while reading these notes, I should get out of the habit of thinking about just schemes, so maybe this is a problem which arises for some stranger sites. still, even that for me is hard to imagine, so again, what is he getting at.
Answer: Let $k$ be a field.  Take $U=\text {Spec}(k),V=\mathbb A^1_k$ and for $ i:\mathbb A^1_k\to \text {Spec}(k)$ take the structural map.
Then the two projections  $p_i:  \mathbb A^1_k\times_{\text {Spec}(k)} \mathbb A^1_k =\mathbb A^2_k\to \mathbb A^1_k$ are certainly different.
Answer: I guess the following is meant (and let me generalize this directly to category theory):
Let $i : V \to U$ be a morphism in a category with fiber products. Then the following are equivalent:

$i$ is a monomorphism
The projections $p_1,p_2 : V \times_U V \to V$ are equal.
The diagonal morphism $\Delta : V \to V \times_U V$ is an isomorphism.

The proof is straight forward.
Of course, in concrete categories, "monomorphism" and "morphism with underlying injective map" are completely different concepts. Some authors say "injective sheaf homomorphism" when they actually mean a monomorphism of sheaves. Perhaps this also applies to schemes.

The two projection maps are different?


Should I use a confidence interval or a prediction interval around the LOESS fitted curve?

Question: A Freakonometrics blog post shows how to use a LOESS regression of the residuals of a logistic model on the predicted values of the logistic model to assess the linearity of the predictors used in the logistic regression model.
If the green interval contains zero, this indicates that the model is correctly specified (or close enough).
My question is, should I use a confidence interval or a prediction interval around the LOESS fitted curve?
I am interested in whether the estimate of $\text{E}[y \mid x]$ is correctly specified - so that makes me think confidence interval. However, normally prediction intervals are used for individual observations.

For reference:
Difference between confidence intervals and prediction intervals
How to calculate prediction intervals for loess
Comment: A heuristic I find useful is to ask whether a *straight line* can fit through the **confidence band** of a nonparametric regression estimate, including LO(W)ESS: if it *can* a linear regression straight line estimate is probably as well-fit for the given data, if not, estimation/interpretation of a nonlinear relationship is probably warranted.
Comment: Possible duplicate of [How to calculate prediction intervals for LOESS?](https://stats.stackexchange.com/questions/141552/how-to-calculate-prediction-intervals-for-loess)
Comment: Yes, that is the purpose of this plot. Here the straight line is where the mode residuals= 0. It's not a duplicate, I'm not interested in *how* to make the prediction interval but whether to use the *prediction* interval or the *confidence* interval.
Answer: You would probably use a confidence interval, since it is narrower and more conservative. Inverting null hypothesis significance testing to "confirm a null hypothesis" has innumerable practical and theoretical problems. Case in point, it's hard (impossible?) to state the actual "level" or "power" of the test, whatever you are actually testing, and one can easily liken a prediction interval to an "extra wide" confidence interval. Add to that: those points are not predictions, you have observed them, and you're interested in whether the mean response would be within a consistent range as that describes the data generating mechanism. But as pragmatic tool, I see it better to verge on the side of more false positives rather than more false negatives.
Comment: "those points are *not* predictions, you have observed them" - that is actually all that needs to be said. Why would you want to calculate *prediction* intervals for *observations*?
Comment: @StephanKolassa it's tempting to offer that as the sole explanation, but it's good to point out even then, the limits of that interval have a dubious interpretation. Equivalence testing (so that you falsify a null hypothesis of difference) requires a user to specify a margin of non-equivalence. That tiny qualifier "...or close enough" suffices to tell me that this is an exploratory exercise, and not formal.


How we can generate Latitude/Longitude at the time of import while using Feed module

Question: I am using Feed Module For Importing Nodes Form CSV File. What i want that at the time of import how we can generate lat/long pair for every node imported. I have address in csv file for every node an i want to generate lat/long pairs.
Answer: I use the location module in tandem with the location feeds module (http://drupal.org/project/location_feeds).  It can be configured to geocode the the addresses at the time of import.
I had to adjust some timeout settings as its possible to try to geocode addresses faster than the geocoding api allows.


Retrieving data fron JSON files

Question: I am trying to use JQuery's JSONP feature to retrieve barometric pressure data from a website.
First, I used Yahoo! Pipes to convert the XML data to JSON. Then I tried to receive and use that data in an alert, but it didn't work. In this JSFiddle, I have a simple, working example, but when I try use the more advanced JSON file, it doesn't work.
See also this article by IBM.
Comment: **1.)** You have to choose jQuery in JSFiddle instead of (default) Mootools. **2.)** Open your browser's javascript console and see the occurring errors. **3.)** You haven't defined the callback function!
Comment: I get a 404 on that first link. The page is not found
Comment: @akellehe He also forgot `http://` in the link.
Comment: It says that `data.value` is undefined in the error console, even after adding the `http://` and changing to JQuery (which I had added in the resources).
Comment: it seems you are just learning javascript. i can only suggest for next time try to make tests in smaller increments. understand which parts fail and why. if you just write a bunch of code and then guess what the problem is you will always end up having misleading titles like in this question (really: i downvoted because the actual issue has absolutely nothing to do with the title). also you can look at my answer, i corrected your code and the alert spits out the pressure value. good luck with your project!
Comment: It's not that I am just learning JavaScript, but I am new to JSON and JQuery. I definitely learned a lot working on this.
Comment: I changed the name; I think it works a bit better for the community
Comment: BTW, here is the final product in case anyone is interested: http://jsfiddle.net/iansan5653/7EPjH/16/
Answer: Problems in your code

You forget to include http:// in your link

You need to try this (see alert. It will alert the title)

Click Me

DEMO
But its better to use like following:

Click Me

function barometer() {
    $.getJSON('http://pipes.yahoo.com/pipes/pipe.run?_id=467a55b506ba06b9ca364b1403880b65&_render=json&textinput1=40.78158&textinput2=-73.96648&_callback=?', function(data) {
        alert(data.value.title);
    })
}

$('div.loadjson').on('click', function() {
    barometer();
});

Note: $.getJSON() returns two parameters within data object.
     - 1st one is `count` that have integer value
     - 2nd one is `value`, which is an `Object`.

To get the second parameter you need to use data.value.
DEMO
Comment: Sorry, I don't have firebug. What is the point of adding the console.log? In your demo, clicking on the div still didn't bring up the alert. Thanks
Comment: @Ian if you're going to be doing JS development I think it would be strongly encouraged to learn firebug or how to use another browser's JavaScript console. http://stackoverflow.com/questions/55633/where-is-the-console-api-for-webkit-safari
Comment: @Ian I make my fiddle with `alert()`, but you should use to learn firebug
Comment: I don't use Firebug because I can just use the Firefox Dev Tools (and Firebug is one of the slowest Firefox addons). I see the alert now, but not with my way to get to the barometer,which means that `data.value.items.data.parameters.pressure.value` is incorrect. Any ideas on that? I checked the JSON file after running it through a JavaScript tidying program, but I can't figure out what is wrong with that path.
Comment: Actually, I;'ve got it working now. The only problem I am having is that when I get to `parameters`. There are two `parameters` under `data`, so how do I select the second one?
Comment: Got it by using `data[1].parameters` which worked perfectly. `data.value.items[0].data[1].parameters.pressure.value`.
Comment: With deeply nested JSON figuring out the tree/path can cause headaches for some thankfully there are a few online tools like this one http://lovelogic.net/support_articles/JSON_XML_parser_demo.php that can decode XML and JSON into something that makes more sense.
Answer: there were many many many problems with the code i fixed it and commented on the problems  inline ...
jsfiddle here:
http://jsfiddle.net/kritzikratzi/LQcVd/
function loadBarometerData(){
    // 1. it's not generally bad practice to put stuff in the
    //    onClick listeners, but really... don't put such long code there! it's not readable ...
    // 2. you were missing a "http://" and it was downloading
    //    jsfiddle.net/pipes.yahoo.com/....
    // 3. getJSON doesn't return a result immediately, you need to use callbacks for that!!
    $.getJSON('http://pipes.yahoo.com/pipes/pipe.run?_id=467a55b506ba06b9ca364b1403880b65&_render=json&textinput1=40.78158&textinput2=-73.96648&_callback=?' ).success( barometer );
};

function barometer(data) {
    console.log( data );
    // 4. you had items instead of items[0]
    //    similar with data.
    alert(data.value.items[0].data[1].parameters.pressure.value);
};

function showPrice(data) {
    alert("Symbol: " + data.symbol[0] + ", Price: " + data.price);
}

Retrieving data fron JSON files


Stop Game App if Home Button clicked iOS

Question: I don't know if by Apple's rules it's necessary to implement that when a user is in the middle of a game, if they click on home button the game pauses and when they click back in game, the game unpauses.
Do I have to click something on storyboard for a home button to appear? I don't know.
Since storyboards has no home button on it so how do I code that when user clicks home button to exit the app, the game pauses. When they return again, the game unpauses.
Comment: Read the docs about an application's lifecycle and review the delegate methods in `UIApplicationDelegate`.
Comment: The Home button is the physical button on iOS devices.
Answer: If the home button is clicked, your App Delegate's method applicationDidEnterBackground: is called. Thus, you can respond as you see fit.
However, you might not need to do anything special here, because when your app goes into the background, it is suspended — it stops running. Thus, in a sense, it pauses automatically. Timers are paused, for example. (Note that this feature, the automatic pausing of timers, is broken in the iOS 8 simulator; but it works correctly on a device.)
Answer: If you are making a simple game, you don't have to implement anything for it to pause. The memory management mechanism will take care of it.
However if you are making a game that needs some features say internet connection, you will have to handle what to do with your tasks. For instances, please checkout the apple's UIApplicationDelegate reference page. Check out "Managing State Transitions" section to have a better understanding.
Answer: In the iOS simulator, you can "press the home button" with the CMD+SHIFT+H shortcut.
You can override the following methods in your UIApplicationDelegate implementation:

applicationWillResignActive: (Called when leaving the foreground state.)
  applicationWillEnterForeground: (Called when transitioning out of the background state.)

Or you can use NSNotificationCenter and the equivilent notifications:

UIApplicationWillEnterForegroundNotification
  UIApplicationWillResignActiveNotification

When iOS puts your app into the background, it is essentially paused, in that it is no longer running (with some exceptions for things like music players, GPS consumers, etc).  But your render loop isn't doing anything.  However, your app may get killed while in this state, so you probably want to do some bookkeeping to keep your apps state consistent.  It wouldn't hurt to pause your app, save the users progress, etc, and then resume/restart and load that info when you come back.
Answer: There are two way to implement it:
1: use NSNotificationCenter:
- (void)setupBackgroundNotification {
    // the same to applicationWillEnterForeground:
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(open)
                                                 name: UIApplicationWillEnterForegroundNotification
                                               object:nil];

    //// the same to applicationWillResignActive
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(close)
                                                 name: UIApplicationWillResignActiveNotification
                                               object:nil];
}

- (void)open {
    NSLog(@"the same to applicationWillEnterForeground");
}

- (void)close {
    NSLog(@"the same to applicationWillResignActive");
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:applicationWillEnterForeground object:Nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:applicationWillResignActive object:Nil];
}

2: Use UIApplicationDelegatedelegate Method
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


Why am I unable to view my Flask-Admin pages on Heroku?

Question: I have a Flask application that I am attempting to deploy onto Heroku. I have two problems that are stopping me from deploying. The first is that when I run the command heroku local. I am taken to my localhost:5000/ page in which everything looks fine until I head to my /admin/login page. The second is that heroku can't seem to detect the heroku/python build pack. I don't know if the first problem is related to the second.
For that page I get a 500 error and additionally there are no logs on the command line to view. All I see is this:
⇒  heroku local
   forego | starting web.1 on port 5000
   web.1  | [2015-12-03 12:31:42 -0500] [7200] [INFO] Starting gunicorn 19.4.1
   web.1  | [2015-12-03 12:31:42 -0500] [7200] [INFO] Listening at:
   http://0.0.0.0:5000 (7200)
   web.1  | [2015-12-03 12:31:42 -0500] [7200] [INFO] Using worker: sync
   web.1  | [2015-12-03 12:31:42 -0500] [7203] [INFO] Booting worker with pid: 7203

I can't determine if I'm supposed to see something on that page or if my Procfile is somehow not allowing it. Anyways, this is my directory structure:
~/Desktop/project_directory
    /venv
       / static
         /images, javascript, css, etc.
       / templates
         - html files
       / bin
       / include
       / migrations
       - Procfile
       - alembic.ini
       - blackduck_directory.py
       - blackduck_directory.pyc
       - pip-selfcheck.json
       - requirements.txt
       - runtime.txt

This is the content of my Procfile:
web: gunicorn blackduck_directory:app --log-file=-

This is my runtime.txt:
python-2.7.10

This is my requirements.txt:
alembic==0.7.7
bcrypt==2.0.0
blinker==1.4
cffi==1.3.1
dominate==2.1.16
Flask==0.10.1
Flask-Admin==1.3.0
Flask-Bcrypt==0.7.1
Flask-Login==0.3.2
Flask-Mail==0.9.1
Flask-Migrate==1.6.0
Flask-Principal==0.4.0
Flask-Script==2.0.5
Flask-SQLAlchemy==2.1
Flask-WTF==0.12
gunicorn==19.4.1
itsdangerous==0.24
Jinja2==2.8
Mako==1.0.2
MarkupSafe==0.23
passlib==1.6.5
Pillow==3.0.0
psycopg2==2.6.1
pycparser==2.14
python-editor==0.4
six==1.10.0
SQLAlchemy==1.0.9
visitor==0.1.2
Werkzeug==0.11.2
wheel==0.24.0
WTForms==2.0.2

There is a question on stackoverflow Heroku with Flask-Admin. Has anyone encountered this problem? Otherwise running python blackduck_directory.py works properly.
Answer: I found the problem. I removed app.secret_key 'secret_key' from my application. That's why it wasn't working.


Free Php encoder

Question: I dont know whether this is correct posting place, can anybody please suggest me few free php encoding softwares as i dont have any money to buy one currently?
FOR ENCODING PHP SCRIPTS / SOURCE CODE
Thank You.
Comment: Encoding... What exactly? Video? Audio? Text?
Comment: Maybe in this special case a none open-source software fits better to your needs - you can take a look at e.g. [www.codecanyon.net](https://codecanyon.net/search/php%20encoder) and search for `php encoder`
Answer: Free PHP encoder (?)

The PHP Encoder allows to encode PHP
  scripts before distributing it.

What encoder are you looking for?

Free Php encoder


Regex search the name

Question: I need to get the name of a class
Class AAA.GitHub Extends %RegisteredObject
{
// some code

The part I want to find is AAA.GitHub. It is very easy to find: \bClass\b\s*(\w*(\.\w*)*)
However, sometimes people put comments on top of the class definition like this
/// some comments
/* some more
   Some more text
and more
*/
Class AAA.GitHub Extends %RegisteredObject
{
// some code

The problem is that these comments can contain the word class. How can I workaround this ?
Comment: *regular expressions work the same as everywhere* is a false statement, they work differently across languages/flavors.
Comment: What is the environment? Try `^Class\b\s*(\w*(\.\w*)*)`
Comment: It is Cache Object Script but regular expressions work the same as everywhere =)
Comment: @WiktorStribiżew, what about the second type of comments /* */? This regex doesn't cover that.
Answer: To avoid matching Class inside single-line comments, you may use a ^ start of line anchor:
(?m)^Class\b\s*(\w*(\.\w*)*)

The (?m) denotes a MULTILINE option that forces ^ to match the start of the line.
The pattern might be also written as (?m)^Class\s+(\w[\w.]*), I believe.
To avoid matching the word inside both multiline and single-line comments, match the multiline comments, but do not capture them:
(?m)/\*[^*]*\*+(?:[^/*][^*]*\*+)*/|^Class\s+(\w[\w.]*)

Or, in case the multiline comments always appear at the beginning of a line,
(?m)^\s*(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/|Class\s+(\w[\w.]*))

Your value will reside in Group 1. See the regex demo.
Comment: what about the second type of comments /* */? This regex doesn't cover that.
Comment: Note that in case the multiline comment is part of a string literal, you may get false positives. That is why I added the 3rd pattern that will only match multiline comments that apear at the line start positions that are safe for a regex.

Regex search the name


Read Http Request Authorization Header

Question: I am dealing with legacy code that runs on a very primitive server. The back-end code of the server can't be touched as its built-in. The main issue here is that I am trying to add an authorization header to my form post, and I don't know how to get that header from the server. But, I have noticed that the browser sends that Authorization header every time it makes a request. Is there a way to intercept that automatic header inserted by the browser and store it in local storage or some like that via javascript?
Example... if I call index.htm from the browser (actual navigation) I do see the authorization header there. However, it is not in the response header.
Thanks
Comment: The `Authorization` header would not be in the response.  That header is intended to be used to pass a token to the backend for authentication.  The response does not need that header.  As far as intercepting the web request, it depends on how it is being constructed, as far as if you are able to proxy some method on the xhr or fetch request to grab the data before letting it continue on.
Comment: Thanks for the response, but that is exactly why I am asking the question. I dont have control over server code, and I failed to intercept the request headers.
Answer: Check fetch
<code>fetch(url, {
   method: 'POST',
   body: formData,
   headers: {
     'Content-Type': 'application/json'
},
}).than((response) => {console.log(response.headers); /*your headers*/);
</code>
Comment: Thanks for the response. I am trying to intercept the request headers not response.
Comment: @alisanad you wont do this at runtime?
Only one way to do this - it create [serviceWorker](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API#Service_worker_concepts_and_usage) and add [listener](https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent) to featchEvent

Read Http Request Authorization Header


How can I listen to my electronic drums through my computer without additional delay?

Question: I recently got a Roland TD-11K, which has an USB output. I plugged it on my Windows 10 and the drivers were successfully installed. I went to the Sound Control Panel, checked "Listen to this device" on the properties of the TD-11K recording device, and it worked!... but with some delay. Impossible to play while listening.
I would like to know what is the best approach to connect my drum kit to my computer and listen to it with my headphones, also computer-plugged, with the same delay and quality as you would have playing with the headphones connected directly in the drum kit. The reason for this is that in the future, I intend to use VSTs to enhance the drum kit and some learning softwares. My drum kit is next to my computer so it makes sense to only use my computer for everything.
Does an audio interface accomplish this? I read a lot of tutorials teaching how to record yourself playing on the computer but none of them explicitly say if or how you also listen through the computer. I just started in the musical area and I'm afraid to spend more money without making sure it will fix this problem.
Thanks!
Comment: "also computer-plugged, with the same delay and quality as you would have playing with the headphones connected directly in the drum kit." - I bet it will be a long while before this is possible. The best shot so far is using ASIO4All or some other ASIO solution.
Answer:
Sound Control Panel, checked "Listen to this device"

This is most likely going to use the Windows WDM/directsound and "in shared mode" which tends to have a lot of latency.
For recording and playing you will want to use a low-latency driver: look for a Roland-provided ASIO driver or use ASIO4ALL (freeware). You will need software that can "use" the ASIO driver as well, and if you are going with VSTs in the future, you would be using a VST Host application that will be able to select ASIO for the input and output. There is a freeware application for windows called "VSTHost" (conveniently enough) that can get you started, and there are also open source ones available.
The trick is to set your ASIO buffers as low as they can go without hanging your application and/or having the audio crackle and break up. You probably are not going to get much below 8-11ms. I think 12-15ms is around when people tend to perceive the delay when playing.
Even with ASIO drivers, one thing I have found that can help reduce latency by a few milliseconds with e.g. on-the-motherboard Realtek audio is to find out what the default sampling is for the chipset and then try setting your ASIO driver settings to use that sampling rate.
Another thing to consider going forward is that you may be able to capture the midi signals instead of the raw audio and then you can re-kit the entire performance with a midi drum kit package.
Further, there are a lot of questions pertaining to ASIO and recording on this stack, so try a search. I "bolded" three terms which will help you google for more information.
Comment: be aware that ASIO requires exclusive use of the audio hardware, so you will not be able to listen to music from some other source on the same computer unless you have two audio devices, such as a separate sound card installed on an audio-capable motherboard. My second device is a "Stealth pedal" audio interface for guitar and a separate set of speakers for the computer
Answer: If the TD-11 is like the TD-15 (which I have and just tested this with), and you're connecting it to your computer via USB, the TD drum module is an audio interface. It provides both stereo audio input and output. You connect your headphones to the TD module and use the TD module as the audio output (AND input) in your computer's DAW software. You may need to install Roland's audio driver software for this to work properly. Since you talk about "VSTs", I suppose you're going to be using a DAW program that can utilize some low-latency technology such as ASIO. If you're on Mac, things are low-latency enabled and work by default.


Adding color components from (r,g,b,a) space

Question: If we define a color with transparency as $(r,g,b,a)$ (red,green,blue,alpha), with $r,g,b,a\in[0,1]$, how do we define $(r_1,g_1,b_1,a_1)+(r_2,g_2,b_2,a_2)$?
The definition must be closed, and must represent the computer science version of adding (blending) two alpha colors.
I tried taking alpha averages, but I don't seem to get closure. I also got that if $a_1r_1=a_2r_2$ then the displayed color is the same.
Addendum
I believe the answer is:
$$\big(\frac{a_1r_1+a_2r_2}{2},\frac{a_1g_1+a_2g_2}{2},\frac{a_1b_1+a_2b_2}{2},\frac{a_1+a_2}{2}\big)$$
Comment: it depends if you are additive (painting, starting from black and adding colors) or substractive (lighting, starting from white and filtering some colors)
Comment: in the additive model, $a = 0$ means black whatever $rgb$ is, and in the substractive model, $a=1$ means white (no filtering) whatever $rgb$ is
Answer: It depends on what kind of mixing you denote with "$+$". If you overlay layers then it is not even a commutative operation (e.g., if both are opaque, the top layer always wins). To really "mix" we should consider what we expect to happen with a coloured background behind the single and the mixed layer. I assume that $(r,g,b,a)$ covering $(r',b',g')$ results in $(ar+(1-a)r',ag+(1-a)g',ab+(1-a)b')$. For
$$ (r,g,b,a)=(r_1,g_1,b_1,a_1)+(r_2,g_2,b_2,a_2)$$
I assume we desire that $(ar+(1-a)r',ag+(1-a)g',ab+(1-a)b')$ should be the arithmetic average of $(a_1r_1+(1-a_1)r',a_1g_1+(1-a_1)g',a_1b_1+(1-a_1)b')$ and $(a_2r_2+(1-a_2)r',a_2g_2+(1-a_2)g',a_2b_2+(1-a_2)b')$.
This implies that $1-a=\frac{(1-a_1)+(1-a_2)}{2}$, i.e., $$a=\frac{a_1+a_2}2$$ (from the background contribution). And then from $ar=\frac{a_1r_1+a_2r_2}2$ etc. we find
$$r=\frac{a_1r_1+a_2r_2}{a_1+a_2} $$
i.e., weighted averages.
Comment: so the alpha component is $\frac{a_1^2+a_2^2}{a_1+a_2}$?
Comment: If you're averaging colors then no, it is as he wrote: $a = (a_1 + a_2)/2$.
Comment: what if $a_1+a_2=0$?
Comment: Then $a_1 = a_2 = 0$ and both are fully transparent, so there is nothing to do.
Answer: Say we have a solid background with color $\vec C_0 = (R_0,G_0,B_0)$, and we'd like to paint another color with transparency $(R,G,B,\alpha) = (\vec C,\alpha)$ over it. The result should be $\alpha \vec C + (1-\alpha) \vec C_0$. We can write this as a matrix equation (where the $\vec C$s are column vectors of $R,G,B$)
$$
\begin{bmatrix} \alpha \vec C + (1-\alpha) \vec C_0 \\ 1 \end{bmatrix}
=
\begin{bmatrix} (1-\alpha) I & \alpha \vec C \\ 0 & 1 \end{bmatrix}
\begin{bmatrix} \vec C_0 \\ 1 \end{bmatrix}.
$$
So if you have two colors with transparency $(C_1,\alpha_1)$ and $(C_2,\alpha_2)$, then the operation of painting the second and then the first would be represented by the matrix
$$
\begin{bmatrix} (1-\alpha_1) I & \alpha_1 \vec C_1 \\ 0 & 1 \end{bmatrix}
\begin{bmatrix} (1-\alpha_2) I & \alpha_2 \vec C_2 \\ 0 & 1 \end{bmatrix}
=
\begin{bmatrix} (1-\alpha_1)(1-\alpha_2) I & \alpha_1 \vec C_1 + (1-\alpha_1)\alpha_2 \vec C_2 \\ 0 & 1 \end{bmatrix}
$$
This shows that blending $(\vec C_1,\alpha_1)$ on top of $(\vec C_2,\alpha_2)$ gives the same result as blending just the single composite color $$ \left( \frac{\alpha_1 \vec C_1 + (1-\alpha_1) \alpha_2 \vec C_2)}{1 - (1 - \alpha_1)(1 - \alpha_2)}, 1 - (1 - \alpha_1)(1 - \alpha_2) \right). $$
One can see why it would be useful to represent transparent colors with premultiplied alpha $\vec c = \alpha \vec C$, and also to store $\beta = 1 - \alpha$ instead of $\alpha$ (so $\beta = 0$ is opaque and $\beta = 1$ is fully transparent). For then the form of the matrices is
$$
\begin{bmatrix} \beta I & \vec c \\ 0 & 1 \end{bmatrix}
$$
and composition formula becomes simply
$$ (\vec c_1,\beta_1), (\vec c_2,\beta_2) \mapsto (\vec c_1 + \beta_1 \vec c_2, \beta_1 \beta_2) $$

Addendum: If you are really mixing colors rather than overlaying, then we can simply average the color matrices:
$$
\frac{1}{2} \left(
\begin{bmatrix} (1-\alpha_1) I & \alpha_1 \vec C_1 \\ 0 & 1 \end{bmatrix} +
\begin{bmatrix} (1-\alpha_2) I & \alpha_2 \vec C_2 \\ 0 & 1 \end{bmatrix}
\right) =
\begin{bmatrix} \bigl(1 - \frac{\alpha_1+\alpha_2}{2}\bigr)I & \frac{\alpha_1 \vec C_1 + \alpha_2 \vec C_2}{2} \\ 0 & 1 \end{bmatrix}
$$
to get
$$(\vec C_1,\alpha_1), (\vec C_2,\alpha_2) \mapsto \left( \frac{\alpha_1 \vec C_1 + \alpha_2 \vec C_2}{\alpha_1 + \alpha_2}, \frac{\alpha_1 + \alpha_2}{2} \right). $$
or in terms of $\vec c$ and $\beta$:
$$(\vec c_1,\beta_1), (\vec c_2,\beta_2) \mapsto
 \left(\frac{\vec c_1 + \vec c_2}{2},\frac{\beta_1 + \beta_2}{2}\right).$$

Moral: Using premultiplied alpha and $\beta = 1-\alpha$ makes things a lot easier.


Cognos - List report (Relational database) - Summary limitations

Question: I have a Cognos report with Data like so.
User    Units   TimeInHours  UnitsPerHour
Smith    10      1            10
Smith    30      2            15

In my report I group by user.  I can do a total on Units and Hours, but how can i summarize units per hour?
Its not the average 10+15/2 = 12.5,
its (10+30)/(1+2) = 13.33
In my report, UnitsPerHour is a calculation.  It's just Units divided by hours.
I don't really need to summarize my unitsPerHour column at all.  I need to perform a calculation based on my summary of other columns, but that appears to be impossible.
Answer: You can build it yourself if you don't want to total the other columns.  Add a query calculation in your footer.  It will be total(Units for report) / total(TimeinHours for report).
Comment: It was that simple.  Not sure why I didn't expect that to work.  Thanks,  =)


Codeception\Exception\InjectionException : Service di is not defined and can't be accessed from a test

Question: Testing started at 下午5:45 ...
/usr/local/bin/php -dxdebug.remote_enable=1 -dxdebug.remote_mode=req -dxdebug.remote_port=9001 -dxdebug.remote_host=127.0.0.1 /var/www/example/vendor/phpunit/phpunit/phpunit --no-configuration --filter "/(::testMerlinTemplate)( .*)?$/" tests\jobs\SettlementJobTest /var/www/example/tests/unit/jobs/SettlementJobTest.php --teamcity
PHPUnit 7.1.4 by Sebastian Bergmann and contributors.

Codeception\Exception\InjectionException : Service di is not defined and can't be accessed from a test
 /var/www/example/vendor/codeception/base/src/Codeception/Test/Metadata.php:191
 /var/www/example/vendor/codeception/base/src/Codeception/Test/Unit.php:47

Answer: You're trying to run a Codeception unit test using phpunit, the di (dependency injection) service is not available in the latter. You should run the test using the Codeception CLI, e.g.:
codecept run /var/www/example/tests/unit/jobs/SettlementJobTest.php

Comment: The test I'm getting this error on has run fine many times in PhpStorm, but is now throwing this error.
Comment: @BobRay you should check what PhpStorm is executing under the hood, most likely it reverted back to a phpunit run configuration (which is the default for unit tests); you might need to (re-)add a Codeception run configuration.
Comment: I had issue, that I was echoing version of my software in `bootstrap.php`, this confused PHPStorm and was unable to detect codeception version and reverted to phpunit.


Joint/disjoint and dependent/independent events

Question: I'm trying to understand joint probabilities and dependence/independence.  I've used examples with coins and cards, but when it comes to real life, I mix them up again.
I want to think of real life examples that are:

Disjoint/independent
Disjoint/dependent
Joint/independent
Joint/dependent

Here are my examples, but for the first one I'm stuck.

?
Night and day
Voting for Trump and liking milk
Voting for Trump and being pro-gun

Are these correct?  And what are some real life examples of independent and disjoint events?
Answer: Disjoint/independent: Disjoint events are only statistically independent if each outcome has probability zero or one (which is a trivial case).  That is the reason you are having trouble finding an example of this case; it is a pathological case that is not important.
Non-disjoint/independent: You need to be careful with this one, since causal independence does not imply statistical independence.  As a rough rule of thumb (which is slightly exaggerated, but not much) everything is correlated with everything.  Although they are unlikely to be causally related, it would surprise me if voting-preference is uncorrelated with milk-consumption.  It is more likely that rates of milk-consumption differ for Trump-voters and non-Trump voters, for all sorts of indirect reasons.  For example, rates of milk-consumption among US adults differ by age and sex, and voting patterns also differ by age and sex.  In particular, within the population of US adults, males drink more milk, and are also more likely to vote for Trump, so if this is one of the main indirect effects, I would expect that there would be some small positive correlation between milk-consumption and voting for Trump.
Comment: Technically isn't there also the trivial case were they both have probability zero? They are still disjoint technically because their intersection is still empty.
Comment: That is true in general, but I was assuming he is talking about binary events, where they partition the sample space.  In the latter case one event having probability zero means that the other has probability one.  You are right though: in the more general case beyond a binary partition, you could have multiple disjoint events that don't cover the sample space and each have probability zero.  I have edited to cover the more general case.
Answer: You're stuck because being both disjoint and independent is impossible (except for the corner case Ben points out where one of the events never happens under any circumstances). Disjoint means the two events are mutually exclusive -- if one happens than the other can't happen. Independent means if one happens it doesn't affect whether or not the other happens. You can't simultaneously prevent the other from happening and also not affect whether it happens. Disjoint implies dependent.
Your other examples look correct (at least in spirit, I have not surveyed voter milk drinking habits).


Little help with prediction

Question: I have energy consumption data from a device for the past two weeks.
I have to predict energy consumption of this device for another week.
I am not sure how to forecast this.
Does anybody know how to do that?
If there a way to do that in R? I've just started learn the R language.
Comment: The simplest prediction is that it will be exactly the same next week. Any other prediction requires assumptions, which you haven't stated...
Comment: @Harvey - "exactly the same next week" also involves assumptions; assumptions of some kind are inescapable. $\quad$ Kacu - Before you consider R, you need to consider what problem you're actually solving (in explicit terms, not merely 'predict energy consumption') -- you need some kind of model/assumptions. You can't just predict out of thin air, you need to know, infer - or at least assume - something about what is going on. When you say you have energy consumption for two weeks, is this weekly consumption? Daily consumption? Hourly consumption? What other information/context do you have?
Comment: I'm sorry but I can't agree with the advice to "start in Excel." I say, force yourself through the learning curve while you have motivation and time, so that you already can do it easily when those things are lacking.
Comment: Why not start in Excel?  Once you know what you want to do in Excel and how you want to do it, then you can move to R.  If this is a one-off problem that you're doing out of interest, R is (in my opinion) a bit too steep of a learning curve.  In any event, forecasting is about how, not the package.
Comment: I have daily energy consumption from past two weeks and I have to predict for another week. After that I have to make a plot in R with what I predict in that week (from Monday -> Sunday). Assume the same consumption is not good for me. I need something that predict data would be a little different from past data.
Answer: The answer depends on the model you have in mind. For basic exponential smoothing, there's an excellent write-up here that is easy to read and has lots of code demos. It's part of an e-book on using R to analyze time series for people with minimal R and programming experience.
Comment: (+1) Fair enough.  I see from the reference you've given that yes, perhaps it is actually not too hard anymore for even a casual user to step into R and do things right.  Thanks for challenging.
Comment: +1 There's also [this excellent book on forecasting](https://www.otexts.org/fpp/), which also uses R.

Little help with prediction


Upload image from Android to WCF service

Question: I'm looking for a complete example for uploading an image + some text fields from Android to a WCF service. I've been searching for days without finding any useful examples. What I need is the code for both the client and server.
I've been able to make it work with JSON and Base64 encoding the image as a string, but this is way too slow with images around 500KB. What I'm looking for has to be efficient. Probably using a stream.
Can anyone please give me a complete sample code? I've seen a lot of snippets on each side, but not a complete sample. From getting the image from a path on the phone to posting it to the server and consuming it on the server in C#? How to get the image as a bytearray on the server and the text into string variables?
Thanks for listening.
Comment: I knew that kind of response would come...I'm not asking for a lot though. This should be possible to do in what, 10-15 loc? I've seen a lot more posted here than that. All I want is a example so I don't have to guess. Is that so bad?
Comment: No way you will get people to code for you here. Ask a specific question and you will get an answer.
Answer: For setting up WCF streaming on the server side see : http://msdn.microsoft.com/en-us/library/ms789010.aspx
You could also try just using basic http binding and MTOM.
For the android part you will need to get help from someone else, sorry.


Windows 2012 Service Removal Log

Question: I have a production server where an application is experiencing an issue.
The psexec service is marked for deletion and I want to try and tie the deactivation of the service to the start of the issue.
Where would the removal of the service be logged or what would be the ID in the event log?
Thanks
Comment: just filter application log with name
Answer: If your application relies on the psexec service, then it would make sense that it is experiencing issues if the psexec service is marked for deletion.
PSEXEC uses a temporary service to launch the process (usually) remotely. Once the remote process exists, the psexec service is removed again.
Unfortunately, Windows doesn't really like services being created and removed a lot, and after a certain number of times (not sure what the number is) of the same service being installed & uninstalled, it will mark the service for deletion and lock it.
At that point you have to restart the service, that is the only way I'm aware of that will delete the service and let you re-create it.

Windows 2012 Service Removal Log


Better antivirus for Windows Server 2008 R2 x64 VPS

Question: I have only one VPS with Windows Server 2008 R2 x64 and want to buy an Antivirus. I tried NOD32 but they do not give less than 5 users in business edition (I have only one server). Kaspersky may be another solution but whether should i go for Internet Security or Anti-virus?
I have few website hosted on this server and user have ability to upload .jpg, .gif, .zip files in few of the folders.
Apart from above two any other suggestions on Antivirus that works well on above configuration and available for only one user?
Thanks
Answer: I always liked ClamWin.  May or may not meet your requirements though.  It doesn't scan everything all the time, so performance is better, but that might be something you need.  Interestingly enough, I see it performed horribly on an AV "roundup" test a few months ago, but the previous year it was a top performer.  Not sure about the status at this time though.  I'm pretty suspicious of those tests though.
Answer: Personally I like AVG, and you can buy it on a per machine basis.  The only downside is that from time to time when they update their scanner it requires a machine reboot so you have to schedule those for convenient times.
Comment: AVG is good, but it is not supported in Windows Server 2008 R2.
Answer: We like Trend Worry Free (hosted on their server or yours), we can add all of our clients to one control panel and manage changes from there, no AV servers at client sites.  This may help with the single user since it can handle multiple sites.
Comment: I'm going to check that out for my local network.
Answer: Kaspersky Internet Security is the consumer version. It doesn't support server OS's, so Windows 2008 R2's right out.
You'd be looking at their Kaspersky Business Space Security suite, in order to get the Kaspersky Anti-Virus for Windows Servers product, which supports Windows 2008 R2  Unfortunately you normally can only buy these in bundles of 10+ licenses, and will start at around £250. Kaspersky might be able to do you a deal though.
Answer: ESET NOD32 Antivirus 4 is sold on single server basis. I just spoke with sales and have installed a trial on the one server that needs AV. Their web site is really confusing though. I thought the same thing until I called them.
So far it seems fine, though I've only been using it for a short time.


Creation of products completely except the admin

Question: I am using Drupal Commerce and I need to let my users to create products without the product display.
I thus adjusted the permissions, but when a user creates a product, 1/ the url is the one of the admin admin/commerce/products/add/1 and 2/ once the created product, the user has a access denied.
My question: how to let the users to create products completely except the admin (modification of the url etc.) ?
Comment: Are you needing editing capabilities as well or just the initial creation?
Comment: thanks nvahalik, just the initial creation. The same thing as the creation of a node by a user
Answer: One option is to use a custom node bundle along with Rules. Allow the users to create the new node type. Then, when the node is being saved, use Rules (or a custom module) to take the values that were entered into the node form and carry them over to a product and save it.


how x y and z become equal in this solution?

Question: I'm trying to understand an example given in my book but not able to understand it as I am quite weak in mathematics.
In the below images I don't get how x, y and z become equal to each other. Please help!
Comment: it is a condition,"at x=y=z"
Comment: I think they simply don't. It seems to me that you're just tasked to verify that a certain partial derivative is equal to something when you evaluate it on $\{x=t\wedge y=t\wedge z=t\}$.
Comment: = show that when
Answer: You have to show that at $x=y=z$, the derivative is what it is. That means you need to prove the statement

If $x=y=z$, then $\frac{\partial d^2z}{\partial x\partial y} = ...$

And any time you prove a statement of the type "If $A$, then $B$", you do it by assuming $A$ is true and, from that, proving that $B$ is true.
Comment: can you please explain me this
Comment: @user3788135 I just did. What part of the explanation is unclear to you?


Drupal 7 theme similar to Wordpress Twenty Fourteen theme?

Question: I'm looking for a Drupal 7 theme similar to the wordpress theme Twenty Fourteen. The main factors that I would like to find in a drupal theme are

the image grid for posts similar to the grid pictured on the theme page
the menu locked into the side
responsive

I was hoping to find something with as little modification needed as possible, but I'm not opposed to creating a subtheme and doing some customization. I tried searching some drupal theme repositories like the offerings available on themeforest and template monster but I haven't found anything that caught my eye.
Answer: You're going to find Drupal is pretty limited on well made pre-built themes. If you're looking for a good grid system, NineSixty and Boostrap provide a good base to build upon. As far as menu settings and post output, this is typically custom to each site. The post output, for instance, would rely on a custom content type and View to display this information.


Exportar grande quantidade de dados para Excel

Question: Tenho um DataGridView onde nele há uma média de umas 50 mil linhas onde essas deveriam ser exportadas para um arquivo Excel.
Porém pelo fato da enorme quantidade de dados a aplicação simplesmente congela e não finaliza, estou utilizando a biblioteca Microsoft.Office.Interop.Excel  o código do botão é esse:
 private void btnExportar_Click(object sender, EventArgs e)
    {
        //exportando arquivos para o excel
        if (dgvDados.Rows.Count > 0)
        {
            try
            {
                XcelApp.Application.Workbooks.Add(Type.Missing);
                for (int i = 1; i < dgvDados.Columns.Count + 1; i++)
                {
                    XcelApp.Cells[1, i] = dgvDados.Columns[i - 1].HeaderText;
                }
                //
                for (int i = 0; i < dgvDados.Rows.Count - 1; i++)
                {
                    for (int j = 0; j < dgvDados.Columns.Count; j++)
                    {
                        XcelApp.Cells[i + 2, j + 1] = dgvDados.Rows[i].Cells[j].Value.ToString();
                    }
                }
                //
                XcelApp.Columns.AutoFit();
                //
                XcelApp.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro : " + ex.Message);
                XcelApp.Quit();
            }
        }
    }

Há alguma maneira de exportar algo desse nível para o excel?
Comment: Tenta criar paginações, ex: se são 50 mil linhas faz com que ele vá ao banco e busque a cada 10 mil, abrindo várias requisições dentro de cada paginação.
Comment: A aplicação está congelando porque está processando bastante coisa na Thread principal, se você criar uma nova thread para Executar isso a aplicação não vai congelar
Comment: Explique melhor o que você quer dizer com "trava", ocorre algum erro, o processo não termina ou só demora e a interface do usuário congela até a finalização?
Comment: @LeandroAngelo a interface congela, mas eu nunca vi ela finalizar e eu já deixei questão de 1h e ainda sim continua congelada
Comment: debugando, você mediu quanto tempo está demorando por linha, apesar do grande volume não tem tanta complexidade assim...
Comment: fiz o teste agora por linha acabou sendo muito variável, por exemplo quando abro a aplicação e exporto pela primeira vez demora cerca de *5s* mas depois de executado a primeira vez ele leva em torno de 0,5s. Testei com 7mil linhas e demorou 15 min
Comment: o problema mesmo é a aplicação ficar congelada sem poder fazer nada, acredito que thread seja realmente uma boa opção mas não conheço mt bem o recurso vou dar uma pesquisada
Comment: mas ainda sim se seguir por esse raciocínio 7 mil linhas = 15 min 50 mil linhas =~ 2h é muito tempo
Answer: Você pode usar o clipboard para fazer a operação. Para essa quantidade de dados também vai demorar um pouco, porém vai ser bem mais rápido que copiar célula por célula
    private void btnExportar_Click(object sender, EventArgs e)
    {
        if (dgvDados.Rows.Count == 0) return;

        bool RowHeadersVisible = dgvDados.RowHeadersVisible;

        //Seleciona todas linhas de dgvDados e passa para o clipboard
        dgvDados.RowHeadersVisible = false;
        dgvDados.SelectAll();
        DataObject dataObj = dgvDados.GetClipboardContent();
        if (dataObj != null) Clipboard.SetDataObject(dataObj);

        dgvDados.RowHeadersVisible = RowHeadersVisible;

        //Declara as variáveis para usar para referir aos elementos do excel
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;

        //Cria uma nova instanci do excel
        xlexcel = new Excel.Application();
        xlexcel.Visible = true;

        //Adiciona um workbook
        xlWorkBook = xlexcel.Workbooks.Add(System.Reflection.Missing.Value);

        //Pega a primeira planilha do workbook
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        //Seleciona a primeira célula
        Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
        CR.Select();

        //Cola o conteúdo do clipboard
        xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
    }

Comment: muito bom, o que era quase um estimado de 3h agora faz em 45s melhora gritante, desde modo ele seleciona todas as linhas de uma só vez é muito mais eficiente
Comment: Pela quantidade de dados seria melhor usar [OleDb](https://docs.microsoft.com/pt-br/dotnet/api/system.data.oledb?view=netframework-4.8), um [exemplo aqui](https://www.codeproject.com/Articles/8500/Reading-and-Writing-Excel-using-OLEDB).
Comment: que biblioteca eu devo chamar com o `using` para utilizar o namespace `Excel` ?
Comment: https://docs.microsoft.com/pt-br/dotnet/api/microsoft.office.interop.excel?view=excel-pia
Answer: Se o seu objetivo é não congelar a interface do usuário, você pode iniciar uma nova Task
para realizar essa tarefa, mas isso não vai resolver a questão do tempo para a execução.
private void btnExportar_Click(object sender, EventArgs e)
{
    //exportando arquivos para o excel
    if (dgvDados.Rows.Count > 0)
    {
       var task = Task.Factory.StartNew(() =>
        {
            try
            {

                XcelApp.Application.Workbooks.Add(Type.Missing);
                for (int i = 1; i < dgvDados.Columns.Count + 1; i++)
                {
                    XcelApp.Cells[1, i] = dgvDados.Columns[i - 1].HeaderText;
                }
                //
                for (int i = 0; i < dgvDados.Rows.Count - 1; i++)
                {
                    for (int j = 0; j < dgvDados.Columns.Count; j++)
                    {
                        XcelApp.Cells[i + 2, j + 1] = dgvDados.Rows[i].Cells[j].Value.ToString();
                    }
                }
                //
                XcelApp.Columns.AutoFit();
                //
                XcelApp.Visible = true;

                MessageBox.Show("Sucesso : Exportação concluída");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro : " + ex.Message);
                XcelApp.Quit();
            }
        });
    }
}