How can I detect if the currently running app was installed from the app store?

Question: Is there a way in iOS to programmatically check if the currently running app was installed from the iOS App Store? This is in contrast to an app that was run via Xcode, TestFlight, or any non-official distribution source.
This is in the context of an SDK that doesn't have access to the app's source code.
To be clear - I am looking for some signature, so to speak, given to the app (presumably by Apple), that will, without dependence on any preprocessor flags or other build configurations, be accessible to any application at run time.
Comment: To be clear - are you looking for some signature, so to speak, given to the app (presumably by Apple), that will, without dependence on any preprocessor flags or other build configurations, be accessible to any application at run time?
Comment: Please clarify. What do you mean by SDK? Are you building a library? Are you building an SDK that outputs an App à la Titanium? In that case, you're still building an app anyway, so while you might be prevented from accessing your "sub-app" source code, you're definitely in control of the running app.
Comment: @CarlVeazey Yes, that is exactly is.
Comment: @magma No, I'm am building a pure SDK that other developers download and integrate into their Xcode builds.
Answer: Apps downloaded from the App Store have a iTunesMetadata.plist file added by the store:
NSString *file=[NSHomeDirectory() stringByAppendingPathComponent:@"iTunesMetadata.plist"];
if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
    // probably a store app
}

Perhaps you might want to check if this file exists.
Update:
In iOS8, the application bundle has been moved. According to @silyevsk, the plist is now one level above [the new application main bundle path], at /private/var/mobile/Containers/Bundle/Application/4A74359F-E6CD-44C9-925D-AC82EB5EA837/iTunesMetadata.plist, and unfortunately, this can't be accessed from the app (permission denied)
Update Nov 4th 2015:
It appears that checking the receipt name can help. It must be noted that this solution is slightly different: it doesn't return whether we're running an App Store app, but rather whether we're running a beta Testflight app. This might or might not be useful depending on your context.
On top of that, it's a very fragile solution because the receipt name could change at any time. I'm reporting it anyway, in case you have no other options:
// Objective-C
BOOL isRunningTestFlightBeta = [[[[NSBundle mainBundle] appStoreReceiptURL] lastPathComponent] isEqualToString:@"sandboxReceipt"];

// Swift
let isRunningTestFlightBeta = NSBundle.mainBundle().appStoreReceiptURL?.lastPathComponent=="sandboxReceipt"

Source: Detect if iOS App is Downloaded from Apple's Testflight
How HockeyKit does it
By combining the various checks you can guess whether the app is running in a Simulator, in a Testflight build, or in an AppStore build.
Here's a segment from HockeyKit:
BOOL bit_isAppStoreReceiptSandbox(void) {
#if TARGET_OS_SIMULATOR
  return NO;
#else
  NSURL *appStoreReceiptURL = NSBundle.mainBundle.appStoreReceiptURL;
  NSString *appStoreReceiptLastComponent = appStoreReceiptURL.lastPathComponent;

  BOOL isSandboxReceipt = [appStoreReceiptLastComponent isEqualToString:@"sandboxReceipt"];
  return isSandboxReceipt;
#endif
}

BOOL bit_hasEmbeddedMobileProvision(void) {
  BOOL hasEmbeddedMobileProvision = !![[NSBundle mainBundle] pathForResource:@"embedded" ofType:@"mobileprovision"];
  return hasEmbeddedMobileProvision;
}

BOOL bit_isRunningInTestFlightEnvironment(void) {
#if TARGET_OS_SIMULATOR
  return NO;
#else
  if (bit_isAppStoreReceiptSandbox() && !bit_hasEmbeddedMobileProvision()) {
    return YES;
  }
  return NO;
#endif
}

BOOL bit_isRunningInAppStoreEnvironment(void) {
#if TARGET_OS_SIMULATOR
  return NO;
#else
  if (bit_isAppStoreReceiptSandbox() || bit_hasEmbeddedMobileProvision()) {
    return NO;
  }
  return YES;
#endif
}

BOOL bit_isRunningInAppExtension(void) {
  static BOOL isRunningInAppExtension = NO;
  static dispatch_once_t checkAppExtension;

  dispatch_once(&checkAppExtension, ^{
    isRunningInAppExtension = ([[[NSBundle mainBundle] executablePath] rangeOfString:@".appex/"].location != NSNotFound);
  });

  return isRunningInAppExtension;
}

Source: GitHub - bitstadium/HockeySDK-iOS - BITHockeyHelper.m
A possible Swift class, based on HockeyKit's class, could be:
//
//  WhereAmIRunning.swift
//  https://gist.github.com/mvarie/63455babc2d0480858da
//
//  ### Detects whether we're running in a Simulator, TestFlight Beta or App Store build ###
//
//  Based on https://github.com/bitstadium/HockeySDK-iOS/blob/develop/Classes/BITHockeyHelper.m
//  Inspired by https://stackoverflow.com/questions/18282326/how-can-i-detect-if-the-currently-running-app-was-installed-from-the-app-store
//  Created by marcantonio on 04/11/15.
//

import Foundation

class WhereAmIRunning {

    // MARK: Public

    func isRunningInTestFlightEnvironment() -> Bool{
        if isSimulator() {
            return false
        } else {
            if isAppStoreReceiptSandbox() && !hasEmbeddedMobileProvision() {
                return true
            } else {
                return false
            }
        }
    }

    func isRunningInAppStoreEnvironment() -> Bool {
        if isSimulator(){
            return false
        } else {
            if isAppStoreReceiptSandbox() || hasEmbeddedMobileProvision() {
                return false
            } else {
                return true
            }
        }
    }

    // MARK: Private

    private func hasEmbeddedMobileProvision() -> Bool{
        if let _ = NSBundle.mainBundle().pathForResource("embedded", ofType: "mobileprovision") {
            return true
        }
        return false
    }

    private func isAppStoreReceiptSandbox() -> Bool {
        if isSimulator() {
            return false
        } else {
            if let appStoreReceiptURL = NSBundle.mainBundle().appStoreReceiptURL,
                let appStoreReceiptLastComponent = appStoreReceiptURL.lastPathComponent
                where appStoreReceiptLastComponent == "sandboxReceipt" {
                    return true
            }
            return false
        }
    }

    private func isSimulator() -> Bool {
        #if arch(i386) || arch(x86_64)
            return true
            #else
            return false
        #endif
    }

}

Gist: GitHub - mvarie/WhereAmIRunning.swift
Update Dec 9th 2016:
User halileohalilei reports that "This no longer works with iOS10 and Xcode 8.". I didn't verify this, but please check the updated HockeyKit source (see function bit_currentAppEnvironment) at:
Source: GitHub - bitstadium/HockeySDK-iOS - BITHockeyHelper.m
Over time, the above class has been modified and it seems to handle iOS10 as well.
Update Oct 6th 2020:
Hockey has been deprecated/abandoned and replaced by Microsoft's AppCenter SDK.
This is their App Store / Testflight build detection class (link to repository below code):
MSUtility+Environment.h :
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#import <Foundation/Foundation.h>

#import "MSUtility.h"

/*
 * Workaround for exporting symbols from category object files.
 */
extern NSString *MSUtilityEnvironmentCategory;

/**
 *  App environment
 */
typedef NS_ENUM(NSInteger, MSEnvironment) {

  /**
   *  App has been downloaded from the AppStore.
   */
  MSEnvironmentAppStore = 0,

  /**
   *  App has been downloaded from TestFlight.
   */
  MSEnvironmentTestFlight = 1,

  /**
   *  App has been installed by some other mechanism.
   *  This could be Ad-Hoc, Enterprise, etc.
   */
  MSEnvironmentOther = 99
};

/**
 * Utility class that is used throughout the SDK.
 * Environment part.
 */
@interface MSUtility (Environment)

/**
 * Detect the environment that the app is running in.
 *
 * @return the MSEnvironment of the app.
 */
+ (MSEnvironment)currentAppEnvironment;

@end

MSUtility+Environment.m :
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#import "MSUtility+Environment.h"

/*
 * Workaround for exporting symbols from category object files.
 */
NSString *MSUtilityEnvironmentCategory;

@implementation MSUtility (Environment)

+ (MSEnvironment)currentAppEnvironment {
#if TARGET_OS_SIMULATOR || TARGET_OS_OSX || TARGET_OS_MACCATALYST
  return MSEnvironmentOther;
#else

  // MobilePovision profiles are a clear indicator for Ad-Hoc distribution.
  if ([self hasEmbeddedMobileProvision]) {
    return MSEnvironmentOther;
  }

  /**
   * TestFlight is only supported from iOS 8 onwards and as our deployment target is iOS 8, we don't have to do any checks for
   * floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1).
   */
  if ([self isAppStoreReceiptSandbox]) {
    return MSEnvironmentTestFlight;
  }

  return MSEnvironmentAppStore;
#endif
}

+ (BOOL)hasEmbeddedMobileProvision {
  BOOL hasEmbeddedMobileProvision = !![[NSBundle mainBundle] pathForResource:@"embedded" ofType:@"mobileprovision"];
  return hasEmbeddedMobileProvision;
}

+ (BOOL)isAppStoreReceiptSandbox {
#if TARGET_OS_SIMULATOR
  return NO;
#else
  if (![NSBundle.mainBundle respondsToSelector:@selector(appStoreReceiptURL)]) {
    return NO;
  }
  NSURL *appStoreReceiptURL = NSBundle.mainBundle.appStoreReceiptURL;
  NSString *appStoreReceiptLastComponent = appStoreReceiptURL.lastPathComponent;

  BOOL isSandboxReceipt = [appStoreReceiptLastComponent isEqualToString:@"sandboxReceipt"];
  return isSandboxReceipt;
#endif
}

@end

