text:
Q: How to see values in boost:unordered_map in debug mode with vs2010 I have the following code...
typedef boost::unordered_map<int, boost::unordered_map<int, float>* > User_item_rating_map;

As you can see, the value of the map is a pointer. How can I get the value in the map. If I use (*(ret[int]))[int], I can't seem to get the value. What am I doing wrong?

A: The file AUTOEXP.DAT is the file that tells Visual Studio how to represent data structures in the debugger.
Some of the descriptions can be quite easy, like this one for CSize:
CSize =cx=<cx> cy=<cy>

But they can also be very complex, like this one for bitset:
std::bitset<*>{
    preview
    (
        #(
        "[",
            $c.digits,
        "](",
        #array
        (
            expr :  ($c._Array[$i / $c._Bitsperword] >> ($i % $c._Bitsperword)),
            size :  $c.digits
        ) : [($e & 1),d],
        ")"
        )
    )
    children
    (
        #array
        (
            expr :  ($c._Array[$i / $c._Bitsperword] >> ($i % $c._Bitsperword)),
            size :  $c.digits
        ) : (bool)($e & 1))
}

You can either write your own description for the boost unordered_map, or possibly someone else already did it for you.  Take a look at https://svn.boost.org/trac/boost/ticket/4209 (this seems like the thing you need).

A: I had the same trouble, went to see whether the suggested fix from Boost Ticket #4209 worked, which didn't. I could see the total number of the elements, but not the content.
So, the choices are, to switch to VS2012, for which there is a Plug-In, or invest in figuring out the format in VS2010 and fixing the existing suggested code.
Or, and that's what I did, use std::tr1::unordered_set / map instead. There is a visualizer for it in Visual Studio. And, later on, after debugging, if you wish, switch back to boost.

A: Open your file autoexp.dat with a text editor.
You usually find it in:

C:\Program Files\Microsoft Visual Studio 10.0\Common7\Packages\Debugger\autoexp.dat

Add the following code to the section [Visualizer]. This code should be added after the definition of another visualizer.
;------------------------------------------------------------------------------
;  boost unordered collections
;------------------------------------------------------------------------------
boost::unordered::unordered_map<*,*,*,*,*>{
    preview (
    #(
        "[",
        $e.table_.size_,
        "](",
        #list(
            head: $e.table_.buckets_[$e.table_.bucket_count_].next_,
            size: $e.table_.size_,
            next: next_
        ) : #(*((std::pair<$T1 const ,$T2>*)&(*(boost::unordered::detail::ptr_node<std::pair<$T1 const ,$T2> > *)(&$e)).value_base_)),
        ")"
    ))
    children(
    #(
        size: ($e.table_.size_),
        #list(
            head: $e.table_.buckets_[$e.table_.bucket_count_].next_,
            size: $e.table_.size_,
            next: next_
        ) : #(*((std::pair<$T1 const ,$T2>*)&(*(boost::unordered::detail::ptr_node<std::pair<$T1 const ,$T2> > *)(&$e)).value_base_)),
    ))
}

boost::unordered::unordered_set<*,*,*,*>{
    preview (
    #(
        "[",
        $e.table_.size_,
        "](",
        #list(
            head: $e.table_.buckets_[$e.table_.bucket_count_].next_,
            size: $e.table_.size_,
            next: next_
        ) : #(*(($T1*)&((*(boost::unordered::detail::ptr_node<$T1>*)(&$e)).value_base_))),
        ")"
    ))
    children(
    #(
        size: ($e.table_.size_),
        #list(
            head: $e.table_.buckets_[$e.table_.bucket_count_].next_,
            size: $e.table_.size_,
            next: next_
        ) : #(*(($T1*)&((*(boost::unordered::detail::ptr_node<$T1>*)(&$e)).value_base_))),
    ))
}

For instance I have added it before the rows
;------------------------------------------------------------------------------
;  std::plus, etc. from <functional>
;------------------------------------------------------------------------------

On your next debug session it should work.
I've tested it with Microsoft Visual Studio 2010 Version 10.0.40219.1 SP1Rel and boost 1.61.0.


text:
Q: rate of change proportional to the diffrence between itself and a fixed value $\frac{dy}{dx}=k(y-a)$ So I have a question regarding exponential growth/decay problem formulated in my book.
In my book they say:
"Sometimes an exponential growth or decay problem will involve a quantity that changes at a rate proportional to the difference between itself and a fixed point:
$\frac{dy}{dx}=k(y-a)$
In this case, the change of dependent variable $u(t)=y(t)-a$ should be used to convert the differential equation to the standard form. Observe that $u(t)$ changes at the same rate as $y(t)(ie,\frac{du}{dy}=\frac{dy}{dt}) so it satisfies
$\frac{du}{dt}=ku$"
I am having a hard time grasping what they mean. And I would hope for somebody to expand on this notion.
More specifically how does $\frac{dy}{dx}=k(y-a)$ relate to $u(t)=y(t)-a$?

A: since we have $$u(t)=y(t)-a$$ we get by differentiating with respect to $t$
$$\frac{du}{dt}=\frac{dy}{dt}$$ (since a is const.)
so we get
$$\frac{du(t)}{dt}=k\cdot u(t)$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to remove the border around the image that is generated by ? I am developing an ASP.NET web application and I have some images in the images slider without any links, so now when I put the images between anchor tags I got a border (in a purple color) around each image just in the Internet Explorer and I don't know why. In Firefox, everything works fine. So how to fix that in the IE browser?

A: What slider?
if you want to remove borders from all the images in  tags
you can use the following css rule:
a img {
   border:none;
}

... every IE sometimes has problems with style="border-style:none"
use style="border:none" instead

A: Set the border-style property to none.
img { border-style: none; }

A: This example uses the style attribute to define the border style:

A: a img {
    border: medium none;
}

Hope this helps.


text:
Q: What's a good approach for loading a YAML config in Ruby but setting default values? I am going to load some app configurations from a YAML file:
# YAML config file
app_name: "Example"
app_path: ~/path/to/app

So I load them:
app_config = YAML::load_file("config.yml")

What would be a clean way to set defaults if some key/value is missing?

A: You should prepare a default hash, and then overwrite the values from the configure by merging the hash.
default_app_config = {
  "app_name" => "Default name",
  "app_path" => "default/path",
  ...,
}

app_config = default_app_config.merge(YAML.load_config("config.yml"))

A: Since app_config would simply be a Hash at the point that you've loaded your YAML config, you can use Hash-like tests, like this:
name = app_config['name'] || 'default'

This works great if you have a very minimal number of these checks to make, particularly if they're located right near the point that you load the YAML config.
However, you can update your config hash with the defaults, like this:
app_config['name'] ||= 'default'

That way, you don't have to keep checking to see if the key exists throughout the rest of your code.
Something like this at the point that you load the YAML might work:
app_config = YAML::load_file("config.yml")

# Set default values
app_config['app_name'] ||= "Example"
app_config['app_path'] ||= "~/path/to/app"

That will keep the rest of your code simple and uncomplicated by applying default values.  These are DRY defaults for YAML config files.


text:
Q:  not invoked when using with  I'm using PrimeFaces 5.3 and I got a issue when trying to use f:setPropertyActionListener with p:confirm in a p:commandButton.
The dialog is shown but the setter method defined in f:setPropertyActionListener is not invoked when it is used with p:confirm. So my bean attribute called produtoSelecionado is not set properly.
My XHTML code:
    <h:form id="produtosForm">
        ...
        <p:dataTable ...>
            ...
                <p:commandButton
                    icon="ui-icon-trash"
                    title="Excluir"
                    process="@this :dialogExclusao"
                    update=":dialogExclusao :produtosForm:produtosTable"
                    oncomplete="PF('dialogExclusao').show()">
                    <f:setPropertyActionListener
                        value="#{produto}"
                        target="#{pesquisaProdutosBean.produtoSelecionado}" />
                    <p:confirm
                        header="Exclusão de produto"
                        message="Tem certeza que deseja excluir o produto #{pesquisaProdutosBean.produtoSelecionado.sku}?"
                        icon="ui-icon-trash" />
                </p:commandButton>
            </p:column>
        </p:dataTable>

    </h:form>

    <component:dialog-exclusao
        id="dialogExclusao"
        updateComponents=":produtosForm:produtosTable"
        yesAction="#{pesquisaProdutosBean.excluir}" />

The custom component defined above called dialog-exlusao is a global generic p:confirmDialog, that is used in multiple pages in the project:
<composite:interface>
<composite:attribute
    name="yesAction"
    method-signature="void yesAction()" />
<composite:attribute name="updateComponents" />
</composite:interface>

<composite:implementation>
    <p:confirmDialog
        id="dialogConfirmacaoExclusao"
        global="true"
        widgetVar="dialogConfirmacaoExclusao">

    <p:button
        value="Não"
        styleClass="ui-confirmdialog-no"
        onclick="PF('dialogConfirmacaoExclusao').hide(); return false;" />
    <p:commandButton
        value="Sim"
        oncomplete="PF('dialogConfirmacaoExclusao').hide()"
        styleClass="ui-confirmdialog-yes"
        process="@this"
        update="dialogConfirmacaoExclusao #{cc.attrs.updateComponents}"
        action="#{cc.attrs.yesAction}" />
</p:confirmDialog>

Below my bean attribute with its getter and setter:
@Named
@ViewScoped
public class PesquisaProdutosBean implements Serializable {

private static final long serialVersionUID = 1L;

private Produto produtoSelecionado;

...
public Produto getProdutoSelecionado() {
    return produtoSelecionado;
}

public void setProdutoSelecionado(Produto produtoSelecionado) {
    this.produtoSelecionado = produtoSelecionado;
}

}

When I remove p:confirm tag, f:setPropertyActionListener is triggered correctly!
Is it a PF bug? How can I show the dialog in my custom component and set the bean attribute at same time, in the click of commandButton?
tks!


text:
Q: Create a new price attribute for the product I want to add a price attribute for my product.
So I can add this to my product as a decimal attribute but...I don't know how to give him the options in order that this attribute comes out with the same render as existing price in the product form. Tried to investigate the magento catalog and the magento wee tax but I didn't found anything very understandable.
I want to come out with that result: any idea ?

A: $eavSetup->addAttribute(
            Product::ENTITY,
            'price_kg',
            [
                'group' => 'General',
                'sort_order' => 30,
                'type' => 'decimal',
                'backend' => Price::class,
                'frontend' => '',
                'label' => 'Prix au Kg',
                'input' => 'price',
                'class' => '',
                'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
                'visible' => true,
                'required' => false,
                'user_defined' => false,
                'default' => '',
                'searchable' => true,
                'filterable' => false,
                'comparable' => true,
                'visible_on_front' => true,
                'used_in_product_listing' => true,
                'unique' => false,
                'apply_to' => ''
            ]
        );

Not exactly the same rendering though but it works