Source: GitHub - microsoft/appcenter-sdk-apple - MSUtility+Environment.m
Comment: @MichaelDautermann : good point! However in iOS NSHomeDirectory() behaves differently: "In iOS, the home directory is the application's sandbox directory. In OS X, it is the application's sandbox directory or the current user's home directory (if the application is not in a sandbox)"
Comment: Actually, it's one level above, at /private/var/mobile/Containers/Bundle/Application/4A74359F-E6CD-44C9-925D-AC82EB5EA837/iTunesMetadata.plist, and unfortunately, this can't be accessed from the app (permission denied)
Comment: "`NSHomeDirectory()`" would return a path of "`~/iTunesMetadata.plist`", which sounds like it is *outside* the app sandbox.  Are you certain this is the right path to check?
Comment: Will try this out and verify if it works or not, thanks for the suggestion.
Comment: @kevlar - this stopped working for me in ios8, did you see the same behavior
Comment: @ekeren in iOS8, apps are now in a different folder, like `/private/var/mobile/Containers/Bundle/Application/4A74359F-E6CD-44C9-925D-AC82EB5EA837/whatever.app` — see updated answer
Comment: @silyevsk thank you, I have modified the answer accordingly.
Comment: Does it work with xcode7 and iOS9 and for the VPP Store as well? (Both app states hidden and not hidden vpp apps?)
Answer: If you're talking about your own app, you could add a state that returns true if it was build as part of a Store version (e.g. a compiler conditional) and false in every other case.
If you're talking about another app, it's not easy or straightforward (or maybe not even possible) to query other apps outside of your sandbox.
Comment: Thanks for your quick response Michael. I've edited my question to specify that I'm building an SDK, so I don't have direct access to the app's code. Do you know any workaround for that?
Comment: > If you're talking about your own app, you could add a state that returns true if it was build as part of a Store version (e.g. a compiler conditional) and false in every other case.
You don't explain how, which is actually the real question here.
Answer: Since the code by @magma no longer works IOS11.1 Here is a bit of a long winded solution.
We check the app version on the app store and compare it to the version in the Bundle
static func isAppStoreVersion(completion: @escaping (Bool?, Error?) -> Void) throws -> URLSessionDataTask {
    guard let info = Bundle.main.infoDictionary,
      let currentVersion = info["CFBundleShortVersionString"] as? String,
      let identifier = info["CFBundleIdentifier"] as? String else {
        throw VersionError.invalidBundleInfo
    }
    let urlString = "https://itunes.apple.com/gb/lookup?bundleId=\(identifier)"
    guard let url = URL(string:urlString) else { throw VersionError.invalidBundleInfo }
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
      do {
        if let error = error { throw error }
        guard let data = data else { throw VersionError.invalidResponse }
        let json = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) as? [String: Any]
        guard let result = (json?["results"] as? [Any])?.first as? [String: Any], let appStoreVersion = result["version"] as? String else {
          throw VersionError.invalidResponse
        }
        completion(appStoreVersion == currentVersion, nil)
      } catch {
        completion(nil, error)
      }
    }
    task.resume()
    return task
}

Called like this
DispatchQueue.global(qos: .background).async {

    _ = try? VersionManager.isAppStoreVersion { (appStoreVersion, error) in
      if let error = error {
        print(error)
      } else if let appStoreVersion = appStoreVersion, appStoreVersion == true {
         // app store stuf
      } else {
        // other stuff

      }
    }
}

enum VersionError: Error {
    case invalidResponse, invalidBundleInfo
}

Comment: If the version on the app store is higher than the bundle version you can deduce that it is an older version not yet updated. If it is the same it is an updated version and if the bundle is higher than the app store then you are running an unreleased or debug version.
Comment: Ok, and what will be happened when application version is not last?
Comment: I do not really understand your question. My code just compares the bundle version to the version on the app store.
Comment: When new version publishes in store, not all users updates it immediately (old iOS version, partically update setting in App Store Connect etc). So, user with old version will see debug-version behaviour.
Comment: This doesn't answer the question. Comparing versions doesn't do anything about that issue whatsoever. Context: An app can be distributed in different ways as a release version: App Store, TestFlight Beta, Firebase, dev build on device, etc.
Answer: My observation is when a device connected to Xcode, and then we open Organiser, switch to Devices pane it will list all Applications which is not installed from App Store. So what you have to do is download Xcode, then connect your device, go to Devices pane and see which all applications are installed from non-App Store sources. This is the simplest solution.
Comment: I believe Kevlar wants to be able to do this programatically -- that is, from within his code -- and not manually via Xcode.


MDT: workgroup installs?

Question: Im trying to use MDT to capture and reproduce a win7 image with some customizations (extra SW). Ive tried both the 'scripts\litetouch.vbs' process and the 'litetouchpe_x64.iso' (pxe boot) approach. Neither seems to get very far.
Im wondering if the issue is that my MDT machine is a domain member whereas the system Im trying to image isn't (and needs to remain a workgroup member). I can get to the 'scripts' folder on the MDT system only if I use a domain login / pw. It appears to start some process but never does anything (no error messages, either)
The PXE boot process seems to take my domain login info, then it reboots but it reboots to the original OS and no 'imaging' takes place.
Am I going down the wrong path from the get-go?
Answer: It is entirely possible to create a non domain joined system from a domain joined MDT instance. I do it fairly regularly for XP and 2008R2 systems. I don't use it for 7 all that often.
It sounds like the OS installation process isn't running for some reason from your MDT server. I have inadvertently moved or deleted items within the task sequence that caused this behavior.
Try creating a new totally stock task sequence using the same base OS WIM file and go from there. If that doesn't do it there is likely something wrong with your base image.

MDT: workgroup installs?


Boost json parser with a ptree within a ptree

Question: So I am working on an assignment and I need to parser several properties into a json to send over a network.  Here is what the final value should look like.
{"__type":"Login:#Messages","Identity":{"sNumber":"value","Alias":"value","FirstName":"value","LastName":"value"}}

so the code I have is
boost::property_tree::ptree pt;
pt.put("__type", "Login:#Messages");
pt.put("Identity", myPlayer.Encode());

myplayer is a class that contains snumber, alias, firstname, lastname.  the encode function returns a ptree but when I go to write_json it seems it doesnt know how to handle a ptree in a ptree.
I tried parsing myPlayer into a json and puting that in the tree but it gives me this
   {"__type":"Login:#Messages","Identity":"{\"sNumber\":\"value\",\"Alias\":\"value\",\"FirstName\":\"value\",\"LastName\":\"value\"}"}

so how to I get boost to parse a ptree such that it can do a ptree in a ptree or doesnt add the escapes for the quotes and doesnt put the Identity property's value as a string?  Thanks
Comment: Nevermind I figured it out.  I need to do pt.put("Identity.sNumber", value)
Comment: Can you turn that into a proper answer? I think your question has a real value.
Answer: Okay so boost ptree to json is a little weird but I figured out how to make subtrees.
Example output:  {"__type":"Login:#Messages","Identity":"{\"sNumber\":\"value\"}}
Solution:
boost::property_tree::ptree pt;
pt.put("__type", "Login:#Messages");
pt.put("Identity.sNumber", value);

Solution 2:
boost::property_tree::ptree pt;
boost::property_tree::ptree subtree;
subtree.put("sNumber", value);
pt.put("__type", "Login:#Messages");
pt.put_child("Identity", subtree);

These 2 examples will both make a subtree in the ptree.


Enviar arquivos anexados por form de email

Question: tenho um modelo de formulario de contato que uso em meus sites. Ele usa JS para validar o conteudo dos campos e PHP para enviar os dados pro email. Gostaria de saber se é possivel enviar arquivos (imagens) anexados usando esse modelo. Agradeco desde já a todos. Deixo aqui os codigos:
FORMULÀRIO HTML:
<form name="sentMessage" id="contactForm" novalidate>

                        Nome Completo*
                        <input type="text" class="form-control" id="name" required data-validation-required-message="Por favor, insira seu nome.">

                        Telefone*
                        <input type="tel" class="form-control" id="phone" required data-validation-required-message="Por favor, insira seu número de telefone." placeholder="(00) 0000-0000">

                        Email*
                        <input type="email" class="form-control" id="email" required data-validation-required-message="Por favor, insira seu email.">

                 Assunto:
                   <select class="form-control" id="sel1">
                    <option>1</option>
                    <option>2</option>
                    <option>3</option>
                    <option>4</option>
                   </select>

                        Mensagem
                        <textarea rows="10" cols="100" class="form-control" id="message" maxlength="999" style="resize:none"></textarea>

                <button type="submit" class="btn btn-success btn-lg">Enviar</button>

            </form>

JAVASCRIPT PARA VALIDAR:
$(function() {

$("input,textarea").jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {

    },
    submitSuccess: function($form, event) {
        event.preventDefault();
        var name = $("input#name").val();
        var phone = $("input#phone").val();
        var email = $("input#email").val();
    var sel1 = $("input#sel1").val();
        var message = $("textarea#message").val();
        var firstName = name;
        if (firstName.indexOf(' ') >= 0) {
            firstName = name.split(' ').slice(0, -1).join(' ');
        }
        $.ajax({
            url: "bin/contact_me.php",
            type: "POST",
            data: {
                name: name,
                phone: phone,
                email: email,
        sel1: sel1,
        message: message
            },
            cache: false,
            success: function() {
                // Success message
                $('#success').html("
");
                $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                    .append("</button>");
                $('#success > .alert-success')
                    .append("Sua mensagem foi enviada. ");
                $('#success > .alert-success')
                    .append('
');

                $('#contactForm').trigger("reset");
            },
            error: function() {
                // Fail message
                $('#success').html("
");
                $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                    .append("</button>");
                $('#success > .alert-danger').append("" + firstName + " Parece que não está funcionando... Você poderia enviar um email direto? Desculpe pela inconveniência.");
                $('#success > .alert-danger').append('
');

                $('#contactForm').trigger("reset");
            },
        })
    },
    filter: function() {
        return $(this).is(":visible");
    },
});

$("a[data-toggle=\"tab\"]").click(function(e) {
    e.preventDefault();
    $(this).tab("show");
});});

$('#name').focus(function() {
    $('#success').html('');
});

PHP PARA ENVIAR:
<?php

if(empty($_POST['name'])        ||
   empty($_POST['phone'])       ||
   empty($_POST['email'])       ||
  !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
 {
   echo "No arguments Provided!";
   return false;
 }
 $name = $_POST['name'];
 $phone = $_POST['phone'];
 $email_address = $_POST['email'];
 $sel1 = $_POST['sel1'];
 $message = $_POST['message'];

 $to = 'email@example.com';
 $email_subject = "Formulário de contato, $name te enviou uma mensagem.";
 $email_body = "Você recebeu uma nova mensagem do site.\n\n"."Aqui estão     os detalhes:\n\nNome: $name\n\nTelefone: $phone\n\nAssunto: $sel1\n\nEmail: $email_address\n\nMensagem:\n$message";
 $headers = "From: $email_address\n";
 $headers .= "Reply-To: $email_address";
 mail($to,$email_subject,$email_body,$headers);
 return true;
 ?>

Comment: Como você já tem uma resposta indicando como subir o arquivo para o seu servidor, basta fazer o que está indicado aqui para enviá-los por email: http://pt.stackoverflow.com/questions/11417/enviar-email-com-anexos-em-php (na verdade são dois problemas separados, um é como "subir" o arquivo, e outro como anexar. Os dois problemas já tem resposta aqui no site).
Answer: Para enviar arquivos atrave de formulario você deve usar a variavel super global $_FILES[]
Em seu form adicione o campo:
<input type="file" name="imagem" />
// Não esqueça de adicionar o parametro de midia em seu formulario
// Adicione enctype="multipart/form-data" logo após o method="post"(get)

Caso queira enviar mais de um arquivo altere o código acima onde type="file" irá se tornar type="file[]" e tambem adicione o parametro ao multiple ficando deste jeito;
<input type="file[]" name="imagem" multiple />

para a validação do campo utilize o método do próprio HTML5; required (coloque o required logo apos o multiple)
Em sua pagina de enviar com PHP pegue o arquivo usando a variavel super global mencionada no começo.
$nomeArquivo = $_FILES["imagem"]["name"]; // Pega o nome do arquivo
$nomeTemporario = $_FILES["imagem"]["tmp_name"]; // Pega o nome temporario do arquivo
$tamanhoArquivo = $_FILES["imagem"]["size"]; // Pega o tamanho
$caminho = 'uploads/'; // define a pasta onde sera salvo o arquivo

$arquivoArray = explode(".", $nomeArquivo); // Separa o nome do arquivo da extensão, por exemplo: imagem1.jpg -> ficara imagem1
    $extensao = end($arquivoArray); // Pega a extensao do arquivo (final da variavel $arquivoArray), por exemplo: imagem1.jpg -> ficara .jpg
    $arquivo = $caminho.md5(time().rand(3212, 15452)).'.'.$extensao; // Junta o caminho e cria um nome complexo para o arquivo para evitar duplicidade, a variável conterá por exemplo -> uploads/987asd3a218w6qw21qeq651.jpg

    if (!is_dir($caminho)) { // Verifica se a pasta para salvar o arquivo existe (uploads)
        mkdir($caminho); // Caso não exista cria a pasta
        chmod($caminho, 777); // Caso não exista adiciona permissões de leitura e escrita na pasta
    }

    if (move_uploaded_file($nomeTemporario, $arquivo)) { // Move o arquivo com o nome tempoparario para a pasta
    foreach($_POST as $key => $val){
//Percorre os indices passados por POST armazanando em $key e os valores em $val
    $campo[] = $key; // Cria um array $campo com os indices
    $valor[] = "'$val'"; // Cria um array $valor com os valores

    $campos = implode(",", $campo); // Junta os indices de $campo com virgula
    $valores = implode(',', $valor); // Junta os valores de $valor com virgula

// Faz a inserção no banco de dados usando PDO
$inserir = $con->prepare("INSERT INTO $tabela($campos, imagem) VALUES($valores,'$arquivo')");
$inseri = $inserir->execute();

Comment: Agradeço muito pela sua resposta, mas na verdade eu gostaria de enviar esses arquivos que fizerem upload no site em anexo no email.


loading module inside redux connect

Question: I'm trying to figure out what I did wrong, here's the scenario
Greeting.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import name from './name';

class SayGreeting extends Component {
  componentDidMount() {
    console.log(name);
  }
  render() {
    return (

        Good Morning to you, {name}

    )
  }
}

const mapStateToProps = ...
const mapDispatchToProps = ...

const Greeter = connect(
  mapStateToProps,
  mapDispatchToProps
)(SayGreeting)

export default Greeter;

name.js
import React from 'react';

const Name = () => (
Yoshie
);
export default Name;

when I log out "name", it logs out a connect function instead of the jsx that I expected:
function Connect(props, context) {
    _classCallCheck(this, Connect);

    var _this = _possibleConstructorReturn(this, _Component.call(this, props, context));

    _this.version = versio…

I wonder if I did anything wrong... thanks for the help!
Answer: have you try it like this,
EDIT: try import the name inside curly braces
import {Name} from './name'

class SayGreeting extends Component {
componentDidMount() {
  console.log(name);
}
render() {
  return (

      Good Morning to you, <Name/>

  )
 }
}

Comment: try import name inside curly braces like `import {Name} from './name'`
Comment: I should be using brackets like you suggested, thanks for pointing that out. guess I need to head to bed ;)

loading module inside redux connect


How much bias am I risking by doing model goodness of fit comparison without accounting for clustering?

Question: I am interested in testing whether an interaction term is statistically significant or not in a logistic regression. Data is large and observations are clustered by family and suffer from sparsity for both the outcome and one of the covariates in the interaction term (% of 0s vs. 1s are about 95% and 5%).
I first tried (with glmer() in lme4)
anova(mixed effects model 1, mixed effects model 2)

very simple
outcome ~ covar 1 * covar 2 + (1|family)

vs.
outcome ~ covar 1 + covar 2 + (1|family)

Both covar 1 and covar 2 are binary variables. The first model probably ran to the edge of the world after 12 hours and could be found no more. Then I wondered what the cost would be if I ran both models in the same wrong way (i.e., not accounting for the random effect)
Here is a publicly available data set I explored--
library(lattice)
gm1 <- glmer(cbind(incidence, size - incidence) ~ period + (1 | herd), data = cbpp, family = binomial)
cbpp$obs <- 1:nrow(cbpp)
gm2 <- glmer(cbind(incidence, size - incidence) ~ period + (1 | herd) +  (1|obs), family = binomial, data = cbpp)
anova(gm1,gm2)

# how is it different from lrt?

gm3 <- glm(cbind(incidence, size - incidence) ~ period + herd,  data = cbpp, family = binomial)
gm4 <- glm(cbind(incidence, size - incidence) ~ period * herd,  family = binomial, data = cbpp)
lrtest(gm4,gm3)

p from ANOVA = 0.002152, p from LRT = 0.001613
As I was expecting, the LRT was too optimal, but say if the bias (in terms of p-value) is no more than 200% (or some upper limit), a quick way to do model comparison could be running the LRT and multiplying the too-optimal p-values by a scaling factor.
Thank you for your time and insight! Any papers on this would be very helpful, too.
Answer: Ignoring the clustering/correlations in your data can have an impact on the inference you are going to make. The magnitude of ignoring the clustering/correlations in p-values depend on how strong the correlations are, the type of effect you are testing (i.e., within or between clusters effects), any potential missing data you have and the type of mechanism that generated this missing data (i.e., missing completely at random or missing at random).


onPageStarted and onPageFinished don't work

Question: Here is my code snippet:
webView = (WebView) browserView.findViewById(R.id.webView);
webView.loadUrl(webUrl);

    webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.contains("some_domain")) {
             webView.loadUrl(url);
             Toast.makeText(context, "Loaded", Toast.LENGTH_SHORT).show();
         } else
             Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
             return true;
         }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        progressBar.setVisibility(View.GONE);
    }
});

Methods onPageStarted and onPageFinished are executed only the first time I click a link. Then, these methods don't work. What could be the problem?
Thanks.
Comment: any error is thrown?
Comment: @Fahim nope. The log is clear.
Answer: Can you try changing your shouldOverrideUrlLoading method to
@Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub
                progressBar.setVisibility(View.VISIBLE);
            webView.loadUrl(url);
            return true;

        }

Comment: But this method is not executed for some unknown reason after the page loads.


How can I align the innerPlots?

Question: I have 2 charts: chart1 and chart2.
I want both charts to have same innerPlotSize and location.
But chart1 has a secondary yaxis.
This does NOT work:
chart2.ChartAreas[0].AlignWithChartArea = chart1.ChartAreas[0].Name;
chart2.ChartAreas[0].AlignmentStyle = AreaAlignmentStyles.PlotPosition;
chart2.ChartAreas[0].AlignmentOrientation = AreaAlignmentOrientations.Vertical;

Comment: You could create a new Postition for the second chartarea from the one of the first chartarea. simply copy the x and Width form one then keep the Y and Height from the other!
Comment: chart2.ChartAreas[0].InnerPlotPosition = chart1.ChartAreas[0].InnerPlotPosition; appears to make NO DIFFERENCE. Also, where do I find width of InnerPosition?
Comment: Oh, sorry. I had assumed that the two charts are actually in the same chart control in different chartareas. If they both are set to auto the code indeed makes no difference. you need to get the actual numbers (in percent of the respective container !!) by calling `RectangleF r1 = chart.ChartAreas[0].Position.ToRectangleF();
            RectangleF r2 = chart.ChartAreas[0].InnerPlotPosition.ToRectangleF();`