text:
Q: Ошибка при освобождении памяти Добрый день, суть вопроса заключается в том, что когда я пытаюсь очистить память во этом фрагменте кода, срабатывает ошибка -
else {
        RecordBook *next, *prev = listOfStudents;
        current = listOfStudents;

        while (current->next && current->index != pos) {
            prev = current;
            current = current->next;
        }

        next = current->next;
        prev->next = next;

        //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        ***//Вот здесь срабатывает ошибка***
        delete current;
        current = NULL;
    }

Вообщем, просидел целый день, так и не понял в чем проблема. Смотрел через дебаггер, он показывает, что указатель указывает на действующую область памяти, так что в чем проблема я не понимаю. Прошу объяснить как можно исправить данную проблему, заранее спасибо!
#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;

class RecordBook {
public:
    void setName(string);
    string getName();
    void setLastName(string);
    string getLastName();
    void setScores(int, int, int, bool, bool, bool);
    void showScores();

private:
    string name;
    string lastName;

    int Math;
    int MathAnalysis;
    int Programming;

    bool English;
    bool PhysEducation;
    bool History;

    //Navigation
    size_t index = 0;
    RecordBook *next = nullptr;

    friend class Group;

};

class Group {
public:
    //Добавить студента
    void addStudent(string, string, int=5, int=5, int=5, bool=true, bool=true, bool=true);
    //Найти студента и вывести оценки
    void findStudent(string);
    //Вставить зачетную книжку в заданный индекс
    void insert(RecordBook &, size_t = 0);
    //Удалить зачетную книжку по заданному индексу
    void erase(size_t = 0);

private:
    //Динамический список студентов, который указывает на последнего студента
    RecordBook *listOfStudents;
    //Количество студентов
    size_t countOfElements = 0;

    //Создать новый узел для студента в динамическом списке
    void createOfNode(RecordBook &);
    //Обновить индексы динамического списка
    void updateOfIndex();

} mx101;

int main() {
    setlocale(0, "");

    mx101.addStudent("Al", "As");
    mx101.addStudent("Petya", "Petrov");

    RecordBook student;
    student.setName("vasya");
    student.setLastName("XXX");
    student.setScores(2, 3, 4, 1, 1, 0);

    mx101.insert(student, 1);
    mx101.erase(1);

    return 0;
}

void RecordBook::setName(string name1) {
    name = name1;
}

string RecordBook::getName() {
    return name;
}

void RecordBook::setLastName(string lastName1) {
    lastName = lastName1;
}

string RecordBook::getLastName() {
    return lastName;
}

void RecordBook::setScores(int M, int MA, int pr, bool En, bool Ph, bool Hi) {
    Math = M;
    MathAnalysis = MA;
    Programming = pr;

    English = En;
    PhysEducation = Ph;
    History = Hi;
}

void RecordBook::showScores() {
    printf("Name: %s, Last Name: %s\n", name.c_str(), lastName.c_str());
    printf("Math: %d, Math analysis: %d, Programming: %d\n", Math, MathAnalysis, Programming);
    printf(English ? "English: passed\n" : "English: didn't passed\n");
    printf(PhysEducation ? "PhysEducation: passed\n" : "PhysEducation didn't passed\n");
    printf(History ? "History: passed\n" : "History: didn't passed\n");
    cout << endl;
}

void Group::addStudent(string name, string lastName, int a, int b, int c, bool d, bool e, bool f) {
    RecordBook student;
    student.setName(name);
    student.setLastName(lastName);
    student.setScores(a, b, c, d, e, f);

    createOfNode(student);
}

void Group::createOfNode(RecordBook &elem) {
    RecordBook *current = new RecordBook;

    if (countOfElements == 0) {
        *current = elem;
        current->next = nullptr;
        current->index = countOfElements++;

        listOfStudents = current;
    }
    else {
        *current = elem;
        current->index = countOfElements++;
        current->next = listOfStudents;

        listOfStudents = current;
    }
}

void Group::findStudent(string str) {
    RecordBook *current = listOfStudents;

    do {
        if (!current->getName().compare(str) || !current->getLastName().compare(str)) {
            current->showScores();

            return;
        }
        else {
            current = current->next;
        }
    } while (current);

    cout << "Ничего не найдено" << endl;
}

void Group::insert(RecordBook &elem, size_t pos) {
    if (pos < 0 || pos > countOfElements) cout << "Неверный индекс" << endl;
    else {
        RecordBook *current = NULL;

        if (pos == 0) {
            current = listOfStudents;

            while (current->next) {
                current = current->next;
            }

            current->next = &elem;
        }
        else if (pos == countOfElements) {
            current = new RecordBook;

            current = &elem;
            current->next = listOfStudents;
            listOfStudents = current;
        }
        else {
            RecordBook *next = NULL;
            current = listOfStudents;

            while (current->next && current->index != pos) {
                current = current->next;
            }

            RecordBook *item = new RecordBook;
            next = current->next;

            item = &elem;
            item->next = next;

            current->next = item;
        }

        countOfElements++;
        updateOfIndex();
    }
}

void Group::erase(size_t pos) {
    if (pos < 0 || pos > countOfElements - 1) cout << "Неверный индекс" << endl;
    else {
        RecordBook *current;

        if (pos == 0) {
            current = listOfStudents;

            while (current->next->next) {
                current = current->next;
            }

            delete current->next;
            current->next = NULL;
        }
        else if (pos == countOfElements - 1) {
            current = listOfStudents;
            listOfStudents = listOfStudents->next;

            delete current;
            current = NULL;
        }
        else {
            RecordBook *next, *prev = listOfStudents;
            current = listOfStudents;

            while (current->next && current->index != pos) {
                prev = current;
                current = current->next;
            }

            next = current->next;
            prev->next = next;

            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            ***//Вот здесь срабатывает ошибка***
            delete current;
            current = NULL;
        }

    }
}

void Group::updateOfIndex() {
    RecordBook *current = listOfStudents;
    size_t acc = countOfElements - 1;

    while (current->next) {
        current->index = acc--;
        current = current->next;
    }
}

A: Вы добавляете в динамический список объект RecordBook student; на стеке. Соответственно попытка delete current; приводит к неопределенному поведению. Кроме того, поле RecordBook *listOfStudents; остается неинициализированным.


text:
Q: Jquery autocomplete variable not working Is there any reason why the following might not pass the "checkit" variable onto the countryselect.php page?
$(function () {
    $('#abbrev').val("");
    $('#country').on('change', function () {
        alert($("#country").val());
    });
    $("#state").autocomplete({
        source: "/countrycomplete.php?checkit=" + $("#country").val(),
        minLength: 2,
        select: function (event, ui) {
            $('#state_id').val(ui.item.id);
            $('#abbrev').val(ui.item.abbrev);
        }
    });
});

The alert () is there just to see if the variable is there, and this produces the expected result. However, this line, - source: "/countrycomplete.php?checkit="+$( "#country").val(), - does not send the variable on to countrycomplete.php
Any ideas?
I have gone through a number of other posts here related to the same question, but none so far have presented a working solution....I bet there must be some really tiny mistake, but...so far I haven't been able to find it.
EDITED VERSION:
$(function() {
    $('#abbrev').val("");
    $('#country').on('change', function(){
        $( "#state" ).autocomplete({
            "option",
            "source",
            "/countrycomplete.php?checkit="+$(this).val(),
            minLength: 2,
            select: function(event, ui) {
                $('#state_id').val(ui.item.id);
                $('#abbrev').val(ui.item.abbrev);
            }
        });
    });
});

Thanks in advance!

A: It's because the autocomplete plugin is initialized on page load and gets the value of the input at that time, and since the input at page load is probably empty the value is empty as well.
You need to update the autocomplete's URL when the input value changes. You don't mention which autocomplete plugin this is, but assuming it's the jQuery UI one you'd do it this way:
$('#country').on('change', function(){
    $( "#state" ).autocomplete(
        "option",
        "source",
        "/countrycomplete.php?checkit="+$(this).val()
    );
});

(Unrelated side note: don't use alert() for debugging.)

A: $(function(){
$(".selector").autocomplete({
   source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"],
   select: function (event, ui) {
   var state = ui.item.value;
   console.log(state);
   $('#state_id').val(state);}
  });
});

see http://jsfiddle.net/DrDrQ/


text:
Q: ndk-build error using cygwin I installed ndk and vuforia. The ndk path is C:\Development\Android\android-ndk-r9b then set this path to system variable. The cygwin path is C:\cygwin\bin then set this path to system variable. The vuforia path also correct. When build the sample ndk examples and when i run the vuforia sample i'm getting below error in cygwin command window. I can't run my project using ndk-build
Arun@Arun-PC ~
$ cd D:\\AugmentedReality\\vuforia\\vuforia-sdk-android-2-5-7\\samples\\ImageTargets-2-6-7

Arun@Arun-PC /cygdrive/d/AugmentedReality/vuforia/vuforia-sdk-android-2-5-7/samples/ImageTargets-2-6-7
$ ndk-build
[armeabi] Gdbserver      : [arm-linux-androideabi-4.6] libs/armeabi/gdbserver
[armeabi] Gdbsetup       : libs/armeabi/gdb.setup
[armeabi-v7a] Gdbserver      : [arm-linux-androideabi-4.6] libs/armeabi-v7a/gdbserver
[armeabi-v7a] Gdbsetup       : libs/armeabi-v7a/gdb.setup
[armeabi] Compile++ arm  : ImageTargets <= ImageTargets.cpp
/bin/sh: /cygdrive/c/Development/Android/android-ndk-r9b/toolchains/arm-linux-androideabi-4.6/prebuilt/windows/bin/arm-linux-androideabi-g++: No such file or directory
/cygdrive/c/Development/Android/android-ndk-r9b/build/core/build-binary.mk:386: recipe for target 'obj/local/armeabi/objs-debug/ImageTargets/ImageTargets.o' failed
make: *** [obj/local/armeabi/objs-debug/ImageTargets/ImageTargets.o] Error 127

A: I was having a lot of issues building Android NDK projects on Windows. Most places suggested using cygwin, I found a solution that didn't need it and wrote up a blog post on it: http://ghoofman.com/android-ndk/
Hope that helps.


text:
Q: Error de compilacion: The method findOne(long) is undefined for the type UsuarioCrud ] a ver si me puede ayudar alguien porque me surge un error en la compilación del editar y borrar y no sé porque es
    The method findOne(long) is undefined for the type UsuarioCrud
] with root cause

java.lang.Error: Unresolved compilation problem:
    The method findOne(long) is undefined for the type UsuarioCrud

at com.inezpre5.controlador.ControladorCrud.editar(ControladorCrud.java:63) ~[classes/:na]

Os muestro mis clases
clase usuario
package com.inezpre5.modelo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.Email;
//import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.NotEmpty;

@Entity
public class Usuario {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @NotEmpty
    @Length(min=5, max=24)
    private String nombre;
    @NotEmpty
    @Length(min=10, max=24)
    private String password;
    @NotEmpty
    @Email
    private String email;

    public Usuario() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Usuario(String nombre, String password, String email) {
        this.nombre = nombre;
        this.password = password;
        this.email = email;
    }