Comment: See [here](http://stackoverflow.com/questions/36221672/constrain-aspect-ratio-in-windowsforms-datavisualization-chart/36248343#36248343)  [and here](http://stackoverflow.com/questions/36491231/ms-chart-rectangular-annotation-width-in-percent-and-not-pixel/36497262#36497262) for a discussion! - In your case it would require you to pick the one where the Left value is the larger as the template for left&width..
Answer: This will align the InnerPlotPositions of two Charts:
    // align the controls:
    yourChart1.Left = yourChart2.Left;
    yourChart1.Size = yourChart2.Size;

    // get the numbers of the current innerplotpositions
    RectangleF ri1 = yourChart1.ChartAreas[0].InnerPlotPosition.ToRectangleF();
    RectangleF ri2 = yourChart2.ChartAreas[0].InnerPlotPosition.ToRectangleF();

    if (ri1.Width < ri2.Width)
    {
        yourChart2.ChartAreas[0].InnerPlotPosition =
            new ElementPosition(ri1.Left, ri2.Top, ri1.Width, ri2.Height);
    }
    else
    {
        yourChart1.ChartAreas[0].InnerPlotPosition =
            new ElementPosition(ri2.Left, ri1.Top, ri2.Width, ri1.Height);
    }

Before and after:
Comment: Thanks for this. After I had got this working - I realised it would be much easier to have 2 chartArea on the same control (I believe you mentioned that in another thread). Then you can use the Align functionality which works perfectly.
Comment: That seems quite good -thank you. Only problem now is that when first chart is in Zoom mode, second is miss-aligned by the amount of the yAxis scroll bar. Any idea how to fix that?
Comment: I believe the scrollbars are part of the chararea, not the innerplotposition. So we'll have to go back one step and calculate the values from both. The ipp ist nested in the chartarea which is nested in the chart client rectangle. - . I'm tied up tonight; I hope I can get it to work tomorrow.
Comment: Actually the IPP are still aligned when zooming in on the (originally) larger of the charts. The solution is simple: You need to re-align them on every zoom just as on every resize! So best call the alignment from the ScaleViewChanged event!

How can I align the innerPlots?


Valid JAR signature for JavaFX projects

Question: I've been working through various recipes to produce a runnable JAR file for a JavaFX project using a Maven POM.  Each of these Stackoverflow questions describes the same problem.  It is frustrating that there seems to be several different solutions for the same goal.
problem:

java.lang.SecurityException: Invalid signature file digest for Manifest main attributes

Error when executing a JAR file on the command line.  Although Netbeans can happily run the program and debug the program.
diagnosis
There are several Stackoverflow and forum questions about this (most helpful ones below).  Even though is a known problem I'm yet to find a clear solution to work with JavaFX.  The procedures described in these answers do NOT with the JavaFxPackager tool used to bundle-up your JavaFX JAR:

"Invalid signature file digest" error adding Janino package through Maven
Error (org.codehaus.mojo) when adding persistence to Maven-Java-project? ... This looks the most promising since it is also a JavaFX project.  Same error here so far.

usual approach:
The post popular answer for this question (255 votes at time of writing): works with non-JavaFX modules in our project:

"Invalid signature file" when attempting to run a .jar ...

However when we put the same plug-in in the POM that builds the JavaFX JAR file, we still get the: "Invalid signature file digest ..." error.  Specifically, I placed the <artifactId>maven-shade-plugin</artifactId> first before and then after the JavaFxPackager exec rule.  The result is

Maven gives the: "Invalid signature file digest for Manifest main attributes..." error

**question*:
How does one manage to package a JavaFX application.  This is the POM <build> section Netbeans sets-up for JavaFX:
      <build>
          <resources>
             <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
             </resource>
          </resources>

          <plugins>
             <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-dependency-plugin</artifactId>
                  <version>2.8</version>
                  <executions>
                      <execution>
                          <id>unpack-dependencies</id>
                          <phase>package</phase>
                          <goals>
                              <goal>unpack-dependencies</goal>
                          </goals>
                          <configuration>
                              <excludeScope>system</excludeScope>
                              <excludeGroupIds>junit,org.mockito,org.hamcrest</excludeGroupIds>
                              <outputDirectory>${project.build.directory}/classes</outputDirectory>
                          </configuration>
                      </execution>
                  </executions>
              </plugin>

              <plugin>
                  <groupId>org.codehaus.mojo</groupId>
                  <artifactId>exec-maven-plugin</artifactId>
                  <version>1.3.2</version>
                  <executions>
                      <execution>
                          <id>unpack-dependencies</id>
                          <phase>package</phase>
                          <goals>
                              <goal>exec</goal>
                          </goals>
                          <configuration>
                              <executable>${java.home}/../bin/javafxpackager</executable>
                              <arguments>
                                  <argument>-createjar</argument>
                                  <argument>-nocss2bin</argument>
                                  <argument>-appclass</argument>
                                  <argument>${mainClass}</argument>
                                  <argument>-srcdir</argument>
                                  <argument>${project.build.directory}/classes</argument>
                                  <argument>-outdir</argument>
                                  <argument>${project.build.directory}</argument>
                                  <argument>-outfile</argument>
                                  <argument>${project.build.finalName}.jar</argument>
                              </arguments>
                          </configuration>
                      </execution>
                      <execution>
                          <id>default-cli</id>
                          <goals>
                              <goal>exec</goal>
                          </goals>
                          <configuration>
                              <executable>${java.home}/bin/java</executable>
                              <commandlineArgs>${runfx.args}</commandlineArgs>
                          </configuration>
                      </execution>
                  </executions>
              </plugin>

              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-compiler-plugin</artifactId>
                  <version>3.1</version>
                  <configuration>
                      <source>1.8</source>
                      <target>1.8</target>
                      <compilerArgument>-Xlint:unchecked</compilerArgument>
                      <showWarnings>true</showWarnings>
                      <showDeprecation>true</showDeprecation>
                      <compilerArguments>
                          <bootclasspath>${sun.boot.class.path}${path.separator}${java.home}/lib      /jfxrt.jar</bootclasspath>
                      </compilerArguments>
                  </configuration>
              </plugin>

              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-surefire-plugin</artifactId>
                  <version>2.16</version>
                  <configuration>
                      <additionalClasspathElements>
                          <additionalClasspathElement>${java.home}/lib/jfxrt.jar</additionalClasspathElement>
                      </additionalClasspathElements>
                  </configuration>
              </plugin>
          </plugins>
      </build>

The shard plugin configuration used based on the answer in: "Invalid signature file" when attempting to run a .jar currently looks like this:
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-shade-plugin</artifactId>

                  <version>2.3</version>
                  <executions>
                      <execution>
                        <id>remove-sign-files</id>
                        <phase>package</phase>
                        <goals>
                          <goal>shade</goal>
                        </goals>
                        <configuration>
                          <filters>
                              <filter>
                                  <artifact>*:*</artifact>
                                  <excludes>
                                      <exclude>classes/META-INF/*.SF</exclude>
                                      <exclude>classes/META-INF/*.DSA</exclude>
                                      <exclude>classes/META-INF/*.RSA</exclude>
                                  </excludes>
                              </filter>
                          </filters>
                        </configuration>
                      </execution>
                  </executions>
              </plugin>

To keep Netbeans out of the equation as much as possible, I just run

mvn package

On the command line.  This just issue seems to be a frequent problem and I'm hoping someone has cracked the code for JavFX bundling in other JAR files for a JavaFX build.
Other links:

How to tell the maven-shade-plugin to preserve signatures?
Packaging jar is invalid Aggregator project need pom as packaging
Apache Maven Shade Plug-in
Executable JAR
Comment: http://stackoverflow.com/questions/34738653/maven-shade-plugin-does-not-exclude-the-manifest-signature-files
Comment: Instead of `classes/META-INF/*.SF` try `META-INF/*.SF`
Answer: I had a very similar problem; when I included a signed JAR (bouncycastle) in the project. Its signature was repackaged verbatim, resulting in an obvious SecurityException:

java.lang.SecurityException: Invalid signature file digest for
  Manifest main attributes

Filtering of all sorts failed; the solution that works for me looks like this in the pom.xml:
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  <version>2.8</version>
  <executions>
    <execution>
      <id>unpack-dependencies</id>
      <phase>package</phase>
      <goals>
        <goal>unpack-dependencies</goal>
      </goals>
      <configuration>
        <excludes>META-INF/*.SF,META-INF/*.DSA,META-INF/*.RSA</excludes>
        ...
      </configuration>
    </execution>
  </executions>
</plugin>

I omitted some lines after the new one with the "excludes" pattern.
This single line was the solution for me - I include the other lines so you can see the placement. (I had trouble with many other postings which omitted the context of a tag, so I try to save others this trouble).
Hope that helps others with the same problem.
Comment: I know the feeling - it motivated me to write this answer.
Comment: by the way - if a JAR is signed, there is usually a reason why it is. Consider whether distributing/installing the JAR separately instead of repackaging makes sense. For a Crypto Provider like BouncyCastle, there are some good reasons why you should try to keep it separately and signed.
Comment: Finally! I've been suffering for hours with de shade plugin to no avail.
Answer: After a lot of research I found a solution that works for my project using JavaFX, Maven and NetBeans.
I'm working on a simple REST client that uses jersey and moxy to decode JSON.
After adding the dependency jersey-media-moxy application reports the error of invalid signature.
I found that this depends on the presence of the signature file ECLIPSE_.RSA and ECLIPSE_.SF inside the META-INF for some libraries.
In my case were the org.eclipse.persistence.moxy-2.5.0.jar, org.eclipse.persistence.antlr-2.5.0.jar, org.eclipse.persistence.asm-2.5.0.jar and org.eclipse.persistence.core-2.5.0.jar
The pom.xml in Netbeans that you indicated running two separate step.
The first invoke maven-dependency-plugin that expands all the external jar.
The second use exec-maven-plugin that call javafxpackager to create the final jar file e finally run it.
By performing the two steps in sequence signature in org.eclipse libraries are placed in the META-INF of the final jar file and this generates the error on the signature.
My solution is add an intermediate step between the execution of the maven-dependency-plugin and exec-maven-plugin. In this step I'm going to delete all signature file inside the directory
${project.build.directory}/classes

To do this I used a plugin maven-antrun-plugin
<plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.8</version>
    <executions>
         <execution>
              <phase>package</phase>
              <goals>
                   <goal>run</goal>
              </goals>
              <configuration>
                   <target>
                       <delete>
                           <fileset dir="${project.build.directory}/classes" includes="**/META-INF/*.DSA"/>
                           <fileset dir="${project.build.directory}/classes" includes="**/META-INF/*.RSA"/>
                           <fileset dir="${project.build.directory}/classes" includes="**/META-INF/*.SF"/>
                    </delete>
                </target>
            </configuration>
        </execution>
    </executions>
</plugin>

Valid JAR signature for JavaFX projects


Rendering Module Code to HTML

Question: Semi-new to Drupal. I'm trying to find a way to render HTML inside my custom module.
Right now I'm using this method
$page = 'hello world';
return $page;

Which can get pretty dirty once you had some logic into it.
Is there a better way to do this? Maybe render it to some kind of template file and pass an array of vars?
Any help is appreciated :)
Comment: _"Maybe render it to some kind of template file and pass an array of vars?"_...yep, you've just described Drupal's theming system :) See [`hook_theme()`](http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_theme/7)
Comment: ...or if you just need to wrap your code in some DIVs, just create the render array and Drupal will take care of the hard work.
Answer: Clive is right that using the drupal theme system is your best bet if you're going to be doing significant variable manipulation but if you just want to load a big blob of HTML into your module you can do it a couple of ways in PHP.
For short blobs, try the EOF method
$str = <<<EOF

Hello

$world

  ... etc.
EOF;

For longer blobs, use file_get_contents()
$myhtml = file_get_contents(path_to_module().'/my_html.tpl');

Rendering Module Code to HTML


Book reference for introduction to Normed Spaces

Question: I wanted a book reference for the study of normed spaces and linear operators. Im still not into functional analysis, but I wanted a reference of an introductory book as to start reading. What would you recommend?
I've have been studying for a while now metric spaces, and related concepts such as connection, completeness, compactness, etc.
Answer: I think that Introductory Functional Analysis, by Erwin Kreyszig is the book you want. The book is elementary, and as the title says, introductory. I even think you have some advantage there, having studied a bit of metric spaces before. The first chapter is about metric spaces, and he doesn't assume that you know anything about normed spaces.


How to add video url to a Jekyll no js lightbox

Question: There is a lightbox sans JavaScript in a Jekyll theme and I have been trying to add url capability to click on image or title and play a YouTube video within it.
Where is the code that includes the elements of the lightbox? In the yml file it has
add:
image: ""
title:""
description:""
And I was hoping to place url: ""
At the end but when I do Jekyll won't build.
Comment: Please include a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) in your post. It should include your exact inputs, exact outputs, and detailed steps you took so that the problem can be reproduced by others.
Comment: just get it from github.
Answer: I figured it out. Works really well where you might want a video to show up in the lightbox instead of an enlarged image. Jekyll had no problem.
<code>--
</code>
name: "animation"
arts:
Row 1

image: "images/galleries/animation/some.png"
order: "1"
artist: "Name"
title: "Something"
description: place the embed youtube iframe here


Capturar em Loop o valor de uma varivel de outra Activity

Question: Na minha app, tenho uma atividade chamada "GpsTrackerActivity" que está constantemente a calcular a distancia percorrida através do método onLocationChanged, da Interface LocationListener.
O meu problema é que necessito de abrir uma nova actividade e quero que esta, enquanto estiver activa, consiga capturar em Loop o valor da variável pública "distancia", que está na actividade "GpsTrackerActivity".
Já tentei um ciclo While infinito para ficar constantemente a capturar o valor da variável "distancia", mas desta forma a app bloqueia! Alguém me pode ajudar?
public class GpsTrackerActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
public static double distancia;
....
}

Segunda Atividade:
public class SegundaActivity extends AppCompatActivity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

while (true){
            double distancia = GpsTrackerActivity.distancia;
            Log.i("Tag", "Distância: " + distancia + " Km");
        }

}
....
}

Answer: O que você está tentando fazer, até  onde sei, não é possível, pois cada activity tem seu próprio contexto ( conjunto de recursos e classes próprias), além disso, só é possível executar uma Activity por vez, então é inviável capturar os eventos de uma Activity A que esá "fechada" dentro de uma Activity B que está aberta. Portanto, se você quiser que alguma activity capture o evento de "localização alterada", é ela mesma quem deve "escutar" e tratar as alterações na localização.
Como no seu caso as duas activities precisam receber alterações na localização, você tem duas opções:

Ao obter a nova localização na GPSTrackerActivity, inicar a segunda activity pasando a localização obtida através de um Bundle
Nesse caso, ao obter a nova localização com o método onLocationChanged(Location location) na GPSTrackerActivity, você faria:
@Override
public void onLocationChanged(Location location) {

    // Calcule a sua distancia
    // double distancia = ?

    Bundle mBundle = new Bundle();
    mBundle.putDouble("distancia",distancia);

    Intent mIntent = new Intent(this, SegundaActivity.class)
           mIntent.putExtras(mBundle);

    startActivity(mIntent);
}

E na SegundaActivity você pegaria a distância passada no método onCreate() utilizando o seguinte código
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    double distancia = getIntent().getExtras().getDouble("distancia");

    /* ... */
}

OBS.: Note que, nesse caso, a sua SegundaActivity só recebe uma única distância, que foi obtida a partir da última localização recebida pela GPSTrackerActivity. Isso significa que, se a sua localização mudar enquanto a SegundaActivity estiver aberta, ela não receberá essa nova distância, pois quem recebe e trata a distância é a GPSTrackerActivity. Se você  quiser que a SegundaActivity receba constantemente uma nova localização conforme haja mudanças, você pode usar a segunda abordagem.
Criar uma classe " MeuLocationManager " que será responsável por acompanhar mudanças na localização e fornece-las a um "solicitante"
Nesse caso, você irá transferir toda a lógica do acompanhamento de mudanças na localização para a classe " MeuLocationManager ". Assim, toda vez que uma classe quiser receber informações sobre mudanças na localização, basta requisitar ao " MeuLocationManager " que envie a ela as localizações obtidas. Fica mais ou menos assim:
 public class MeuLocationManager implements LocationListener /*, etc. */ {

     // Classe que vai requisitar a localização
     private LocationListener requisitorLocalizacao;

     /* Vamos implementar o padrão Singleton para evitar que
        um novo LocationManager seja criado a cada vez que for
        necessário chamá-lo*/

     private static MeuLocationManager instance;

     private MeuLocationManager() {

     /* Implemente e/ou crie todos os métodos necessários
        para obtenção de localização, como:

        Criação e inicialização do Google Services
        Callbacks para escutar a conexão com o Google Services, etc. */
     }

     public static MeuLocationManager getInstance(){

         if(instance == null){
             return new MeuLocationManager();
         }else{
             return instance;
         }
     }

    /* Método que será usado por outra classe para solicitar
     a localização */
    public void requestLocationUpdates(LocationListener requisitorLocalizacao){

        this.requisitorLocalizacao = requisitorLocalizacao;
    }

    /* Repassa a localização obtida para o requisitor da
    localização */
    @Override
    public void onLocationChanged(Location location){

         // Repassa a localização obtida para o requisitor da
         // localizacao
         requisitorLocalizacao.onLocationChanged(location);
    }
}

Agora, toda classe que quiser receber mudanças na localização, deverá implementar a interface LocationListener e solicitar ao MeuLocationManager que envie a ela as novas localizações obtidas. Vamos utilizar como exemplo a sua classe SegundaActivity. Primeiro, você deve fazer ela implementar a interface LocationListener, em seguida você fará o seguinte no seu método onCreate():
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    MeuLocationManager locationManager = MeuLocationManager.getInstance();

    // Solicita localização
    locationManager.requestLocationUpdates(this);
}

// No método `onLocationChanged` faça o que você quiser
// com a localização que foi recebida do MeuLocationManager
@Override
public void onLocationChanged(Location location) {

    /* ... */
}

Essas são apenas duas soluções possíveis, existem muitas outras, como por exemplo, utilizar a biblioteca Reactive Location, que é a que eu uso nos meus projetos :)
Comment: regmorais, muito obrigado pela sua ajuda, pois foi excelente a sua explicação. Vou optar pela segunda abordagem.
Comment: regmorais, só não percebi na Classe MeuLocationManager a configuração  public static MeuLocationListener getInstance(){...}? Ao inseri-lo na Classe obtenho um erro por causa do nome  MeuLocationListener?
Comment: @VitorMendanha me desculpe, eu coloquei o nome errado, o certo é **MeuLocationManager**. Já consertei na resposta :)


SQL syntax error when try insert into by python

Question: I have the following table in my database:
create table tt (
id varchar(20),
hora varchar(20),
preco varchar(20),
qtde varchar(20),
cpa varchar(20),
vda varchar(20),
agressor varchar(20)
);

I put them all like varchar (30) because my head was too white with the mistakes they were making.
even with all fields like varchar (30) I am not able to insert into the following 7 values via python
19928 12:53:34 4.049,00 5 107 308 Comprador