    public long getId() {
        return id;
    }

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

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

Interfaz
package com.inezpre5.modelo;

import org.springframework.data.repository.CrudRepository;

public interface UsuarioCrud extends CrudRepository<Usuario, Long>{

}

controlador
package com.inezpre5.controlador;

import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.inezpre5.modelo.Usuario;
import com.inezpre5.modelo.UsuarioCrud;

@Controller
@RequestMapping("/crud")
public class ControladorCrud {

@Autowired
private UsuarioCrud uc;

//aqui estarían listar y crear que funcionan perfectamente, el error me lo da el //findOne(id)

@RequestMapping(value="/editar/{id}", method=RequestMethod.GET)
public String editar(@PathVariable("id") long id, ModelMap mp){
    mp.put("usuario", uc.findOne(id));
    return "crud/editar";
}

@RequestMapping(value="/actualizar", method=RequestMethod.POST)
public String actualizar(@Valid Usuario usuario, BindingResult bindingResult, ModelMap mp){
    if(bindingResult.hasErrors()){
        mp.put("usuarios", uc.findAll());
    return "crud/lista";
    }
    Usuario user = uc.findOne(usuario.getId());
    user.setNombre(usuario.getNombre());
    user.setPassword(usuario.getPassword());
    user.setEmail(usuario.getEmail());
    uc.save(user);
    mp.put("usuario", user);
    return "crud/actualizado";
}
}

vista
    <!doctype html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
    crossorigin="anonymous">

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
    integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
    crossorigin="anonymous">

<title>Lista:Crud</title>

Lista de Usuarios

                        Id
                        Nombre
                        Contraseña
                        Email

 Nuevo Usuario

pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.inezpre5</groupId>
    <artifactId>CrudSpringBoot</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>CrudSpringBoot</name>
    <description>Crud Total con Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

A: El método findOne(id) se reemplazó por findById(id).
El nuevo método devuelve un Optional que permite manejar mejor los null, acá esta la documentación.
Con el nuevo método se puede imitar la funcionaliad anterior de esta forma:
User user = uc.findById(usuario.getId()).orElse(null);

Usando orElse() y métodos similares podés alterar lo que devuelve el método en caso de null, o incluso tirar una excepción.


text:
Q: Unable to start tweepy tweet scraper from other file my tweepy file works fine. It collects all German tweets.
Now it interrupts sometimetimes. Thus, I want to restart it with another python file.
The Tweepy file is called "Twython_36" and is started by my Scraper_Starter.py:
import threading
def printit():
    threading.Timer(15.0, printit).start()
    print("Scraper restartet.")
    exec(open("./twython_36.py").read())

printit()

Now I get this error
Traceback (most recent call last):
  File "<string>", line 42, in on_status
NameError: name 'langid' is not defined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/M/PycharmProjects/Bachelor_Thesis/Scraper_Starter.py", line 10, in <module>
    printit()
  File "C:/Users/M/PycharmProjects/Bachelor_Thesis/Scraper_Starter.py", line 7, in printit
    exec(open("./twython_36.py").read())
  File "<string>", line 81, in <module>
  File "C:\Users\M\Anaconda3\lib\site-packages\tweepy\streaming.py", line 445, in filter
    self._start(async)
  File "C:\Users\M\Anaconda3\lib\site-packages\tweepy\streaming.py", line 361, in _start
    self._run()
  File "C:\Users\M\Anaconda3\lib\site-packages\tweepy\streaming.py", line 294, in _run
    raise exception
  File "C:\Users\M\Anaconda3\lib\site-packages\tweepy\streaming.py", line 263, in _run
    self._read_loop(resp)
  File "C:\Users\M\Anaconda3\lib\site-packages\tweepy\streaming.py", line 324, in _read_loop
    self._data(next_status_obj)
  File "C:\Users\M\Anaconda3\lib\site-packages\tweepy\streaming.py", line 297, in _data
    if self.listener.on_data(data) is False:
  File "C:\Users\M\Anaconda3\lib\site-packages\tweepy\streaming.py", line 54, in on_data
    if self.on_status(status) is False:
  File "<string>", line 49, in on_status
NameError: name 'sys' is not defined

Langid is a library that enables me to scrape German tweets. It is installed.
Why is this code not working, even though if I start my Scraper "Twython_36.py" manually there is no error?
Any suggestions to fix this
Edit: A new error appeared. It asks for a logfile, but this logfile is defined. So I do not see the problem:
File "C:\Users\M\Anaconda3\lib\threading.py", line 914, in _bootstrap_inner
    self.run()
  File "C:\Users\M\Anaconda3\lib\threading.py", line 1180, in run
    self.function(*self.args, **self.kwargs)
  File "C:/Users/M/PycharmProjects/Bachelor_Thesis/Scraper_Starter.py", line 8, in printit
    exec(open("./twython_36.py").read())
  File "<string>", line 81, in <module>
  File "C:\Users\M\Anaconda3\lib\site-packages\tweepy\streaming.py", line 445, in filter
    self._start(async)
  File "C:\Users\M\Anaconda3\lib\site-packages\tweepy\streaming.py", line 361, in _start
    self._run()
  File "C:\Users\M\Anaconda3\lib\site-packages\tweepy\streaming.py", line 294, in _run
    raise exception
  File "C:\Users\M\Anaconda3\lib\site-packages\tweepy\streaming.py", line 249, in _run
    if self.listener.on_error(resp.status_code) is False:
  File "<string>", line 52, in on_error
N**ameError: name 'logfile' is not defined**

Relevant part of the code:
**# open log file
logfile = open('twython1.log', 'a')**

class CustomStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        global old_date
        global writer
        global outfile
        new_date = date.today()
        if not new_date == old_date:
            outfile.close
            outfile = codecs.open ("tweets-" + str(new_date) + ".txt", "ab", "utf-8")
            writer = csv.writer(outfile,quoting=csv.QUOTE_NONNUMERIC,lineterminator='\n')
            old_date = new_date
        try:
            lang = langid.classify(status.text)[0];
            if lang == "de":
                writer.writerow( (status.created_at, status.id_str, status.text) )
        except Exception, e:
            # Catch any unicode errors while printing to console
            # and just ignore them to avoid breaking application.
            sys.exc_clear()
#                pass

    **def on_error(self, status_code):
        logfile.write(str(time.asctime( time.localtime(time.time()) )) + ' Encountered error with status code:' + str(status_code) + "\n")
        return True # Don't kill the stream**


text:
Q: Opencart Product Page All Image Compression to Zip File For Download Hi I want to show an image gallery on my site and then have a link that allows the user to download the whole image gallery

*

*All the image automatically convert to the zip file & displayed button on product page to "download image"

Like This :-

A: Product.php
Create new function
public function downloadcatalog(){
$this->load->model('catalog/product');
        $product_info = $this->model_catalog_product->getProduct($this->request->get['product_id']);

        $results = $this->model_catalog_product->getProductImages($this->request->get['product_id']);

            foreach ($results as $result) {
                $files[] = 'image/'.$result['image'];
            }

        $zip = new ZipArchive();

        # create a temp file & open it
        $tmp_file = tempnam('.', '');
        $zip->open($tmp_file, ZipArchive::CREATE);

        # loop through each file
        foreach ($files as $file) {
            # download file
            $download_file = file_get_contents($file);

            #add it to the zip
            $zip->addFromString(basename($file), $download_file);
        }

        # close zip
        $zip->close();
        $file_name = $product_info['name'].'.zip';
        # send the file to the browser as a download
        /*header('Content-disposition: attachment; filename="'.$product_info['name'].'"');
        header('Content-type: application/zip');*/
        header("HTTP/1.1 200 OK");
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-type: application/zip");
        header('Content-Disposition: attachment; filename="'.$file_name.'"');
        header("Content-Transfer-Encoding: binary");
        header('Content-Length: ' . filesize($tmp_file));

        //$zip->close();
        //readfile($zipname);
                readfile($tmp_file);
                unlink($tmp_file);
            }

====================================================================
Product.php
(Index controller add before)
$data['column_left'] = $this->load->controller('common/column_left');

$data['download_catalog'] = $this->url->link('product/product/downloadcatalog', 'product_id=' . $this->request->get['product_id']);


text:
Q: Not able to upload image on server using Api in meteor I am using 'nimble:restivus' package of meteor to create a api for uploading the image.
HTML:
<form id="upload" onSubmit="upload()">
 <input type="file" id="avatar" name="avatar" />
 <input type="text" id="fname" name="fname" />
 <button type="submit">Submit</button>
</form>

Ajax Request:
var file_data = $("#avatar").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
form_data.append("userId", '8NrAn4sR3bKmXi84u');
form_data.append("fileName", file_data.name);
$.ajax({
    url: "http://localhost:3000/api/v1/uploadImages/",
    cache: false,
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    processData: false,
    data: form_data,
    type: 'POST'
});

Api Code:
var Api = new Restivus({
    version: 'v1',
    useDefaultAuth: true
});
Api.addRoute('uploadImages', { authRequired: false }, {
    post: function(){
        console.log("=====> UPLOAD IMAGES API <======");
        console.log("this.bodyParams -> ",this.bodyParams)
        return true;
    }
});

Server side Response(API):
Please check attached image for console output on server side--

When i submitting the form as POST, not able to get the image on server side. As i received body-params but when i tried to get image as this.bodyParams.file, it returns undefined.
Please guide me how i can image on server side after submitting the form.
Thanks.


text:
Q: How to serve a local website under a global domain using a proxy? Some time ago I saw a paid (IIRC) service that allowed to serve a local website under a global subdomain like shadow-zombies-1234.coolservice.com.
If I remember correctly it was about running some program on the local machine, which was connecting to their server and establishing a tunnel for the HTTP traffic. So if you sent GET / to shadow-zombies-1234.coolservice.com, that request was proxied to the local server.
I don't remember the name of the service and I cannot find it now, so I need your help.
PS. Not sure if this question is a good fit for Stack Overflow but neither Superuser nor Server Fault seem to be 100% good fits..
EDIT: I'm not trying to make a custom solution, I just forgot the name of the service and cannot find it on google. I guess there could be more than one of them now.

A: I received an answer from someone who doesn't have enough reputation to post it here himself (many thanks!):
You are referring to localtunnel.com, which is no longer available.
See
http://progrium.com/blog/2012/12/25/localtunnel-v2-available-in-beta/
The project https://github.com/progrium/localtunnel is currently down, so you can use
https://ngrok.com/
There are also http://localtunnel.me/ and https://meetfinch.com/.

A: Thomasz, I'm not quite sure what problem you're trying to solve. Hopefully this helps:
In order for a site to be visible globally, it must be have an external IP and, probably, DNS name.
If that IP is the address of a proxy, the server can be told to satisfy the request by passing it on to another server. If the proxying server has a tunnel or non-public interface as well as the public interface, the actual server can be non-public.
I can't see anything obvious with a quick search, but you could perhaps look into a low-cost or free AWS or similar server to host the proxy and a VPN tunnel to the actual host?


text:
Q: C# and SQL Batch Update Is there any API available similar to JDBC batch update [PreparedStatement.addBatch() and PreparedStatement.executeBatch() ]?
I have seen the DataAdapter. However I think it is using DataTable; is it similar to JDBC PreparedStatement?

A: PreparedStatements in JDBC are directly analogous to SqlCommand, right down to supplying the statement and parameters. Here's an example:
    var cmd = "UPDATE SomeTable SET Value = @Param1 WHERE ID = @ID";