(19928, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':53:34, 4.049,00, 5, 107, 308, Comprador)' at line 1")
my command to insert into is the following:
c.execute("INSERT INTO tt VALUES ({}, {}, {}, {}, {}, {}, {})".format(id_, hora, preco, qtde, cpa, vda, agressor))
conn.commit()

could also assist me in what types of variables to use to create the table? (int, varchar (20), float)?
Answer: You should be using a prepared statement here, which would likely also resolve your current errors:
cursor = conn.cursor(prepared=True)
sql = """INSERT INTO tt (id, hora, preco, qtde, cpa, vda, agressor)
         VALUES (%s, %s, %s, %s, %s, %s, %s)"""
cursor.execute(sql, (id_, hora, preco, qtde, cpa, vda, agressor,))
conn.commit()

Using this approach, you let Python/MySQL worry how to properly escape your string data with single quotes.  Also note that it is best practice to always explicitly list out the target columns for an insert, which I have done above.
Comment: [Check the documentation](https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursorprepared.html).
Comment: cursor = conn.cursor(prepared=True)
TypeError: cursor() got an unexpected keyword argument 'prepared'
Comment: @Leo What is the driver/connector you are using?  Can you check [here](https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursorprepared.html) and let us know if it looks familiar to you?
Comment: import MySQLdb
conn = MySQLdb.connect(host= "localhost",
                  user="root",
                  passwd="****",
                  db="tryd")
Comment: a lot of problems here.  the first: this question, the second: the conector (import mysql.connector), the third: the package (i need to pip install MySQL-connector-python); your and this question help me a lot https://stackoverflow.com/questions/50243506/caching-sha2-password-is-not-supported-mysql
Answer: Your problem is that your query looks like this:
INSERT INTO tt VALUES (19928, 12:53:34, 4.049,00, 5, 107, 308, Comprador)

which is invalid because of unquoted time and string values, and the comma in one of the numbers. You need to use the prepared statement form:
c = conn.cursor()
c.execute("INSERT INTO tt VALUES (%s, %s, %s, %s, %s, %s, %s)",(id_, hora, preco, qtde, cpa, vda, agressor))
conn.commit()
c.close()

Note that when you change your column data types, to insert 4.049,00 into MySQL as a number you will need to first swap the , and . characters.
Comment: Note: OP only has varchar fields .. a problem for another day I suppose.


bootstrap KS 2 sample test

Question: I have two datasets $S_1$ and $S_2$. I can run KS 2 samples test on these datasets to obtain the value of the KS 2 samples test.
Is there a correct way to bootstrap the KS 2 sample test using the datasets $S_1$ and $S_2$?
In other words, how exactly should sample from $S_1$ and $S_2$ to obtain a bootstrap distribution for the KS 2 sample test.
For example if we have in scipy the following 2 datasets :
from scipy import stats

n1 = 200  # size of first sample
n2 = 300  # size of second sample

S1 = stats.norm.rvs(size=n1, loc=0., scale=1)
S2 = stats.norm.rvs(size=n2, loc=0.5, scale=1.5)
stats.ks_2samp(S1, S2)

Then stats.ks_2samp returns a KS value. I would like to know how could we do bootstrap the samples $S_1$ and $S_2$ to obtain a bootstrap distribution for the ks_2samp values. Any help is appreciated.
Comment: @BruceET Besides power studies, I have found a few additional reasons to carry out such a procedure.  One is where the two-sample test available does not correctly compute the p-value; for instance, maybe it uses a doubtful approximation or it simply refuses to run with datasets of a certain size.  The other reason is where either of the datasets has a tie, which makes the KS-test inapplicable--but the KS *statistic* may still be useful for distinguishing the underlying distributions.
Comment: What are you trying to accomplish? Why isn't enough to have just one K-S test comparing the two samples? I could see the purpose of a simulation procedure if you were trying to find the power of the the K-S test in certain circumstances.
Comment: @whuber , Do you have an idea for how to carry how bootstrap  in this case? thanks.
Answer: The null hypothesis is that the batches of data are independent simple random samples from a common continuous distribution.  The (two-sample) Kolmogorov-Smirnov (KS) statistic measures a difference in their empirical distributions.  Thus, exactly as in any other case where you have a measure of difference, you can bootstrap it by resampling from the combined dataset.
There's a slight problem: about $1/e\approx 37\%$ of a bootstrap sample will be duplicated, which is bad news for the KS test: many implementations will complain.  One workaround is to add a tiny amount of noise to each resampled value.  This is legitimate because adding a tiny bit of noise will scarcely change the underlying distribution (provided it has no discrete components).
(Another attractive alternative is to perform a permutation test in which one "bootstrap" sample is obtained without replacement from the combined dataset and is compared to the remainder of the data. If there are no ties the combined dataset, there will never be a problem with the KS statistic.  The permutation test and bootstrap perform very nearly the same.)
Below is an example in R, commented and coded to port readily to Python. It works by concatenating the two datasets into an array S and sampling from this array (or, literally, from its indexes using sample.int).  Its output documents bootstrapping five situations like the one in the question, giving some indication of the power of the test (that is, its likelihood of rejecting the null).  A bootstrap of 500 resamples would be more than enough, but here I show 5000 resamples to create precise results.

(The code will perform a permutation test by setting do.bootstrap to FALSE.  If nothing else is modified, the same random datasets will be generated, enabling direct comparison between the bootstrap and permutation test results.)
ppts <- function(n) (1:n - 1/2)/n
stat <- function(S1, S2, tol=1e-4) {
  sigma <- sd(c(S1,S2)) * tol # (See the text)
  X1 <- S1 + rnorm(length(S1), 0, sigma)
  X2 <- S2 + rnorm(length(S2), 0, sigma)
  ks.test(X1, X2)$statistic
}

do.bootstrap <- FALSE # Alternatively, use a permutation test.

par(mfcol=c(2,5))
set.seed(17)
seeds <- round(runif(5)*2^31)
n1 <- 10
for (i in 1:5) {
  #
  # Generate data.
  #
  set.seed(seeds[i])
  n2 <- round(n1 * 3/2)
  S1 <- rnorm(n1, 0, 1)
  S2 <- rnorm(n2, 0, 1.5)
  #
  # Compare the data graphically.
  #
  qqplot(S1, S2, bty="n", main="QQ Plot")
  abline(0:1)
  #
  # Bootstrap the statistic.
  #
  S <- c(S1, S2)
  boot <- replicate(5000, {
    if (do.bootstrap) {
      i <- sample.int(length(S), length(S), replace=TRUE)
      stat(S[i[1:n1]], S[i[-(1:n1)]])
    } else {
      i <- sample.int(length(S), n1, replace=FALSE)
      stat(S[i], S[-i], tol=0)
    }
  })
  #
  # Display the bootstrap results.
  #
  ks.data <- stat(S1, S2)
  boot <- c(ks.data, boot)
  p.value <- mean(boot >= ks.data)
  hist(boot, freq=FALSE, breaks=30, col="#f0f0f0", border="Gray",
       main=paste0("P-value is ", signif(p.value, 3)))
  abline(v = ks.data, lwd=2, col="Red")
}
par(mfcol=c(1,1))

Comment: thanks man, this is pretty helpful.

bootstrap KS 2 sample test


Filling array with multithreading

Question: I am trying to read multidimensional arrays and get the index and values of the element if it is fitting the condition with multithreading.
I divided the multidimensional array into smaller subcubes under name jobs
If the condition fits, I save the value to the samples array, and index to the ValidCubeIndexList array.  So the "samples" and the "ValidCubeIndexList" is going to be shared and used between threads.
I am not sure if this is a correct approach or not, but with parallelism, I couldn't find a way to lock iSample locally.
Parallel.For(0, jobs.Count, new ParallelOptions {
    MaxDegreeOfParallelism = NumOfProcessor
  },
  delegate(int i, ParallelLoopState state) {

    var job = jobs[i];

    Index3 min = job.output.MinIJK;
    Index3 max = job.output.MaxIJK;

    var bulk = job.output.ToArray();

    int x = bulk.GetLength(0);
    int y = bulk.GetLength(1);
    int z = bulk.GetLength(2);

    for (int n = 0; n < x; n++) {
      for (int m = 0; m < y; m++) {
        for (int b = 0; b < z; b++) {

          int activeIndex = Get3DIndex(min.I + n, min.J + m, min.K + b, cubeIndex.I,
            cubeIndex.J, cubeIndex.K);

          if (SelectionMaskIsActive) {
            if (invFlags[activeIndex]) {

              samples[iSample] = bulk[n, m, b];

              ValidCubeIndexList[iSample] = activeIndex;
              Interlocked.Increment(ref iSample);

            }
          } else {
            samples[iSample] = bulk[n, m, b];
            ValidCubeIndexList[iSample] = activeIndex;
            Interlocked.Increment(ref iSample);
          }
        }
      }
    }
  });

However the Interlocked.Increment(ref iSample) is not working as I expected.
How can I share and use the iSample parameter between threads?
Comment: `However the "Interlocked.Increment(ref iSample)" is not working as I expected.` - what does it do and what did you expect? Also; I see you make use of a lot of variables defined outside the scope of the execution loop - you should be careful with that because they share state accross the threads.
Comment: What are you trying to do? Parallel.For/ForEach is meant for data parallelism, not spawning threads. It's not meant to process a queue of jobs either. `Parallel.ForEach` works by *partitioning* the input data into as many partitions as there are cores and use one worker task per partition, ensuring there's no need to synchronize access. What you wrote seems to try to process each job in a single thread. There better options for this, eg ActionBlock or TransformBlock
Comment: Could you include in the question the definition of the `samples` and `iSample` variables?
Comment: Also having the definition of the `ValidCubeIndexList` variable might help us understand your problem.
Comment: Instead of trying to modify an array, why not use a ConcurrentQueue? Although a TransformBlock could act as both a processor *and* output buffer. A TransformBlock guarantees that the output messages will be in the same order as the input messages, which means you can tell which job each result came from
Answer: As far as I can tell the usage and value of iSample is shared over multiple threads.
Incrementing it using Interlocked.Increment(ref iSample); will not cause the value to be locked locally in any way, so, if you increment, you're changing the value over all the threads which often leads to unexpected results.
If your timing is as such that you rely on this behavior I recommend to use an alternative approach or mark the variable as volatile, but even then its considered bad practice, because, whilst:

The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time.

it does not guarantee direct availability of the variable over all threads, by:

On a multiprocessor system, a volatile read operation does not guarantee to obtain the latest value written to that memory location by any processor. Similarly, a volatile write operation does not guarantee that the value written would be immediately visible to other processors.

Filling array with multithreading


Swift 3 - Como redimensionar UITableView automaticamente

Question: Como redimensionar automaticamente um UITableView de acordo com a quantidade de conteúdo no mesmo?
Quero fazer algo como o que dá pra fazer com um UiTextView:
MyTextView.sizeToFit()

Comment: Sua pergunta nao faz muito sentido porque a UITableView é feita pra acomodar infinitos elementos e mostra-los com scroll. Ou voce esta falando dos elementos dentro do contentView dentro da tableCell?
Comment: Não @leofontes, se trata do tableView mesmo. De alguma forma, existe como calcular a altura total das linhas de dentro desse tableView? O que quero fazer é pegar esse tamanho, setar {tableView.frame.size.height} e colocar isso tudo em um scrollview
Answer: Voce precisa pegar a altura da celula, pedir pro array que voce usa como dataSource o count e entao setar o tamanho no frame, segue uma ideia:
var tamanhoCell = tableView.rowHeight
var count = seuArray.count
tableView.frame = CGRectMake(tableView.frame.origin.x, tableView.frame.origin.y, tableView.frame.size.width, tamanhoCell * count);

Ainda acho que sua pergunta nao faz muito sentido, porque o TableView foi feito pra acomodar os itens ali dentro sem aumentar sua altura, mas boa sorte!
Answer: Simples, basta inserir este código no seu viewDidLoad:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 76

Na primeira linha, ele vai dimensionar automaticamente.
Na segunda, você estima a altura mais utilizada. Na teoria, você precisa somente da primeira, mas eu recomendo utilizar as duas.
Abraços.


Problemas com JPA - Hibernate nao persiste TODO o objeto

Question: Bom dia galera!
Tenho as seguintes entidades:
package br.com.sistema.entidade;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="TB_Carrinho")
@IdClass(CarrinhoDeComprasID.class)
public class CarrinhoDeCompras {

    @Id
    @ManyToOne
    @JoinColumn(name="id_produto")
    private Produto produto;

    @Id
    @ManyToOne
    @JoinColumn(name="id_venda")
    private Venda venda;

    private Integer quantidade;

    public Produto getProduto() {
        return produto;
    }

    public void setProduto(Produto produto) {
        this.produto = produto;
    }

    public Venda getVenda() {
        return venda;
    }

    public void setVenda(Venda venda) {
        this.venda = venda;
    }

    public Integer getQuantidade() {
        return quantidade;
    }

    public void setQuantidade(Integer quantidade) {
        this.quantidade = quantidade;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((produto == null) ? 0 : produto.hashCode());
        result = prime * result
                + ((quantidade == null) ? 0 : quantidade.hashCode());
        result = prime * result + ((venda == null) ? 0 : venda.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        CarrinhoDeCompras other = (CarrinhoDeCompras) obj;
        if (produto == null) {
            if (other.produto != null)
                return false;
        } else if (!produto.equals(other.produto))
            return false;
        if (quantidade == null) {
            if (other.quantidade != null)
                return false;
        } else if (!quantidade.equals(other.quantidade))
            return false;
        if (venda == null) {
            if (other.venda != null)
                return false;
        } else if (!venda.equals(other.venda))
            return false;
        return true;
    }
}

package br.com.sistema.entidade;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name="TB_PRODUTO")
public class Produto implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Integer id;

    private String descricao;

    @Column(name="data_cadastro")
    @Temporal(TemporalType.DATE)
    private Date dataCadastro;

    private Double valor;

    @Column(name="quantidade_vendida")
    private Integer quantidadeVendida = 0;

    //Construtores
    public Produto() {
    }

    public Produto(String descricao, Date dataCadastro,
            Double valor) {
        this.descricao = descricao;
        this.dataCadastro = dataCadastro;
        this.valor = valor;
    }

    // Get's e Set's
    public Integer getId() {
        return id;
    }

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

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public Date getDataCadastro() {
        return dataCadastro;
    }

    public void setDataCadastro(Date dataCadastro) {
        this.dataCadastro = dataCadastro;
    }

    public Double getValor() {
        return valor;
    }

    public void setValor(Double valor) {
        this.valor = valor;
    }

    public Integer getQuantidadeVendida() {
        return quantidadeVendida;
    }

    public void setQuantidadeVendida(Integer quantidadeVendida) {
        this.quantidadeVendida = quantidadeVendida;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((dataCadastro == null) ? 0 : dataCadastro.hashCode());
        result = prime * result
                + ((descricao == null) ? 0 : descricao.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime
                * result
                + ((quantidadeVendida == null) ? 0 : quantidadeVendida
                        .hashCode());
        result = prime * result + ((valor == null) ? 0 : valor.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Produto other = (Produto) obj;
        if (dataCadastro == null) {
            if (other.dataCadastro != null)
                return false;
        } else if (!dataCadastro.equals(other.dataCadastro))
            return false;
        if (descricao == null) {
            if (other.descricao != null)
                return false;
        } else if (!descricao.equals(other.descricao))
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (quantidadeVendida == null) {
            if (other.quantidadeVendida != null)
                return false;
        } else if (!quantidadeVendida.equals(other.quantidadeVendida))
            return false;
        if (valor == null) {
            if (other.valor != null)
                return false;
        } else if (!valor.equals(other.valor))
            return false;
        return true;
    }
}

package br.com.sistema.entidade;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name="TB_VENDA")
public class Venda implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    @Column(name="venda_id")
    private Integer vendaId;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="id_cliente", nullable=false) // No banco esse campo vai se chamar id_cliente | Não pode ser nulo
    private Cliente cliente;

    @OneToMany(mappedBy="venda")
    private List<CarrinhoDeCompras> produto;

    @Column(name="data_venda")
    @Temporal(TemporalType.DATE)
    private Date dataVenda;

    private Double valorTotal;

    @Column(name="flag_venda_ativa")
    private Integer flagVendaAtiva;

    //Construtor
    public Venda(){

    }

    public Venda(List<CarrinhoDeCompras> p, Cliente c){
        this.produto = p;
        this.cliente = c;
    }

    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

    public List<CarrinhoDeCompras> getProduto() {
        return produto;
    }

    public void setProduto(List<CarrinhoDeCompras> produto) {
        this.produto = produto;
    }

    public Date getDataVenda() {
        return dataVenda;
    }

    public void setDataVenda(Date dataVenda) {
        this.dataVenda = dataVenda;
    }

    public Integer getVendaId() {
        return vendaId;
    }

    public void setVendaId(Integer vendaId) {
        this.vendaId = vendaId;
    }

    public Double getValorTotal() {
        return valorTotal;
    }

    public void setValorTotal(Double valorTotal) {
        this.valorTotal = valorTotal;
    }

    public Integer getFlagVendaAtiva() {
        return flagVendaAtiva;
    }

    public void setFlagVendaAtiva(Integer flagVendaAtiva) {
        this.flagVendaAtiva = flagVendaAtiva;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((cliente == null) ? 0 : cliente.hashCode());
        result = prime * result
                + ((dataVenda == null) ? 0 : dataVenda.hashCode());
        result = prime * result
                + ((flagVendaAtiva == null) ? 0 : flagVendaAtiva.hashCode());
        result = prime * result + ((produto == null) ? 0 : produto.hashCode());
        result = prime * result
                + ((valorTotal == null) ? 0 : valorTotal.hashCode());
        result = prime * result + ((vendaId == null) ? 0 : vendaId.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Venda other = (Venda) obj;
        if (cliente == null) {
            if (other.cliente != null)
                return false;
        } else if (!cliente.equals(other.cliente))
            return false;
        if (dataVenda == null) {
            if (other.dataVenda != null)
                return false;
        } else if (!dataVenda.equals(other.dataVenda))
            return false;
        if (flagVendaAtiva == null) {
            if (other.flagVendaAtiva != null)
                return false;
        } else if (!flagVendaAtiva.equals(other.flagVendaAtiva))
            return false;
        if (produto == null) {
            if (other.produto != null)
                return false;
        } else if (!produto.equals(other.produto))
            return false;
        if (valorTotal == null) {
            if (other.valorTotal != null)
                return false;
        } else if (!valorTotal.equals(other.valorTotal))
            return false;
        if (vendaId == null) {
            if (other.vendaId != null)
                return false;
        } else if (!vendaId.equals(other.vendaId))
            return false;
        return true;
    }
}

Qual e a bronca que está acontecendo...
Quando eu executo o método salvar:
    @Override
    public void salvar(Object obj){
        try {
            abrirTransacao();
            this.em.persist(obj);
            fecharECommitarTransacao();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            rollback();
        }
    }

package br.com.sistema.entidade;

import java.io.Serializable;

public class CarrinhoDeComprasID implements Serializable{

    private int produto;
    private int venda;

    public int getProduto() {
        return produto;
    }

    public void setProduto(int produto) {
        this.produto = produto;
    }

    public int getVenda() {
        return venda;
    }

    public void setVenda(int venda) {
        this.venda = venda;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + produto;
        result = prime * result + venda;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        CarrinhoDeComprasID other = (CarrinhoDeComprasID) obj;
        if (produto != other.produto)
            return false;
        if (venda != other.venda)
            return false;
        return true;
    }
}

Ele só salva o objeto venda sem as referências, ou seja, salva na tabela de Vendas mas a de Carrinho fica vazia.
Alguém tem alguma solução ou ideia para esse problema?
Grato pela atenção.
Comment: Parceiro, caso queira algo para facilitar em seus projetos utilizando Hibernate, eis um link que poderá te ajudar: https://github.com/KaynanCoelho/generic-repository
Answer: Abra sua entidade Venda e onde você mapeou o Carrinho:
@OneToMany(mappedBy="venda")
private List<CarrinhoDeCompras> produto;

Adicione o Cascade:
@OneToMany(mappedBy="venda", cascade = {CascadeType.PERSIST, CascadeType.MERGE })
private List<CarrinhoDeCompras> produto;

Depois tente salvar novamente. Da uma lida sobre os Cascades que vai te ajudar bastante. Aqui tem um excelente artigo.
Answer: Você já debugou o seu código e verificou se o objeto que chega no método salvar está populado com os atributos da List. Sugiro você forçar a passagem de parametro antes de chamar o método salvar
Exemplo em sua controller voce pode fazer assim
public class MinhaController {
    private class Venda venda;
    private class Service service;
    private List<CarrinhoDeProdutos> produtosList;

    public void salvar() {
        venda.setProdutos(produtosList);
        service.salvar(venda);
    }
}

Comment: Sim sim, já conferir.
Esta quase dessa forma, mas posso te garantir que o objeto esta TODO populado.


Cannot see user_stats module logs in drupal site

Question: I have used  User Stats Module for the purpose to find the users login count till date.
I am able to see the data in database but can't find the logs in my drupal site.
I have checked in "Reports" but can't see. Please help.
Answer: Apart from some pages available under admin/reports/ip_tracking, which are visible when the Views module is enabled, and the "Track IP addresses" option is enabled on admin/settings/user_stats, the module doesn't show those values. You need to do one of the following:

Install the Advanced Forum module
Use user_stats_get_stats() in a template file

Reference

The module's README file (Drupal 7)
The module's README file (Drupal 6)


Proving that $(1-\sqrt{2})^{3000} < 10^{-100}$

Question: I am trying to prove  $(1-\sqrt{2})^{3000} < 10^{-100}$. The notes that I am looking at show the following steps.
$$
    (1-\sqrt{2})^{3000} < 10^{-100} \\
    1-\sqrt{2} < 10^{-1/30} \\
$$
The LHS is clearly a negative number and the RHS is positive. So the proof should be done at this point, correct?
In my lecture notes, I saw that the proof continued with the following step:
$$
    1-\sqrt{2} < 10^{-1/30} \\
    \frac{1}{(1-\sqrt{2})^{30}} > 10 \\
$$
The inequality was flipped, but I am confused why this occurred. I thought raising both sides to a negative exponent only require inequality flipping if the product of the base on both sides is positive? In this case, the LHS base is negative and the RHS base is positive, so their product is negative.
Comment: Note that $a^n < b^n$ is *not* equivalent to $a < b$ if $a$ or $b$ is negative.
Comment: @anomaly The former
Comment: The new equation is taking each side to the -30th power, which flips the inequality.
Comment: @amWhy Is this because $f(x) = x^{-1/3}$ is a decreasing function?
Comment: Are you trying to prove that $(1 - \sqrt{2})^{3000} < 10^{-100}$ or that $1 - \sqrt{2} < 10^{-100}$?
Comment: Your concerns are good ones: some of these intermediate steps are not correct or not useful steps in a correct proof.
Answer: Like this
\begin{align*}
&(1-\sqrt{2})^{3000} < 10^{-100} \\ \Longleftarrow\qquad
    &|1-\sqrt{2}| < 10^{-1/30}\\ \Longleftarrow\qquad
    &\sqrt{2}-1 < 10^{-1/30}\\ \Longleftarrow\qquad
    &(\sqrt{2}-1)^{-30} > 10\\ \Longleftarrow\qquad
    &\frac{1}{(\sqrt{2}-1)^{30}} > 10\\ \Longleftarrow\qquad
    &(\sqrt{2}+1)^{30} > 10\\ \Longleftarrow\qquad
    &(\sqrt{2}\;)^{30} > 10\\ \Longleftarrow\qquad
    &2^{15} > 10\\ \Longleftarrow\qquad
    &2^{4} > 10\\ \Longleftarrow\qquad
    &16 > 10
\end{align*}
Comment: Where did the absolute value come from? Is it because the $1-\sqrt{2}$ is negative and the exponent is even, so the LHS is originally a positive number, and we need to ensure that it stays positive when we're raising each side to $\frac{1}{3000}$?


How can I sample from the conditional distribution?

Question: I am learning Gibbs Sampling, in which there is a step named sampling from conditional distributions. I don't understand:
1. where is the conditional distribution from? From a general case, how can I get the conditional distribution?
Any help will be greatly appreciated.
Comment: Before trying to understand Gibbs sampling, you should learn the basics of [probability theory](http://en.wikipedia.org/wiki/Probability_theory) and read up on [conditional probability](http://en.wikipedia.org/wiki/Conditional_probability) on your own.
Comment: You get the conditional distribution from your model.
Answer: The goal is to generate samples for a multivariate distribution and its marginals, e.g. for the random vector $\mathbf{X} = (X_1, X_2, X_3)$, with pdf $f(x_1,x_2,x_3)$.

where is the conditional distribution from?

The conditional distributions, a.k.a. the full conditional distributions, are the distributions of each component random variable in the vector, conditional on the others, e.g. $X_1 | X_2=x_2, X_3=x_3$, and $X_2 | X_1=x_1, X_3=x_3$, and $X_3 | X_1=x_1, X_2=x_2$.

From a general case, how can I get the conditional distribution?

To get a full conditional, you treat the conditioning variables as constant in the multivariate pdf. E.g., to get the pdf for $X_1 | X_2=x_2, X_3=x_3$, you treat $x_2$ and $x_3$ as constant: the pdf $f(x_1|x_2,x_3)$ is obtained by simply starting with $f(x_1,x_2,x_3)$ and treating $x_2$ and $x_3$ as constant. What you hope is that you can recognize the core of the resulting pdf as a well-known univariate distribution, which you can easily sample from. Then, given a set of starting values, you sample from each full conditioning distribution in turn, using the most recent values of the conditioning variables.
Comment: You example is very helpful. I had another problem in learning Gibbs Sampling. It is hard for me to implement it. Could you suggest me some introductory books or notes that provide simple examples or codes to implement Latent Dirichlet allocation using Gibbs sampling?
Comment: happy to have helped. Sorry I can't help with your follow-up question. Why not post another question on cross validated (giving a few more details of what you've tried / looked at so far)?


$\arctan x=\frac{1}{2}i[\ln(1-ix)-\ln(1+ix)]$