    using (var connection = new SqlConnection("Connection String Here"))
    using (var command = new SqlCommand(cmd, connection))
    {
        command.Parameters.AddWithValue("@Param1", "NewValue");
        command.Parameters.AddWithValue("@ID", 1);
        connection.Open();
        command.ExecuteNonQuery();
    }

From what I've read, all the above should see very familiar for someone who uses PreparedStatement.


text:
Q: Phase plot of $x(t)=2i\sin(\pi t)e^{-i\pi t}$ I am asked to draw the phase of $x(t)=2i\sin(\pi t)e^{-i\pi t}$. The requested plot should look like:

When $t\in\mathbb{Z}$, the graph jumps from $-\pi/2$ to $\pi/2$. Both values mean that the function is 'fully' imaginary if $t\in\mathbb{Z}$, but $x(t)=0$. And why does the phase value decrease linearly between integers? Could you give me some hints? Thanks in advance!

A: From properties of phase we have that:
$$\angle x(t) = \angle 2i + \angle \sin(\pi t) + \angle e^{-i\pi t} = \frac{\pi}{2} + \pi k - \pi t$$
$\sin(\pi t)$ is always a real number, so its contribution to the phase will always be some integer multiple of $\pi$. Then using the convention that the phase is in the principal branch, i.e. $\angle x(t) \in (-\pi,\pi]$, look at the behavior of the $\pi k$ term. $\sin(\pi t)$ changes phase for every $t\in\mathbb{Z}$.
Now take the interval $(0,1)$ for example. On $(0,1)$, $-\frac{\pi}{2}\leq\frac{\pi}{2}-\pi t\leq \frac{\pi}{2}$ and $\sin(\pi t) > 0$, therefore $k$ must be an even integer. The only choice of even integer that keeps our phase in the principal branch is $k=0$. Playing with more cases, we get the following phase function as our final solution:
$$\angle x(t) = \frac{\pi}{2} - \pi t + \pi\lfloor t \rfloor = \frac{\pi}{2} - \pi \{t\}$$
where $\{t\}\equiv t - \lfloor t \rfloor$ is the fractional part of $t$.


text:
Q: How to close the One-Tap hint when user logs in with another method? I managed to implement the relatively new One-Tap sign-up/sign-in flows, following the get started guide here. I also have other login methods working on the same project (facebook login and email/password login). When the user logs in using one of these other methods, the One-Tap hint inviting the user to login with Google stays there, in the middle of my logged-in experience, as the hint was added to the page before the user was identified. In my login flow, I don't reload the page. I just replace/show/hide stuff on it. How can I close that Google invitation when the user decides to login with another method?

A: you can call this method, source
googleyolo.cancelLastOperation().then(() => {

// Credential selector closed.

});

A: This has changed to the following -
google.accounts.id.cancel();

Sign In With Google JavaScript API reference  |  Google Developers


text:
Q: How to parse data in a List from JSON data like following link using C#? How to parse data in a List from JSON data like following link using C# ?
{
    "voters": [{
        "id": "5644309456813",
        "name": "Rimi Khanom",
        "address": "House no: 12. Road no: 14. Dhanmondi, Dhaka",
        "date_of_birth": "1979-01-15"
    }, {
        "id": "9509623450915",
        "name": "Asif Latif",
        "address": "House no: 98. Road no: 14. Katalgonj, Chittagong",
        "date_of_birth": "1988-07-11"
    }, {
        "id": "1098789543218",
        "name": "Rakib Hasan",
        "address": "Vill. Shantinagar. Thana: Katalgonj, Faridpur",
        "date_of_birth": "1982-04-12"
    }, {
        "id": "7865409458659",
        "name": "Rumon Sarker",
        "address": "Kishorginj",
        "date_of_birth": "1970-12-02"
    }, {
        "id": "8909854343334",
        "name": "Gaji Salah Uddin",
        "address": "Chittagong",
        "date_of_birth": "1965-06-16"
    }]
}

A: try this :
public class Voter
{
    public string id { get; set; }
    public string name { get; set; }
    public string address { get; set; }
    public string date_of_birth { get; set; }
}

public class RootObject
{
    public List<Voter> voters { get; set; }
}

var VoterModel = JsonConvert.DeserializeObject<List<Voter>>(json);

A: You are getting an array of objects from the JSON. So all you need is to do a foreach on the voters. JavaScript objects are mapped to Dictionary<string, object> in C#. Pseudo code
using System.Web.Script.Serialization;
using System.Net;

using (var client = new WebClient())
{
    var url = "http://nerdcastlebd.com/web_service/voterdb/index.php/voters/all/format/json";
    var jsonString = client.DownloadString(url);
    var json = new JavaScriptSerializer().Deserialize<dynamic>(jsonString);
    foreach (Dictionary<string, object> voter in json["voters"])
    {
        var id = voter["id"].ToString();
        // pull name, address and date_of_birth here
    }
}


text:
Q: query execution time is more in NamedParameterJdbcTemplate than mySql I am using spring NamedParameterJdbcTemplate with my sql.I am executing 2 queries through jbdc template it is taking 1.1 and 4 s respectively. but the same query if I am running in my sql it is taking 0.5 and 1 s respectively I don't understand what could be my bottleneck. my application and db resides on same server so there can be no network overhead, I have my connection pooled. I can say it is working because query with less amount of data taking 50 ms through application. please let me know what could be my bottleneck
below is my code of namedjdbcTemplate
MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue("organizationIds", list);
        parameters.addValue("fromDate", fromDate);
        parameters.addValue("toDate", toDate);
        long startTime =  System.currentTimeMillis();
        List<MappingUI> list =namedParameterJdbcTemplate.query(QueryList.CALCULATE_SCORE,parameters,new RowMapper<MappingUI>() {

            @Override
            public MappingUI mapRow(ResultSet rs, int rowNum) throws SQLException {
                MappingUI mapping=  new MappingUI();
                mapping.setCompetitor(rs.getInt("ID"));
                mapping.setTotalRepufactScore(rs.getFloat("AVG_SCORE"));
                return mapping;
            }
        });

below is my query
SELECT AVG(SCORE.SCORE) AS AVG_SCORE,ANALYSIS.ID AS ID FROM  SCORE SCORE,QC_ANALYSIS ANALYSIS WHERE SCORE.TAG_ID = ANALYSIS.ID AND                                     ANALYSIS.ORGANIZATION_ID IN (:organizationIds) AND DATE(ANALYSIS.DATES) BETWEEN DATE(:fromDate) AND DATE(:toDate)                                     GROUP BY ANALYSIS.ORGANIZATION_ID


text:
Q: DrawerLayout widget background change I am using DrawerLayout widget along with google maps.
when I scroll my list view my backgroud is being changed. and when I click on list view it is changing back to my default background
My intial listview

on drag/scroll

On Select

xml Code:
<ListView android:id="@+id/left_drawer1"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@drawable/divider"
    android:dividerHeight="1dp"
    android:background="#333"
    android:paddingLeft="15sp"
    android:paddingRight="15sp"
    />

java code -
@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
     actionBarDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    actionBarDrawerToggle.onConfigurationChanged(newConfig);
}

A: for your XML ListView set android:cacheColorHint="@color/transparent"
Java code listView.setCacheColorHint(Color.TRANSPARENT);


text:
Q: Neo4j Cypher query: Parenthesis not considered in WHERE clause? I am trying to run a query like:
MATCH (n:Type1)-[:relation1]->(:Type1)<-[:relation2]-(:Type2) WHERE
((n.prop1="A" and n.prop2 in [42, 34]) OR
 (n.prop1="B" and n.prop2 in [67])     OR
 (n.prop1="C" and n.prop2 in [51, 43]) OR
 (n.prop1="D" and n.prop2 in [56, 42]))
RETURN DISTINCT id(n) as node_id, n.prop3 as node_prop3, n.prop1 as prop1, n.prop2 as prop2;

This is giving mixed results ie prop1="D" matched with prop2=51 which is clearly not in the intended condition. It is as if the parentheses have no say in the formation of conditional.
The results are the same when I run the query w/o parentheses in the WHERE clause.
Although, If I query something like:
MATCH (n:Type1)-[:relation1]->(:Type1)<-[:relation2]-(:Type2) WHERE
((n.prop1="A" and n.prop2=42) OR
 (n.prop1="A" and n.prop2=34) OR
 (n.prop1="B" and n.prop2=67) OR
 (n.prop1="C" and n.prop2=51) OR
 (n.prop1="C" and n.prop2=43) OR
 (n.prop1="D" and n.prop2=56) OR
 (n.prop1="D" and n.prop2=42))
RETURN DISTINCT id(n) as node_id, n.prop3 as node_prop3, n.prop1 as prop1, n.prop2 as prop2;

Is there something I'm missing when replacing the separate conditions in example 2 with the IN in example 1 to avoid repeated string comparisons for prop1?

A: I believe that IN works as you expect.
Set up sample data.
(:Type1 {prop1:"A", prop2:34}),
(:Type1 {prop1:"B", prop2:67}),
(:Type1 {prop1:"C", prop2:51}),
(:Type1 {prop1:"C", prop2:43}),
(:Type1 {prop1:"D", prop2:56}),
(:Type1 {prop1:"D", prop2:42}),
(:Type1 {prop1:"D", prop2:51}),
(:Type1 {prop1:"B", prop2:42});

MATCH (t:Type1)
MERGE (t)-[:relation1]->(:Type1)<-[:relation2]-(:Type2);

Now run your query.
MATCH (n:Type1)-[:relation1]->(:Type1)<-[:relation2]-(:Type2) WHERE
((n.prop1="A" and n.prop2 in [42, 34]) OR
 (n.prop1="B" and n.prop2 in [67])     OR
 (n.prop1="C" and n.prop2 in [51, 43]) OR
 (n.prop1="D" and n.prop2 in [56, 42]))
RETURN DISTINCT id(n) as node_id, n.prop3 as node_prop3, n.prop1 as prop1, n.prop2 as prop2;

The statement returns seven records, and the results do not include the node with prop1 = D and prop2 = 51.
See this answer for information on the precedence of Boolean operators if you leave out parenthesis.


text:
Q: Setting caption for Virtual Tree List nodes I can't understand the process described in documentation. It says to use event:
procedure TForm1.VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
                Column: Integer; TextType: TVSTTextType; var CellText: WideString);
var
    Data: PTreeData;
begin
   Data:=VST.GetNodeData(Node);
   CellText := Data^.FCaption;
end;

How do I do that? I can't redeclare it just like this. When I double click on Tree List OnGetTextEvent it throws some exception at me "Property and Method are incompatible"

A: You don't mention the Delphi and VirtualTreeview version but I guess thats because of the CellText: WideString parameter - it should be of string type now after the UnicodeString became the default string type in Delphi. IOW change it to
procedure TForm1.VSTGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
          Column: Integer; TextType: TVSTTextType; var CellText: string);

A: There was something wrong with my project. I'm not sure what, cos I've recreated it. Now the GetText event works properly. My code above works.


text:
Q: What does 'Class.forName("org.sqlite.JDBC");' do? I am trying to create a simple app with a SQLite database. I chose to use the SQLiteJDBC driver.
The code below is taken from the above website.
My question is about the line after public static void main...
It reads: Class.forName("org.sqlite.JDBC");
My question is, what does this line mean? And what does it do? It doesn't seem to be connected to the rest of the code. Class.forName() should return a class, but the line seems to stand alone inside the body. Whatever it returns isn't used by another part of the code, that I can see.
Please help clarify this. Thanks in advance.
public class Test {
 public static void main(String[] args) throws Exception {
    Class.forName("org.sqlite.JDBC");
    Connection conn =
      DriverManager.getConnection("jdbc:sqlite:test.db");
    Statement stat = conn.createStatement();
    stat.executeUpdate("drop table if exists people;");
    stat.executeUpdate("create table people (name, occupation);");
    PreparedStatement prep = conn.prepareStatement(
      "insert into people values (?, ?);");

prep.setString(1, "Gandhi");
prep.setString(2, "politics");
prep.addBatch();
prep.setString(1, "Turing");
prep.setString(2, "computers");
prep.addBatch();

conn.setAutoCommit(false);
prep.executeBatch();
conn.setAutoCommit(true);

ResultSet rs = stat.executeQuery("select * from people;");
while (rs.next()) {
  System.out.println("name = " + rs.getString("name"));
  System.out.println("job = " + rs.getString("occupation"));
}
rs.close();
conn.close();
}
  }

A: It loads a class dynamically. What does Class.forname method do? is a good article about it and it also explains why database drivers needs it:

Let's see why you need Class.forName() to load a driver into memory. All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static an initializer only.
The MySQL JDBC Driver has a static initializer looks like this:

static {
    try {
        java.sql.DriverManager.registerDriver(new Driver());
    } catch (SQLException E) {
        throw new RuntimeException("Can't register driver!");
    }
}

JVM executes the static block and the Driver registers itself with the DriverManager.
You need a database connection to manipulate the database. In order to create the connection to the database, the DriverManager class has to know which database driver you want to use. It does that by iterating over the array (internally a Vector) of drivers that have registered with it and calls the acceptsURL(url) method on each driver in the array, effectively asking the driver to tell it whether or not it can handle the JDBC URL.

A: The Class.forName statement is making sure that the class that implements the JDBC driver for sqlite3 is loaded and registered with the JDBC factory mechanism.
When you call DriverManager.getConnection(), it looks for classes that are registered and claim to be able to handle the connection string.  If no such class is found, it can't create the connection.


text:
Q: How to unit test build script? I am trying to unit test my build script.
I think following testing scenarios are normal scenarios

*

*Verify the build version number correctness

*Verify version numbers of msi and verify whether they are latest?

*Verify whether all the assemblies were strong name signed

*verify whether compilation failures were communicated to responsible person?

What are all the other test cases may be commonly applicable for build script?

A: For the "what are other test cases" - You probably want to test that it handles failures correctly - if a disk fails, if the compile fails, there's some other I/O error. Whatever your error procedures are, you should test for those.
Does your build script run your automated tests also? You might want to check that it actually runs those (getting recursive here), and reports failures from those correctly.
Testing the version numbers seems straightforward. I assume you are passing the version numbers to the script (or have some other easily identifiable way of figuring out what they should be). Check that your build artifacts have those numbers in the filename/readme/whereever.


text:
Q: GC.COllect() doesnt seem to work in debug mode I am running the code below and the result is totally different when it runs in Release mode. While in Debug mode, it never collects the object of class A and in Reaelse mode it immediately collects the object of class A.
Can someone explain why.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2 {
    class Program
    {
        static void Main(string[] args)
        {
            A obj = new A();

            B bobj = obj.objB;

            GC.Collect();
            GC.WaitForPendingFinalizers();

            while (bobj.isLive)
            {
                Console.WriteLine("Is Alive!!");
            }

            Console.WriteLine("Is Dead!!");

            Console.ReadLine();
        }
    }

    class A:IDisposable

    {
        public B objB = new B();

        public A()
        { }

        ~A()
        {
            objB.Dispose();
        }

        #region IDisposable Members

        public void  Dispose()
        {
            GC.SuppressFinalize(this);
        }

        #endregion

    }
    class B:IDisposable
    {
        public bool isLive = true;

        #region IDisposable Members

        public void  Dispose()
        {
            this.isLive = false;
            GC.SuppressFinalize(this);
        }

        #endregion
    } }

A: In Debug mode, the compiler does not optimize the local variables. Therefore, the reference to A still exists. In Release mode, the compiler optimized the usage so that the reference is thrown away and the object can be collected.

A: The garbage collector handles variable usage differently in debug mode and release mode.
In release mode the usage of a variable is only where it's actually used. After the last use of the varaible, the object is up for garbage collection.
In debug mode the usage of a varaible is expanded to it's scope. The reason for this is so that the watch window in the debugger can show the value of a variables throughout it's scope.

A: I just found this behavior in my tests. Inserting
obj = null;

right before GC.Collect() should help. I think that is kind of "simulated" optimization.


text:
Q: SQL PnL Inventory Query I have a table containing a list of trades:
Security ;   Quantity ; Price ;  Consid
 1. IBM  ;    +1,000 ;   20  ;  -20k
 2. IBM  ;    +2,000 ;   22  ;  -44k
 3. IBM  ;    -1,000 ;   30  ;  +30k
 4. IBM  ;    -2,000 ;   20  ;  +40k
 5. IBM  ;    -2,000 ;   20  ;  -20k

So the PnL is basically the sum of the Consid column so before Trade#5 was added the PnL would be +6k.
After Trade #5 was added this shows the PnL as -14k which isnt really that reflective of where we stand.
What I would like is some way of filtering out the not closed trades? So Trade#5 will only be allowed into the sum when we have added a purchase of 2k IBM shares to the table.
My intial attempt at this was:
set @Ret = @Ret + isnull((SELECT SUM(GC) AS GS
FROM  (SELECT SUM(GrossConsid) * - 1 AS GC
                     FROM   Trades AS CT
                     WHERE  (SpecialCond = 'Prop') AND (SettType <> 'Futures') AND (TrdDt <= @Date) AND (TrdDt >=@StartDate) AND (Name = 'my_Comp')
                     GROUP BY ABS(Quantity)
                     HAVING (SUM(Quantity) = 0)) AS dt),0)

but I have no figured out that there is an edge condition where by if I have a trades with a Quantity of +5,+5,-5 it doesnt get counted because the (SUM(Quantity) = 0))  evaluates to false.
Any ideas on how I can rectify this?
Thanks Chris

A: Rather than using SQL to match up your inventory, can you have your app set a flag in an additional "Closed" column?  Then you could do this:
SELECT Security, SUM(Consid)
FROM mytable
WHERE Closed = 1
GROUP BY Security

A: Cant say about your logic, just fixing what you say is wrong:
HAVING (case when SUM(Quantity) = 0 then 1 else 0 end)

A: Runnable Example
DECLARE @tbl AS TABLE (Seq int, Security varchar(3), Quantity int, Price int, Consid int) ;
INSERT INTO @tbl VALUES
(1, 'IBM', 1000, 20, -20000)
,(2, 'IBM', 2000, 22, -44000)
,(3, 'IBM', -1000, 30, 30000)
,(4, 'IBM', -2000, 20, 40000)
,(5, 'IBM', -2000, 20, -20000);

WITH RunningInventory AS (
SELECT l.Seq, SUM(r.Quantity) AS Inv
FROM @tbl AS l
LEFT JOIN @tbl r
ON r.Seq <= l.Seq
GROUP BY l.Seq
)
SELECT *
FROM @tbl AS trx
INNER JOIN RunningInventory
    ON trx.Seq = RunningInventory.Seq
WHERE RunningInventory.Inv >= 0 ;


text:
Q: Sample in R throws too few positive probs A problem with the sample function. With the attached data set I tried
after loading (column 9 is how often something occurs, and col 11 the associated var, the weight are in col eight
which(kfg[,9]==1)->aj
sample(kfg[aj,11],prob=kfg[aj,8])

Error in sample.int(length(x), size, replace, prob) :
  too few positive probabilities

This is confusing because
mean(kfg[aj,8])
#[1] 0.0009090909

Not all of the probabilities are the same value, could somebody maybe tell why this happens?
The dataset can be found here:
https://www.dropbox.com/s/gyimxbz5f3v0uq3/kfg.RData?dl=0

A: You need one of replace=TRUE or size options since there are a bunch of 0 probabilities.  Otherwise, sample is trying to return the same number of elements as the length of the input, but can't do so because of a lack of positive probabilities.


text:
Q: How to ensure security in Mobile Applications I am developing a front end mobile app for Android and iOS that interacts with my webserver that runs ASP.NET.  Right now, I am doing the following security measures:
1)Basic authentication
2)SSL using REST API
3)Store only a token on the device that is used to confirm with the server for future accesses
Anything else I missed??

A: I have some suggestions,

*

*Use secure encryption/decryption algorithms like AES-256 with password based cryptographic key. Also code obfuscation & jumble algorithms can be applied for secure key generation to avoid reverse engineering attacks upto a level.

*Disable caching of webservice request/ delete cache for each time. In iOS prevent caching of snapshots.

*If you want to store Tokens on device you need to encrypt the token and don't depend authentication like sensitive web services relying on this token.

*Define Session expire time according to your business needs and criticality.

*Do not install or load application in Jail broken/Rooted devices.


text:
Q: Can't set up WebStorm Build WS-163.9166.30
WebStorm doesn't want to remember my JetBrains account license on 16.10. I unzipped it to /opt. It worked fine from /opt on 16.04
java.lang.SecurityException: Could not lock User prefs. Lock file access denied.
    at java.util.prefs.FileSystemPreferences.checkLockFile0ErrorCode(FileSystemPreferences.java:937)
    at java.util.prefs.FileSystemPreferences.lockFile(FileSystemPreferences.java:925)
    at java.util.prefs.FileSystemPreferences.sync(FileSystemPreferences.java:729)
    at java.util.prefs.FileSystemPreferences.flush(FileSystemPreferences.java:824)
    at java.util.prefs.FileSystemPreferences.syncWorld(FileSystemPreferences.java:464)
    at java.util.prefs.FileSystemPreferences.access$1200(FileSystemPreferences.java:50)
    at java.util.prefs.FileSystemPreferences$3.run(FileSystemPreferences.java:432)
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505)

I tried ~ folder and other JetBrains products as well. Same story.

Also, JetBrains Toolbox is crashing after 5 seconds after launch

A: After opening a ticket with JetBrain's support, this is what helped me:

*

*Open (or create) webstorm64.vmoptions file. If you can open
WebStorm, you can go to Help -> Edit Custom VM Options.... If you
can't, create a file named webstorm64.vmoptions in the config
directory (usually ~/.WebStorm<version>) and open it in a text
editor.

*Find (or create) a folder that you have full permissions to (e.g. mkdir ~/.ws-prefs)

*Add the following line to the file:
-Djava.util.prefs.userRoot=absolute_path_to_prefs_folder

Save and restart WebStorm.
The issue happened again after upgrading WebStorm and a few reboots. This time, I've noticed that although it crushed during initialization after I've logged in to my JetBrains account, I was able to run WebStorm with a trial license. So I removed the entire configuration folder (rm -rf ~/.WebStorm<version>) and everything works again (for now...)

A: I had the same issue with PyCharm. The following solved the problem for me:
sudo chmod -R 775 ~/.java/
sudo chown -R username:root ~/.java/

Just doing the first command wasn't enough.


text:
Q: Concatenate - sign with numeric in Crystal Report I want to Concatenate - sign with numeric I tried but not working. I just want to add - sign with the calculation result value. Code is mentioned below.
if ({Sp_ProductLedger;1.QtyOut}) >0 then
"-" &({#RTotal0} + {Sp_ProductLedger;1.Opbal});

A: If you want a numeric result that is negative, multiply by -1 instead of adding a minus sign (which would result in a string rather than a number).


text:
Q: How does flask migrate track which revision ID is current? I've been using Flask-Migrate incorrectly. Between two environments I have independently created the migrations folder, and added the migrations folder to the .gitignore file.
This has recently caused problems because I would like to interact with Alembic migrations directly, and track those changes in github.
This means I have forked my production flask app, and now track the migrations folder removing its entry in my .gitignore file. I pulled this branch to my local and destroyed my local db. I ran the tracked migrations and it seems to work.
I'm wondering between two environments, how does flask migrate track what the current revision id is? Suppose I create and run two migrations on my local, and push the migrations folder. How will Flask migrate track these two revisions, and run these on Production, when I run db upgrade on production?

A: Alembic (the engine behind Flask-Migrate) will insert a little table in your database called alembic_version. It writes the current revision of the database in this table. Here is a dump of this table in one of my databases:
mydb=# select * from alembic_version;
 version_num
--------------
 36e0d1f0d589
(1 row)

When you run an upgrade it will know from where to start upgrading by reading the current revision from this table.
Good question!


text:
Q: Attempt to read property "id" on null Auth::user() multiple authentication system I implemented the multiple authentication system using the laravel Auth package.
But in route example.com/admin/login when I use this code:
dd(Auth::user()->id);

I get the following error:

Attempt to read property "id" on null

Note: I do not have this problem in the default route of the Auth package, ie example.com/login.


text:
Q: Send Mail with Large Attachment using c# I am trying to send email using Smtp using "smtp.gmail.com". Our project use .net 3.5 Framweork and c# to keep XP Compatibility. However, I always failed when the attachment is over 5MB. I read that google smtp allow to send attachment as large as 25MB. However, when I try to do it, it always throw error:
System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException: The write operation failed, see inner exception. ---> System.Threading.ThreadAbortException: Thread was being aborted.
   at System.Net.UnsafeNclNativeMethods.OSSOCK.send(IntPtr socketHandle, Byte* pinnedBuffer, Int32 len, SocketFlags socketFlags)
   at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, SocketError& errorCode)
   at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
   at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.Security._SslStream.StartWriting(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security._SslStream.ProcessWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
   --- End of inner exception stack trace ---
   at System.Net.Security._SslStream.ProcessWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
   at System.Net.DelegatedStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.DelegatedStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.DelegatedStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.DelegatedStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.DelegatedStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.DelegatedStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.Base64Stream.FlushInternal()
   at System.Net.Base64Stream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.Net.Mime.MimePart.Send(BaseWriter writer)
   at System.Net.Mime.MimeMultiPart.Send(BaseWriter writer)
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)

This is the method I use to send mail:
public void Send( SMTPServerInfo serverInfo, string from, string to, string subject, string body, IList<Attachment> attachments )
{
  SmtpClient client = new SmtpClient();
  client.EnableSsl = serverInfo.EnableSSL;
  MailMessage message = new MailMessage( from, to, subject, body );
  if( IsHTML )
    message.IsBodyHtml = true;
  client.Host = serverInfo.ServerName;
  if( !Text.IsEmpty( serverInfo.UserName ) )
    client.Credentials = new NetworkCredential( serverInfo.UserName, serverInfo.Password );
  if( serverInfo.Port.HasValue )
    client.Port = serverInfo.Port.Value;
  if( attachments != null )
    foreach( Attachment attachment in attachments )
      message.Attachments.Add( attachment );

  client.Send( message );
  message.Dispose();
}

I am not sure why is this happening.

A: You have to Instantiate the mail like this:
System.Net.Mail.Attachment attachment1;
 attachment1 = new System.Net.Mail.Attachment(attachmentFilePath_Here);
 message.Attachments.Add(attachment1);

A: This error thrown when the SMTP is force to stop when sending large attachment. The problem is not within the SMTP neither the Timeout. See:
 System.Threading.ThreadAbortException: Thread was being aborted

That is the reason the error shown. The thread that sending the email is aborted. See we might need to check more on the Thread problem.


text:
Q: Jquery alternate sweet alert I want to run the program so that if the result returned is str4 or str2, the sweet alert will throw up an "error" instead of a "success" icon but I have no idea how.
Here is the code:
$( document ).ready(function() {

   $( "#w2" ).click(function() {
    swal({
        title: result(),
        icon: "success",
        button: "OK",
    });
   });

   function result() {

    var str = $("#w1").val().toLowerCase();
    var str2 = "This is not a cafe";
    var str3 = "This cafe does have a plug source";
    var str4 = "This cafe does not have a plug source";

    if (str== "cafe express" || str=="cafeexpress") {
        return str3;
    } else if ( str=="jungle cafe" || str=="junglecafe") {
        return str4;
    } else {
        return str2;
    }

   }

});

A: $( document ).ready(function() {

   $( "#w2" ).click(function() {
    var res = result();
    swal({
        title: res[0],
        icon: res[1],
        button: "OK",
    });
   });

   function result() {

    var str = $("#w1").val().toLowerCase();
    var str2 = "This is not a cafe";
    var str3 = "This cafe does have a plug source";
    var str4 = "This cafe does not have a plug source";

    if (str== "cafe express" || str=="cafeexpress") {
        return [str3, "success"];
    } else if ( str=="jungle cafe" || str=="junglecafe") {
        return [str4, "error"];
    } else {
        return [str2, "error"];
    }

   }

});


text:
Q: Testing if string is sha1 in PHP I'm planning on storing the passwords as a sha1, so I need a way to validate that it is a sha1 at another point in my website. I was planning on using preg_match, but I do not know how to make regex patterns. Could someone help me out with one?
Thanks
Edit: I am not trying to see if two hashes match.

A: ctype_xdigit is much faster. I typically use hashes for lookups and find it very useful.

A: Actually, you can use preg_match() to make sure it's a 40 characters hexadecimal string as such:
function is_sha1($str) {
    return (bool) preg_match('/^[0-9a-f]{40}$/i', $str);
}

To explain the pattern:

/        Opening Delimiter
^        Start Of String Anchor
[0-9a-f] Any of the following characters: 0123456789abcdef
{40}     Repeated 40 times
$        End Of String Anchor
/        Closing Delimiter
i        Modifier: Case-Insensitive Search

If you are trying to make sure that the sha1() hash matches the password the user provider, you simply rehash like this:
if($db_hash == sha1($user_provided_pass))
   echo "Password is correct!";

A: When comparing two SHA1 hashes, and you know that the first one is one (because it comes out of the database), then just assume that the second is a SHA1 value as well. You are only interested if two hashes match or not. If one of the compared values is not a possible SHA1 value, then it's particulary not the same as the one in the database. And that's all you need to know.


text:
Q: JClouds-Chef: IllegalAccessError on TokenType2? I am using the JClouds-Chef API to bootstrap a Linux VM (myapp01.me.example.com) with Chef Client, and to then run the client and configure the VM with its app stack via a typicalapp role:
package com.me.myorg.chef;

import org.jclouds.Constants
import org.jclouds.ContextBuilder
import org.jclouds.chef.ChefContext
import org.jclouds.chef.ChefService
import org.jclouds.chef.config.ChefProperties
import org.jclouds.chef.domain.BootstrapConfig
import org.jclouds.chef.util.RunListBuilder
import org.jclouds.compute.domain.ExecResponse
import org.jclouds.compute.domain.OsFamily
import org.jclouds.domain.LoginCredentials
import org.jclouds.scriptbuilder.domain.Statement
import org.jclouds.ssh.SshClient
import org.jclouds.sshj.config.SshjSshClientModule

import com.google.common.base.Charsets
import com.google.common.collect.ImmutableSet
import com.google.common.io.Files
import com.google.common.net.HostAndPort
import com.google.inject.Key
import com.google.inject.TypeLiteral

public class ChefProvisioner {
    public static void main(String[] args) {
        ChefProvisioner.provision()
    }

    public static provision() {
        String vmIp = "myapp01.me.example.com";     // A Linux VM living in our local vCenter
        String vmSshUsername = "admin";
        String vmSshPassword = "12345";

        String endpoint = "https://mychefserver";
        String client = "myuser";
        String validator = "chef-validator";
        String clientCredential = Files.toString(new File("C:\\Users\\myuser\\sandbox\\chef\\myuser.pem"), Charsets.UTF_8);
        String validatorCredential = Files.toString(new File("C:\\Users\\myuser\\sandbox\\chef\\chef-validator.pem"), Charsets.UTF_8);

        Properties props = new Properties();
        props.put(ChefProperties.CHEF_VALIDATOR_NAME, validator);
        props.put(ChefProperties.CHEF_VALIDATOR_CREDENTIAL, validatorCredential);
        props.put(Constants.PROPERTY_RELAX_HOSTNAME, "true");
        props.put(Constants.PROPERTY_TRUST_ALL_CERTS, "true");

        ChefContext ctx = ContextBuilder.newBuilder("chef")
            .endpoint(endpoint)
            .credentials(client, clientCredential)
            .overrides(props)
            .modules(ImmutableSet.of(new SshjSshClientModule())) //
            .buildView(ChefContext.class);
        ChefService chef = ctx.getChefService();

        List<String> runlist = new RunListBuilder().addRole("typicalapp").build();
        BootstrapConfig bootstrapConfig = BootstrapConfig.builder().runlist(runlist).build();

        chef.updateBootstrapConfigForGroup("jclouds-chef", bootstrapConfig);
        Statement bootstrap = chef.createBootstrapScriptForGroup("jclouds-chef");

        SshClient.Factory sshFactory = ctx.unwrap().utils()
            .injector().getInstance(Key.get(new TypeLiteral<SshClient.Factory>() {}));
        SshClient ssh = sshFactory.create(HostAndPort.fromParts(vmIp, 22),
        LoginCredentials.builder().user(vmSshUsername).password(vmSshPassword).build());

        ssh.connect();
        try {
            String rawScript = bootstrap.render(OsFamily.UNIX);
            ExecResponse result = ssh.exec(rawScript);
        } finally {
            ssh.disconnect();
        }
    }
}

When I run this I get:
Exception in thread "main" java.util.ServiceConfigurationError: org.jclouds.apis.ApiMetadata: Provider org.jclouds.openstack.swift.SwiftApiMetadata could not be instantiated: java.lang.IllegalAccessError: tried to access class com.google.common.reflect.TypeResolver from class org.jclouds.util.TypeToken2
    at java.util.ServiceLoader.fail(ServiceLoader.java:224)
    at java.util.ServiceLoader.access$100(ServiceLoader.java:181)
    at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:377)
    at java.util.ServiceLoader$1.next(ServiceLoader.java:445)
    at com.google.common.collect.ImmutableCollection$Builder.addAll(ImmutableCollection.java:323)
    at com.google.common.collect.ImmutableSet$Builder.addAll(ImmutableSet.java:633)
    at org.jclouds.apis.Apis.all(Apis.java:72)
    at org.jclouds.apis.Apis.withId(Apis.java:89)
    at org.jclouds.ContextBuilder.newBuilder(ContextBuilder.java:168)
    at org.jclouds.ContextBuilder$newBuilder.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at com.me.myorg.chef.ChefProvisioner.provision(ChefProvisioner.groovy:51)
    at com.me.myorg.chef.ChefProvisioner$provision.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
    at com.me.myorg.chef.ChefProvisioner.main(ChefProvisioner.groovy:27)