Question: In wikipedia it says,
$$\arctan x=\frac{1}{2}i[\ln(1-ix)-\ln(1+ix)]$$
I want to now why is this true and what does a logarithm of a complex number even mean. I'm guessing that if I use the Taylor series I can prove this result.
Thanks
Comment: If we are willing for a while to operate formally, we can write $1+x^2=(1+ix)(1-ix)$, then express $\frac{1}{(1+ix)(1-ix)}$ as $\frac{A}{1-ix}+\frac{}{1+ix}$ using partial fractions machinery, and integrate.
Comment: If you want the link with the complex logarithm, see https://en.wikipedia.org/wiki/Complex_logarithm#Definition_of_principal_value and https://en.wikipedia.org/wiki/Atan2. It is what do you need to find the proof.
Comment: I also think Taylor works, but I found this would be a bit boring.. maybe there is a more creative/insightful approach.
Answer: As $e^{i\varphi} = \cos\varphi + i\sin\varphi$ we get
$$
\sin \varphi = \frac{e^{i\varphi} - e^{-i\varphi}}{2i}, \quad \cos\varphi = \frac{e^{i\varphi} + e^{-i\varphi}}{2}
$$
which leads to
$$
\tan \varphi = \frac{e^{i\varphi} - e^{-i\varphi}}{i(e^{i\varphi} + e^{-i\varphi})}.
$$
Let $\tan \varphi = x$, then
$$
\frac{e^{i\varphi} - e^{-i\varphi}}{e^{i\varphi} + e^{-i\varphi}} = ix
$$
and solving it we find that
$$
e^{i\varphi} = \sqrt{\frac{1 + ix}{1 - ix}}
$$
which leads us to
$$
\arctan x = \varphi = \frac{1}{i}\ln\sqrt{\frac{1 + ix}{1 - ix}} = \frac{i}{2}\left[\ln(1 - ix) - \ln(1 + ix)\right].
$$
Comment: @Ahmed S. Attaalla I've edited my post, does it look clear now?
Comment: Yes thank you. It is clear now.
Comment: Can we do this backwards? Ie NOT already assuming Euler's formula, NOR the complex definition of sine etc. I start with only that there is an obvious link between arctan and complex logarithms through integrating 1/(1+x^2) and its 2 equivalent complex factors. This gets me to the equation in the title. Rearranging gets me to the penultimate equation (above) with the square root of the ratio of complex numbers. However in my quest to move backwards toward Euler's formula from here, I cannot get to the previous equation where the ratio of the complex exponentials.= ix. How should I move on?
Answer: We know
$$\int \frac{dx}{1+x^2}=\arctan(x) +c_1$$
Now notice
$$\int \frac{dx}{1+x^2}=1/2\int \frac{1}{1+ix}+\frac{1}{1-ix} dx$$
$$=\frac{1}{2i}[\ln(1+ix)-\ln(1-ix)]+c_2$$
Expanding the fraction $\frac{1}{2i}$ with i and comparing both expressions results in:
$$\arctan(x)=\frac{i}{2}[\ln(1-ix)-\ln(1+ix)]+c_3.$$
Plug in $x=0$ to determin $c_3=0$.
Answer: There is a nice geometrical interpretation of this too. Sadly I'm on mobile so I can't include an image right now but it works like this:
When a complex number is represented in an  Argand diagram (i.e. as a point on the plane where the $x$-coordinate is the real part and the $y$-coordinate is the imaginary part) one can consider the distance from the origin (the modulus) and the angle anti-clockwise from the real ($x$) axis to the number (that is, the line from the origin to the number), called the argument. When a number is below the real axis we consider the angle as negative rather than bigger than $\pi$.
Consider how complex exponential works:
$$\mathrm e^{x+\mathrm i y} = \mathrm e^x(\cos y + \mathrm i \sin y).$$
Thus we see that the logarithm of a complex number should be a complex number where the real part is the logarithm of the modulus and the imaginary part is the argument. We ignore the problems where there are multiple values this could be and will say that the imaginary part is between $-\pi$ and $\pi$. It will turn out we don't need to think about what e.g. $\log(-1)$ should be.
Now we come back to the identity in question. First we let $x>0$ be a real number (certainly the identity is true if $x=0$) and we rearrange the right hand side to get:
$$\arctan x = \frac1{2\mathrm i}\left[\log(1+\mathrm i x) - \log(1-\mathrm i x)\right].$$
Draw an Argand diagram. Label the origin $O$ and now label the point $(1,x)$ (corresponding to $1+\mathrm i x$) by $A$ and the point $(1,-x)$ by $B$. Finally label the point $(1,0)$ by $C$.
We see that the real parts of both logarithms must be the same (as $OA$ and $OB$ have the same length). The imaginary part of the first logarithm is the angle $\widehat{COA}$ and the imaginary part of the second is negative the angle $\widehat{BOC}$. Thus the difference of the logarithms will be the number $2\mathrm i \theta$ where $\theta$ is the angle $\widehat{COA}$ (equal to $\widehat{BOC}$ by symmetry). Thus the right hand side of the equation is equal to $\theta$. However we consider the right triangle $ACO$ and see that $$\tan \theta = \frac{|AC|}{|OC|}=x. $$
Thus we have proven the identity for positive $x$. The same reasoning follows for the identity for negative $x$.
Answer: If $\arctan x=y,$
$$\ln(1-ix)-\ln(1+ix)=\ln\dfrac{1-ix}{1+ix}=\ln\dfrac{1-i\tan y}{1+i\tan y}=\ln(e^{-2iy})=-2iy$$
Comment: I don't see how all those tangents turned into an exponential. Can you please explain.
Comment: @AhmedS.Attaalla, $$\dfrac{1-i\tan y}{1+i\tan y}=\dfrac{\cos y-i\sin y}{\cos y+i\sin y}=\dfrac{e^{-iy}}{e^{iy}}=?$$


plot these points xy in c3.js

Question: I'm trying to generate a "scatter plot" chart in c3.js. My problem occurs when I want to plot these points. in c3.js the points do not match the real points in the plane.

what am I doing wrong?.
these are the points:
//x
['data1', 1,2,3,4,5,4,3,2,1],
//y
['data2', 2,3,4,7,8,9,8,7,3]

https://jsfiddle.net/qrqquhvd/
  var chart = c3.generate({
    data: {
      xs: {
        data1: "data2"
      },
      columns: [
        ['data1', 1,2,3,4,5,4,3,2,1],
        ['data2', 2,3,4,7,8,9,8,7,3]
      ],
      type: 'scatter'
    }
  });

Answer: You have your (X,Y) coordinates mixed up, look at the c3 plot vs your real plot.  On the real plot your first point is (1,2) but on your c3 plot you have it as (2,1).
Either swap the values of data1 and data2 like so...
columns: [
  ['data1', 2,3,4,7,8,9,8,7,3],
  ['data2', 1,2,3,4,5,4,3,2,1]
],

Or change the xs to
xs: {
  data2: "data1"
},

Comment: I thank you very much for your time. But it does not work either. the graph is still the same.
Comment: @yavg Make sure you do either the first suggestion or the second, but not both... Take a look at https://jsfiddle.net/8bccg0nh/ I just swapped the data1 and data2 values and it works correctly.
Comment: what is the xs attribute used for?
Comment: "Specify the keys of the x values for each data." - http://c3js.org/reference.html#data-xs, so you're saying the you have the data1 values and data2 values, and it works like `xs: { y_values: x_values }`.  Alternatively, you can explicitly define the points that are x and y like this https://jsfiddle.net/xks5dfag/
Comment: Thank you! can you help me whit thits? https://stackoverflow.com/questions/46325699/my-chart-lines-are-not-in-order

plot these points xy in c3.js


TCP Port prioritizing on switch/router (QoS)

Question: I have some HP ProCurve series Switch. There is a QoS option for prioritize traffic by TCP/UDP port. I set two ports: one with highest priority and another with lowest. Then I performed tests to ensure that prioritizing really works. I run two instances (per computer) of Network Benchmark application on two computers being in the LAN. One computer acts like server and other like client. In benchmark applications I set two ports configured earlier on the switch. Then I run tests, so that server sends some amount of data to client showing current transmission speed. I assumed that, since one port has higher priority then other, the transmission speed will not be equal, and the traffic going throughout the tcp port with higher priority will be significant faster. Unfortunately there is no difference. The speeds are nearly equal (half of bandwidth) and non prioritizing seems to be applied.
Can anyone explain me why this is not working. I suppose that I misunderstand some QoS basics and this is a reason, but I will be grateful if someone clarify this issue for me.
Answer: Priority on the Switch will have no effect in your test because the sending computer's NIC is the bottleneck. The switch is seeing 1Gb (or 100Mb) of input, sees a path at that same speed and sends the data along happily. If it has to choose what data to send, then it would prioritize.
Comment: As I mentioned under Oliver's reply, I've tried to limit my client bandwidth using NetLimiter (www.netlimiter.com) without any effect. Transmission speed was still divided equally for both clients apps, despite client's bandwith was much tighter than server's one.
Comment: The switch would still see two ports of the same speed. The switch doesn't magically know what the software on the computers is doing. It only shovels from one port to another, and if there's bandwidth on those physical ports then QoS is never going to be factored.
Answer: The priority setting only comes into play when a resource is limited - so if both 1G servers were transmitting at full speed to another 1G host there would be twice as much traffic as the destination link could handle.  The switch would then, in theory, reference the relative priority of the frames to determine which would be transmitted and which would be dropped.
Note that there may be multiple mechanisms that you can select to perform evaluation and drops and that each may yield different results (not very familiar with HP's network gear) - for example a 2:1 ratio of high to low priority packets (vs all high and no low)
Comment: As I mentioned under Oliver's reply, I've tried to limit my client bandwidth using NetLimiter (www.netlimiter.com) without any effect. Transmission speed was still divided equally for both clients apps, despite client's bandwith was much tighter than server's one.
Comment: The switch can handle full bandwidth and will hand off full bandwidth regardless of whether you're limiting inbound traffic.  The switch port itself needs to be overloaded to see any effect.  Bring a third machine into the mix and send 2G -> 1G and you'll see the queueing work.
Answer: You might be able to verify if your QoS configuration works by configuring the speed of the ports where the sender and the receiver is to 100 Mbps (sender) and 10 Mbps (receiver). That way, provided that your sender is able to create more than 10 Mbps of traffic, you should overload your switch port and force the switch to prioritize.
If your sender is fast enough, you can also do that experiment at 1 Gbps and 100 Mbps.
Comment: How can I configure the speed? I've tried to limit my client bandwidth using NetLimiter (www.netlimiter.com), without any effect. Transmission speed was still divided equally for both clients apps.
Comment: I'm not sure if your switch allows to do this, but usually this is in the ports configuration. You usually can configure duplex and speed settings. Hope that helps.
Comment: Forget NetLimiter if you want your switch to prioritize. Your switch is designed to deliver the packets at wire speed.