Caused by: java.lang.IllegalAccessError: tried to access class com.google.common.reflect.TypeResolver from class org.jclouds.util.TypeToken2
    at org.jclouds.util.TypeToken2.where(TypeToken2.java:47)
    at org.jclouds.rest.internal.BaseRestApiMetadata.contextToken(BaseRestApiMetadata.java:60)
    at org.jclouds.rest.internal.BaseRestApiMetadata$Builder.<init>(BaseRestApiMetadata.java:74)
    at org.jclouds.openstack.swift.SwiftApiMetadata$Builder.<init>(SwiftApiMetadata.java:85)
    at org.jclouds.openstack.swift.SwiftApiMetadata$Builder.<init>(SwiftApiMetadata.java:81)
    at org.jclouds.openstack.swift.SwiftApiMetadata$ConcreteBuilder.<init>(SwiftApiMetadata.java:108)
    at org.jclouds.openstack.swift.SwiftApiMetadata$ConcreteBuilder.<init>(SwiftApiMetadata.java:108)
    at org.jclouds.openstack.swift.SwiftApiMetadata.<init>(SwiftApiMetadata.java:60)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at java.lang.Class.newInstance(Class.java:374)
    at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:373)
    ... 16 more

Any ideas as to what is going on here?

A: You will need the following, in order to be able to bootstrap your VM:

*

*The ip address of the VM. It must be reachable, have the port 22 open (as the bootstrap will be done via SSH) and have access to the Internet so it can install Ruby and Chef.

*A client in the Chef Server and its corresponding private key. That client is used by jclouds to perform the operations against the Chef Server REST API.

*The validator certificate. That certificate will be uploaded to the node so it can self-register in the Chef Server.

In this case, as the jclouds ComputeService is not being used, you'll have to manually instantiate an SSH client to connect to the virtual machine, but it should be pretty straightforward.
In the example you mention, the Git repo is cloned when using ChefSolo, but since you have a Chef Server the only thing you need to do is to configure the connection and the desired run list and attributes.
A minimal program to do that would require the following dependencies:
<!-- Required dependencies -->
<dependency>
    <groupId>org.apache.jclouds.driver</groupId>
    <artifactId>jclouds-sshj</artifactId>
    <version>${jclouds.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.jclouds.api</groupId>
    <artifactId>chef</artifactId>
    <version>${jclouds.version}</version>
</dependency>

And it could be something like the following:
Update: I've changed the configuration to match the provided knife.rb configuration, and also added a couple properties to avoid SSL errors, as your Chef endpoint is https.
// Configuration
String vmIp = "vm-ip";
String vmSshUsername = "root";
String vmSshPassword = "foo";

String endpoint = "https://mychefserver.example.com";
String client = "myuser";
String validator = "chef-validator";
String clientCredential = Files.toString(new File("/home/myuser/.chef/myuser.pem"), Charsets.UTF_8);
String validatorCredential = Files.toString(new File("/home/myuser/.chef/chef-validator.pem"), Charsets.UTF_8);

Properties props = new Properties();
props.put(ChefProperties.CHEF_VALIDATOR_NAME, validator);
props.put(ChefProperties.CHEF_VALIDATOR_CREDENTIAL, validatorCredential);
props.put(Constants.PROPERTY_RELAX_HOSTNAME, "true");
props.put(Constants.PROPERTY_TRUST_ALL_CERTS, "true");

/* *** First, create the context to connect to the Chef Server *** */

// Create the context and configure the SSH driver to use. sshj in this example
ChefContext ctx = ContextBuilder.newBuilder("chef")
    .endpoint(endpoint)
    .credentials(client, clientCredential)
    .overrides(props)
    .modules(ImmutableSet.of(new SshjSshClientModule())) //
    .buildView(ChefContext.class);
CherService chef = ctx.getChefService();

/* *** Second, generate the bootstrap script *** */

// Generate the bootsrap configuration
List<String> runlist = new RunListBuilder().addRole("typicalapp").build();
BootstrapConfig bootstrapConfig = BootstrapConfig.builder().runlist(runlist).build();

// Generate the bootstrap script to be executed in the VM (this will persist
// the configuration in a data bag under the key 'jclouds-chef' so it can be reused
// and then build the bootstrap script with the information in the configuration data bag)
chef.updateBootstrapConfigForGroup("jclouds-chef", bootstrapConfig);
Statement bootstrap = chef.createBootstrapScriptForGroup("jclouds-chef");

/* *** Finally create an SSH connection manually and run the script on the VM *** */

SshClient.Factory sshFactory = ctx.unwrap().utils()
    .injector().getInstance(Key.get(new TypeLiteral<SshClient.Factory>() {}));
SshClient ssh = sshFactory.create(HostAndPort.fromParts(vmIp, 22),
    LoginCredentials.builder().user(vmSshUsername).password(vmSshPassword).build());

ssh.connect();
try {
    String rawScript = bootstrap.render(OsFamily.UNIX);
    ExecResponse result = ssh.exec(rawScript);
} finally {
    ssh.disconnect();
}


text:
Q: How to display custom modal UIView? I am trying to display a custom UIView on top of all other views making it modal that works correctly in both portrait and landscape. The way i am currently doing this is by creating a transparent black view which basically dims the entire screen and then add my custom view on top of that. Everything is working great except for the fact that it doesn't orient itself property when in landscape. I think this is due to the way i am adding my view:
UIWindow* mainWindow = (((MyAppDelegate*)[UIApplication sharedApplication].delegate).window);
[mainWindow addSubview:self];

It seems that mainWindow is ALWAYS in portrait regardless of what the actual device orientation is so even when i am in landscape my custom view displays upside down as if it was in portrait mode. My main viewcontroller is a navcontroller which adds several custom views on top of it so i really dont want to pass a reference to it all the way down through my views just so i can use it above.
My question finally is how do i correctly add my custom view to the main windows so that it is correctly orientated in landscape as well as portrait and still displays over the entire screen.
Thx

A: Create and make-key a new UIWindow with a higher zorder, and add a view controller to it.  The view controller has the built in logic to handle view rotation.


text:
Q: Why is PropertyChangedEventHandler null? The mainpage:
MainPage.xaml
<Canvas x:Name="LayoutRoot" Background="White">
</Canvas>

MainPage.xaml.cs
List<Usol> list = new List<Usol>();
for (int i = 0; i < 10; i++)
{
    var element = new Usol();
    list.Add(element);
    Canvas.SetTop(element, i * 25);
    LayoutRoot.Children.Add(list[i]);
    }
foreach (var item in list)
{
    item.context.name = "Varken";
}

A usercontrol
Usol.xaml
<Grid x:Name="LayoutRoot" Background="White">
    <TextBlock Text="{Binding Name}" />
</Grid>

Usol.xaml.cs
 public Context context;
 public Usol()
 {
     InitializeComponent();
     context = new Context();
     this.DataContext = context;
 }

A class
Context.cs
public class Context : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #region Fields
    /// <summary>
    /// Field Declaration for the <see cref="Name"/>
    /// </summary>
    private string name;
    #endregion
    #region Properties
    /// <summary>
    /// Gets or Sets the Name
    /// </summary>
    public string Name
    {
        get { return name; }
        set
        {
            if (this.name != value)
            {
                this.name = value;
                OnPropertyChanged("Name");
            }
        }
    }
    #endregion
}

Situation
I have created this small test application to copy a problem I have in a bigger application. It works about the same way (not exactly, but close enough).
It adds several custom made usercontrols and each get a own instance of a datacontext class.
However, none of the properties are willing to update themselfs due to a empty PropertyChangedEventHandler.
Question
Why is public event PropertyChangedEventHandler PropertyChanged; always null?

A: Context.cs needs to implement INotifyPropertyChanged interface. Are you doing that?
Edit: Post your update.
I have generally seen this kind of problem when programmers create "two" instances of Model/ViewModel. While you attach one instance with View, it's always the other one that gets update (which ofcourse will have a null PropertyChanged subscribers). Thus, you must make sure that your view is using the same instance as being updated at other parts.
Hope my point is clear.

A: Your code is wrong,
OnPropertyChanged("Name"); <-- should update "name" not "Name"

You are firing event saying that "Name" is changed, but name of property is "name", C# and binding are case sensitive.
Change it to,
#region Fields
/// <summary>
/// Field Declaration for the <see cref="name"/>
/// </summary>
private string _Name;
#endregion
#region Properties
/// <summary>
/// Gets or Sets the name
/// </summary>
public string Name
{
    get { return _Name; }
    set
    {
        if (this._Name != value)
        {
            this._Name = value;
            OnPropertyChanged("Name");
        }
    }
}
#endregion

From  C# 6 on wards, please use nameof() keyword...
#region Fields
/// <summary>
/// Field Declaration for the <see cref="name"/>
/// </summary>
private string _Name;
#endregion
#region Properties
/// <summary>
/// Gets or Sets the name
/// </summary>
public string Name
{
    get { return _Name; }
    set
    {
        if (this._Name != value)
        {
            this._Name = value;
            OnPropertyChanged(nameof(Name));
        }
    }
}
#endregion


text:
Q: How to get all sums values with out each element using BigQuery? I have a table in BigQuery. I want to count all sums of values in column removing each element alternately by id. As output I want to see removed id and sum of other values.

WITH t as (SELECT  1 AS id, "LY" as code,  34 AS value
UNION ALL
SELECT  2, "LY",  45
UNION ALL
SELECT  3, "LY", 23
UNION ALL
SELECT  4, "LY", 5
UNION ALL
SELECT  5, "LY", 54
UNION ALL
SELECT  6, "LY", 78)
SELECT lv id, SUM(lag) sum_wo_id
FROM
(SELECT *, FIRST_VALUE(id) OVER (ORDER BY id DESC) lv, LAG(value) OVER (Order by id) lag from t)
     GROUP BY lv

In example above I can see sum of values with out id = 6. How can I modify this query to get sums without another ids like 12346, 12356, 12456, 13456, 23456 and see which one removed?

A: Below is for BigQuery Standard SQL
Assuming ids are distinct - you can simply use below
#standardSQL
SELECT id AS removed_id,
  SUM(value) OVER() - value AS sum_wo_id
FROM t

if applied to sample data from your question - output is
Row removed_id  sum_wo_id
1   1           205
2   2           194
3   3           216
4   4           234
5   5           185
6   6           161

In case if id is not unique - you can first group by id as in below example
#standardSQL
SELECT id AS removed_id,
  SUM(value) OVER() - value AS sum_wo_id
FROM (
  SELECT id, SUM(value) AS value
  FROM t
  GROUP BY id
)


text:
Q: Ray Cylinder intersection I am developing a Ray Tracing system and it is working, now I am trying to support more primitives (for now it supports: spheres, boxes, planes and triangles), and I am having problems with cylinders.
I know to intersect ray with cylinder I need to do two check, the first is with the body (with that I get an Infinite Cylinder), for this I assume circle in two dimensions, in the plane xz (x² + z² = r, where r is the radius) then I need check that Y coordinate is between 0 and height and finally I need to check if the intersection is in the caps (x²+z²<=r, where r is the radius).
My code is the follow (see the comments for more explanations)
Intersection Cylinder::hit(Ray ray)
{
    ray.setOrigin(vec3(getInverseTransform() * vec4(ray.getOrigin(),1)));
    ray.setDirection(glm::normalize(vec3(getInverseTransform() * vec4(ray.getDirection(),0))));

    // R(t) = o + td
    // x² + z² = r²
    // (ox+tdx)² + (oz+tdz)² = r²
    // (ox)² + 2oxtdx + (tdx)² + (oz)² + 2oztdz + (tdz)² = r²
    // t²(dx + dz) + 2t(oxdx + ozdz) + (ox)² + (oz)² - r² = 0
    // a=(dx + dz); b = 2(oxdx + ozdz); c = (ox)² + (oz)² - r²
    float a = ray.getDirection().x*ray.getDirection().x + ray.getDirection().z*ray.getDirection().z;
    float b = 2*(ray.getOrigin().x*ray.getDirection().x + ray.getOrigin().z*ray.getDirection().z);
    float c = ray.getOrigin().x*ray.getOrigin().x + ray.getOrigin().z*ray.getOrigin().z - m_radius*m_radius;

    float discr = b*b - 4*a*c;
    if (discr < 0)
    {
        return Intersection(false);
    }

    float x1 = (-b+sqrt(discr))/(2*a);
    float x2 = (-b-sqrt(discr))/(2*a);

    float t;
    //choose the smallest and >=0 t
    if (x1 > x2)
    {
        t=x2;
    }

    if (t < 0)
    {
        t=x1;
    }

    // if both solution are <0 => NO INTERSECTION!
    if (t<0)
    {
        return Intersection(false);
    }

    // normal calculation
    // f(x,y) = x² + z² - r² = 0
    // T = (dx/dt, y, dz/dt)
    // 0 = df/dt = (df/dx, y, df/dz) · T
    // N = (2x, 0, 2z)
    vec3 point = ray.getOrigin() + ray.getDirection()*t;
    vec3 normal = vec3(2*point.x, 0.0f, 2*point.z);

    // If the y-component from point computed is smaller than 0 or bigger than height => NO INTERSECTION!
    if (point.y < 0 || point.y > m_height)
    {
        return Intersection(false);
    }

    //If ray direction is not pararel to Y Plane
    if (ray.getDirection().y != 0.0f) //Paralel
    {
        //Compute t's for point intersection in the Y Plane
        float t3 = (0-ray.getOrigin().y)/ray.getDirection().y;
        float t4 = (m_height-ray.getOrigin().y)/ray.getDirection().y;
        float t2;

        //choose the smallest and >=0 t
        t2 = std::min(t3,t4);
        if (t2 < 0)
        {
            t2 = std::max(t3,t4);
        }
        if (t2 >= 0)
        {
            // If there is a t >= 0 compute de point and check if the point is inside the cap
            vec3 point1 = ray.getOrigin() + ray.getDirection()*t2;
            std::cout << "point " << point1.y << " hipo "  << point1.x*point1.x + point1.z*point1.z << " radio " << m_radius*m_radius << std::endl;
            if (point1.x*point1.x + point1.z*point1.z <= m_radius*m_radius+0.9f)
            {
                // Intersection point is inside cap but, Which t is the smallest? t from cap or t from body cylinder?
                // I choose the smallest t and check if the t is from cap and compute normal and return intersection.
                t = std::min(t,t2);
                if (t == t3)
                {
                    normal = vec3(0.0f,-1.0f,0.0f);
                    return Intersection(true, point1, normal);
                }
                else if (t == t4)
                {
                    normal = vec3(0.0f,1.0f,0.0f);
                    return Intersection(true, point1, normal);
                }
            }
        }
    }

    // Intersection in the body cylinder, compute the point and return the intersection
    point = ray.getOrigin() + ray.getDirection()*t;

    return Intersection(true, point, normal);
}

this code result in the following image

(As you can see the top cap is not rendering, and I want to render the caps also)
I have been researching and the problem look like here:
point1.x*point1.x + point1.z*point1.z <= m_radius*m_radius
The code never enter here, here is the output text (generated by std::cout << "point " << point1.y << " hipo "  << point1.x*point1.x + point1.z*point1.z << " radio " << m_radius*m_radius << std::endl;) from the firsts pixeles (that should enter in that condition because the first pixeles corresponds with the top cap)
point 0.5 hipo 0.0900812 radio 0.09
point 0.5 hipo 0.0900206 radio 0.09
point 0.5 hipo 0.0900812 radio 0.09
point 0.5 hipo 0.0900206 radio 0.09
Pixel: y: 280
point 0.5 hipo 0.0913921 radio 0.09
point 0.5 hipo 0.120013 radio 0.09
point 0.5 hipo 0.0913921 radio 0.09
point 0.5 hipo 0.120013 radio 0.09
Pixel: y: 281
point 0.5 hipo 0.0930369 radio 0.09
point 0.5 hipo 0.183345 radio 0.09
point 0.5 hipo 0.0930369 radio 0.09
point 0.5 hipo 0.183345 radio 0.09
Pixel: y: 282
point 0.5 hipo 0.0950108 radio 0.09
point 0.5 hipo 0.261889 radio 0.09
point 0.5 hipo 0.0903952 radio 0.09
point 0.5 hipo 0.0903952 radio 0.09
point 0.5 hipo 0.0950108 radio 0.09
point 0.5 hipo 0.261889 radio 0.09
Pixel: y: 283
point 0.5 hipo 0.0973093 radio 0.09
point 0.5 hipo 0.347767 radio 0.09
point 0.5 hipo 0.0927148 radio 0.09
point 0.5 hipo 0.0927148 radio 0.09
point 0.5 hipo 0.0973093 radio 0.09
point 0.5 hipo 0.347767 radio 0.09

As you can see never hipo is < than radio
I want to render the whole cylinder with caps. Can anybody guide me to render the whole cylinder? (body and caps)
Thanks

A: I assume that you are able to find the intersection points between the ray and the cylinder surface, obtained as t values along the ray. Do a similar computation to find the intersections with the planes of the two basis.
You will get two pairs [tc0, tc1], [tp0, tp1]. If these intervals do not overlap, the ray doesn't hit the cylinder. Otherwise, the largest of tc0 and tp0 tells you what surface is actually hit, and this t value tells you where.


text:
Q: resize with custom allocator How can I resize a std::vector by using a custom allocator and not the copy constructor?
Here is what I tried:
#include <vector>
#include <iostream>

class A{
public:
  A(int x){
    std::cout<<" new a:"<<this<<" "<< x<<std::endl;
  }
};

template<typename T>
class ParamAlloc:public std::allocator<T>{
public:
  template<typename U> struct rebind {typedef ParamAlloc other;};

  void construct(typename std::allocator<T>::pointer p, typename std::allocator<T>::const_reference val){
    new ((void*)p) T(47);
  }

  void destroy(typename std::allocator<T>::pointer p){
    ((T*)p)->~T();
  }
};

int main(){

  ParamAlloc<A> all;
  std::vector<A,ParamAlloc<A> > ac(all);
  ac.resize(5);
}

but still I get compilation errors due to the compile trying to instantiate A::A().
Related to this question, what would be the best way (pre-C++11) to allocate a vector of objects of class A, where A's constuctor takes a parameter, but the A objects should not be copy constructed

A: Pre-C++11 the resize member is defined as:
resize(size_type n, const T& = T());

So when you call it as ac.resize(5) that actually means ac.resize(5, A()) which obviously needs a default constructor. The only workaround for C++03 is to provide an object to copy: ac.resize(5, A(99)), which says to resize the vector and construct any new elements as copies of A(99). The copies will be done by your custom allocator, which will actually construct them as A(47) instead of using the copy constructor.
The requirements for resize() have been relaxed for C++11 and the C++11 standard says in [vector.capacity] that vector::resize()

Requires: T shall be MoveInsertable and DefaultInsertable into *this.

DefaultInsertable requires that this is valid:
allocator_traits<A>::construct(m, p)

That call will try to call m.construct(p) on the allocator m if that is valid, but because your allocator does not support that it will do:
 ::new((void *)p) T()

which requires a default constructor.
If you want your custom allocator to be used for resize you need to provide a construct member that can be called with just one argument e.g.
void construct(typename std::allocator<T>::pointer p){
  new ((void*)p) T(47);
}

That should mean there is no need for a default constructor when resizing.

A: Just offer a default para for A(int x), the complie will pass.
class A{
public:
  A(int x=0){//here !!
    std::cout<<" new a:"<<this<<" "<< x<<std::endl;
  }
};

And the result is :
 new a:0x7fffe01aab5f 0
 new a:0x1c7d010 47
 new a:0x1c7d011 47
 new a:0x1c7d012 47
 new a:0x1c7d013 47
 new a:0x1c7d014 47

A: C++ standard defines certain requirements for item type for given containers.
For instance to be storable in vector in pre-C++11 T must meet the requirements of CopyAssignable and CopyConstructible. For resize to be available T must meet the requirements of DefaultConstructible. So, what you try to achieve is explicitly prohibited by pre-C++11 standard. Maybe you it would be enough for you to use vector::reserve instead of vector::resize or you just need a different container. It is possible in C++11 though - see answer by Jonathan Wakely.