Q:

Unknown type name after project reorganization

I am currently reorganizing a c project to use cmake as build generator. I am using the Cmake-Init project (https://github.com/cginternals/cmake-init) as a template for my project layout.
I think i have done the organizing part, the cmake generating part succeeds so far, but compiling fails. The compiler throws this error:
In file included from /home/simon/Documents/buffer/janus_oss_transition/source/ibis/include/ibis/ngramLM.h:48:0,
             from /home/simon/Documents/buffer/janus_oss_transition/source/base/include/base/list.h:46,
             from /home/simon/Documents/buffer/janus_oss_transition/source/stc/include/stc/cbn_parmat.h:45,
             from /home/simon/Documents/buffer/janus_oss_transition/source/stc/include/stc/cbnew.h:53,
             from /home/simon/Documents/buffer/janus_oss_transition/source/stc/source/cbn_common.c:40:
/home/simon/Documents/buffer/janus_oss_transition/source/base/include/base/array.h:76:55: error: unknown type name ‘List’
 extern int iarrayGetListItf( IArray* IA, char* value, List* L);
                                                       ^

array.h has only one include: #include "base/list.h"
list.h defines the typedef struct List like this:
#define LIST(T) \
{ \
 \
 T*              itemA;      /* array of items                      */ \
 int             itemN;      /* number of items in the list         */ \
 int             itemMax;    /* max. number of items in the list    */ \
 int             itemSize;   /* size of the indivual items          */ \
 int             itemSizeCP; \
 int             allocN;     /* number of allocated records in dsA  */ \
 int             blkSize;    /* block size for allocation           */ \
 int             compress;   /* compress list when deleting items   */ \
\
 TypeInfo*       typeInfo;   /* pointer to item type information    */ \
\
 int             sorted;     /* is array sorted                     */ \
 ListCmpFn*      sortCmp;    /* compare two items in the list       */ \
 int*            sortXA;     /* sorted index array                  */ \
\
 int*            hashTable; \
 HashRec*        hashXA; \
 int             hashSizeX;  /* hash size as index of hashPrimes    */ \
 int             hashSizeY;  /* hash size = hashPrimes(hashSIzeX)   */ \
 HashKeyFn*      hashKey; \
 HashCmpFn*      hashCmp; \
 ClientData      DataHolder;\
\
 ListItemInit*   init;       /* item initialization function        */ \
 ListItemDeinit* deinit; \
 ListItemLinkN*  links; \
\
}

typedef struct LIST(char*) List;

This is the CMakeLists for the "base" folder, containing array and list:
#
# External dependencies
#

# find_package(THIRDPARTY REQUIRED)

#
# Library name and options
#

# Target name
set(target base)

# Exit here if required dependencies are not met
message(STATUS "Lib ${target}")

# Set API export file and macro
string(MAKE_C_IDENTIFIER ${target} target_id)
string(TOUPPER ${target_id} target_id)
set(feature_file         "include/${target}/${target}_features.h")
set(export_file          "include/${target}/${target}_export.h")
set(template_export_file "include/${target}/${target}_api.h")
set(export_macro         "${target_id}_API")

#
# Sources
#

set(include_path "${CMAKE_CURRENT_SOURCE_DIR}/include/${target}")
set(source_path  "${CMAKE_CURRENT_SOURCE_DIR}/source")

set(headers
    ${include_path}/array.h
    ${include_path}/common.h
    ${include_path}/dbase.h
    ${include_path}/ffmat.h
    ${include_path}/list.h
    ${include_path}/mach_ind_io.h
    ${include_path}/matrix.h
)

set(sources
    ${source_path}/array.c
    ${source_path}/common.c
    ${source_path}/dbase.c
    ${source_path}/ffmat.c
    ${source_path}/list.c
    ${source_path}/mach_ind_io.c
    ${source_path}/matrix.c
    ${source_path}/matrix-io.c
    ${source_path}/melscale.c

)

# Group source files
set(header_group "Header Files (API)")
set(source_group "Source Files")
source_group_by_path(${include_path} "\\\\.h$|\\\\.hpp$"
    ${header_group} ${headers})
source_group_by_path(${source_path}  "\\\\.cpp$|\\\\.c$|\\\\.h$|\\\\.hpp$"
    ${source_group} ${sources})

#
# Create library
#

# Build library
add_library(${target}
    ${sources}
    ${headers}
)

# Create namespaced alias
add_library(${META_PROJECT_NAME}::${target} ALIAS ${target})

# Export library for downstream projects
export(TARGETS ${target} NAMESPACE ${META_PROJECT_NAME}:: FILE ${PROJECT_BINARY_DIR}/cmake/${target}/${target}-export.cmake)

# Create feature detection header
# Compilers: https://cmake.org/cmake/help/v3.1/variable/CMAKE_LANG_COMPILER_ID.html#variable:CMAKE_%3CLANG%3E_COMPILER_ID
# Feature: https://cmake.org/cmake/help/v3.1/prop_gbl/CMAKE_CXX_KNOWN_FEATURES.html

# Check for availability of module; use pre-generated version if not found
if (WriterCompilerDetectionHeaderFound)
    write_compiler_detection_header(
        FILE ${feature_file}
        PREFIX ${target_id}
        COMPILERS AppleClang Clang GNU MSVC
        FEATURES cxx_alignas cxx_alignof cxx_constexpr cxx_final cxx_noexcept cxx_nullptr cxx_sizeof_member cxx_thread_local
        VERSION 3.2
    )
else()
    file(
        COPY ${PROJECT_SOURCE_DIR}/source/codegeneration/${target}_features.h
        DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/include/${target}
        USE_SOURCE_PERMISSIONS
    )
endif()

#
# Project options
#

set_target_properties(${target}
    PROPERTIES
    ${DEFAULT_PROJECT_OPTIONS}
    FOLDER "${IDE_FOLDER}"
    VERSION ${META_VERSION}
    SOVERSION ${META_VERSION_MAJOR}
)

#
# Include directories
#

target_include_directories(${target}
    PRIVATE
    ${PROJECT_BINARY_DIR}/source/include
    ${CMAKE_CURRENT_SOURCE_DIR}/include
    ${CMAKE_CURRENT_BINARY_DIR}/include

    PUBLIC
    ${DEFAULT_INCLUDE_DIRECTORIES}

    INTERFACE
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}/include>
    $<INSTALL_INTERFACE:include>
)

#
# Libraries
#

target_link_libraries(${target}
    PRIVATE
    ${DEFAULT_LIBRARIES}
    ${META_PROJECT_NAME}::base
    ${META_PROJECT_NAME}::features
    ${META_PROJECT_NAME}::hmm
    ${META_PROJECT_NAME}::ibis
    ${META_PROJECT_NAME}::itf
    ${META_PROJECT_NAME}::models
    ${META_PROJECT_NAME}::stc
)

#
# Compile definitions
#

target_compile_definitions(${target}
    PRIVATE

    PUBLIC
    $<$<NOT:$<BOOL:${BUILD_SHARED_LIBS}>>:${target_id}_STATIC_DEFINE>
    ${DEFAULT_COMPILE_DEFINITIONS}

    INTERFACE
)

#
# Compile options
#

target_compile_options(${target}
    PRIVATE

    PUBLIC
    ${DEFAULT_COMPILE_OPTIONS}

    INTERFACE
)

#
# Linker options
#

target_link_libraries(${target}
    PRIVATE

    PUBLIC
    ${DEFAULT_LINKER_OPTIONS}

    INTERFACE
)

#
# Target Health
#

perform_health_checks(
    ${target}
    ${sources}
    ${headers}
)

#
# Deployment
#

# Library
install(TARGETS ${target}
    EXPORT  "${target}-export"            COMPONENT dev
    RUNTIME DESTINATION ${INSTALL_BIN}    COMPONENT runtime
    LIBRARY DESTINATION ${INSTALL_SHARED} COMPONENT runtime
    ARCHIVE DESTINATION ${INSTALL_LIB}    COMPONENT dev
)

# Header files
install(DIRECTORY
    ${CMAKE_CURRENT_SOURCE_DIR}/include/${target} DESTINATION ${INSTALL_INCLUDE}
    COMPONENT dev
)

# Generated header files
install(DIRECTORY
    ${CMAKE_CURRENT_BINARY_DIR}/include/${target} DESTINATION ${INSTALL_INCLUDE}
    COMPONENT dev
)

# CMake config
install(EXPORT ${target}-export
    NAMESPACE   ${META_PROJECT_NAME}::
    DESTINATION ${INSTALL_CMAKE}/${target}
    COMPONENT   dev
)

This is the CMakeLists for my targets. I am trying to build janus.
#
# External dependencies
#

# find_package(THIRDPARTY REQUIRED)

#
# Executable name and options
#

# Target name
set(target janus)
set(libTarget libjanus)

# Exit here if required dependencies are not met
message(STATUS "Example ${target}")

#
# Sources
#

set(sources
    janusInit.c
    janusMain.c
)

add_library(${libTarget} STATIC ${sources})
set_target_properties(${libTarget} PROPERTIES OUTPUT_NAME janus)
target_compile_definitions(${libTarget} PUBLIC -DIBIS)
target_include_directories(${libTarget}
    PRIVATE
    ${DEFAULT_INCLUDE_DIRECTORIES}
    ${PROJECT_BINARY_DIR}/source/include
)
target_link_libraries(${libTarget}
    PRIVATE
    ${DEFAULT_LIBRARIES}
    ${META_PROJECT_NAME}::base
    ${META_PROJECT_NAME}::features
    ${META_PROJECT_NAME}::hmm
    ${META_PROJECT_NAME}::ibis
    ${META_PROJECT_NAME}::itf
    ${META_PROJECT_NAME}::models
    ${META_PROJECT_NAME}::stc
)
target_compile_definitions(${libTarget}
    PRIVATE
    ${DEFAULT_COMPILE_DEFINITIONS}
)

#
# Create executable
#

# Build executable
add_executable(${target}

    ${sources}
)

# Create namespaced alias
add_executable(${META_PROJECT_NAME}::${target} ALIAS ${target})

#
# Project options
#

set_target_properties(${target}
    PROPERTIES
    ${DEFAULT_PROJECT_OPTIONS}
    FOLDER "${IDE_FOLDER}"
)

#
# Include directories
#

target_include_directories(${target}
    PRIVATE
    ${DEFAULT_INCLUDE_DIRECTORIES}
    ${PROJECT_BINARY_DIR}/source/include
)

#
# Libraries
#

target_link_libraries(${target}
    PRIVATE
    ${DEFAULT_LIBRARIES}
    ${META_PROJECT_NAME}::base
    ${META_PROJECT_NAME}::features
    ${META_PROJECT_NAME}::hmm
    ${META_PROJECT_NAME}::ibis
    ${META_PROJECT_NAME}::itf
    ${META_PROJECT_NAME}::models
    ${META_PROJECT_NAME}::stc
)

#
# Compile definitions
#

target_compile_definitions(${target}
    PRIVATE
    ${DEFAULT_COMPILE_DEFINITIONS}
    -DIBIS
)

if(NOT USE_TK)
        target_compile_definitions(${target} PUBLIC -DDISABLE_TK)
        target_compile_definitions(${libTarget} PUBLIC -DDISABLE_TK)
endif()

#
# Compile options
#

target_compile_options(${target}
    PRIVATE
    ${DEFAULT_COMPILE_OPTIONS}
)

#
# Linker options
#

target_link_libraries(${target}
    PRIVATE
    ${DEFAULT_LINKER_OPTIONS}
)

#
# Target Health
#

perform_health_checks(
    ${target}
    ${sources}
)

#
# Deployment
#

# Executable
install(TARGETS ${target}
    RUNTIME DESTINATION ${INSTALL_BIN} COMPONENT examples
    BUNDLE  DESTINATION ${INSTALL_BIN} COMPONENT examples
)

Did i might messed something in the cmake includes up? The files are in the same folder.
Thanks for your help
Simon
EDIT:
Added the CMakeLists.

A:

I found a circular include that seems to be the root of the error.


Q:

Como funciona o yield* no Javascript?

Muitas vezes, quando tenho uma dúvida que tenho certeza que já foi respondida, venho aqui no "Faça uma pergunta" e digito os termos que julgo chave no título, pra pegar as respostas relacionadas. Mas não achei nenhuma quando digitei essa.
Vi em alguns trechos de código a keyword yield*. Ela é diferente do yield?
Pesquisando sobre, cheguei a o seguinte exemplo de código:
function* g1() {
  yield 2;
  yield 3;
  yield 4;
}

Qual o motivo do * ao lado da keyword function? Tem a ver com o * ao lado de yield?

A:

Geradores
A sintaxe function* é utilizada para definir um gerador e yield é o análogo a return para um gerador.
O que é?
Gerador é considerado como uma função especial, responsável por criar um iterador. É caracterizado por calcular cada item pertencente ao elemento iterável por vez, ao invés de armazená-los todos em memória, como é feito sem o gerador. Característica esta que é conhecida por lazy evaluation.
Exemplo
Consideremos a sequência de Fibonacci, que cada elemento consiste na soma dos dois elementos anteriores. Sem utilizar um gerador, poderíamos fazer:

function fibonacci (n)
{
  var sequence = [];

  sequence.push(0, 1);

  for (let i = 2; i < n; i++)
  {
    sequence.push(sequence[i-1] + sequence[i-2]);
  }

  return sequence;
}

const sequence = fibonacci(10);

console.log(sequence.length);

O código acima irá gerar uma saída igual à 10, referente ao número de posições armazenadas em memória para a sequência. Para quantias pequenas, isso não afetaria a aplicação, mas se considerarmos um valor gigantesto, tal como um milhão de elementos, isso provavelmente afetaria o rendimento da sua aplicação.
Com o uso do gerador:

function* fibonacci (n)
{
  var a = 0, b = 1, current;

  while (true)
  {
    current = a;

    yield current;

    a = b;
    b = current + b;
  }
}

const sequence = fibonacci(10);

for (let i = 0; i < 10; i++)
{
  console.log(sequence.next().value);
}

Os elementos da lista não estarão em memória quando fizermos const sequence = fibonacci(10), os mesmos serão calculados dentro do for, apenas quando forem utilizados, através de sequence.next(). Mas e se a lista precisar ter um milhão de elementos? Sem problemas, como os elementos não ficam em memória, o gerador não afetará na sua aplicação (tempo de execução continuaria alto, pois continuaria a ser executado milhões de operações, mas na memória, não seria afetado).
Iterador
O retorno de um gerador é um iterador e, portanto, implementa o método next.

Utilização
Imagine que você deseja exibir uma lista com todos os nomes das cidades do Brasil, que totalizam um número de aproximadamente 5570, utilizando infinite scroll. Armazenar em memória os dados destes 5570 registros seria desnecessário, pois dificilmente o usuário usará todos eles. Então você poderia exibir em tela uma quantidade inicial, 20 por exemplo, e quando o usuário requerir mais, ao atingir o final da lista, fazer, com o gerador, uma requisição AJAX para o servidor solicitando mais 10 registros e adicionando-os à lista. Desta forma, os 5570 registros só estariam em memória se o usuário solicitasse isso.
Relacionados

Com fazer um iterator/generator no javascript?
Quais as vantagens de usar um Generator (yield) no PHP?
Iterators and generators

A sequência de Fibonacci, embora não muito utilizada na prática, foi usada como exemplo devido a facilidade de implementação.


Q:

Which euler angle order does this code result in?

Using the mathematics library GLM, I use this code to combine the euler angle rotations to a rotation matrix.
#include <GLM/gtc/matrix_transform.hpp>
using namespace glm;

mat4 matrix = rotate(mat4(1), X, vec3(1, 0, 0))
            * rotate(mat4(1), Y, vec3(0, 1, 0))
            * rotate(mat4(1), Z, vec3(0, 0, 1));

Does this result in an euler angle sequenze of XYZ or ZYX? I am not sure since matrix multiplication behave not the same as scalar multiplications.

A:

Remember that matrix calculation, in openGL, use a notation knows as vector column (http://en.wikipedia.org/wiki/Column_vector). So, any point transformation will be expressed by a system of linear equation, expressed in vector column notation like this:

[P'] = M.[P], where M = M1.M2.M3

This means that the first transformation that is applied to the points, expressed by vector [P] is M3, after that by M2 and at last by M1.
Answering your question, the resulting Euler angle will be ZXY, once Z rotation transformation is the last matrix that you write to form a matrix multiplication.


Q:

Counting k-tuples constrained to contain all elements

The elements for the k-tuples are: $\{1,2,\ ...\ ,n\}$. I know the total amount of tuples is $n^k$, but I fail to find a simple way to count the part of them containing all elements.
In mathematica I made this function, which does the thing (to be able to verify):
count[n_, k_] := Sum[Fold[{#[[1]] - #2, #[[2]] Binomial[#[[1]], #2]} &,
{n, 1}, Tally[i][[All, 2]]][[2]]/Times @@ (i!) k!, {i, IntegerPartitions[k, {n}]}]

It's not inefficient, however it's no way near the simple stuff my teacher wants. Does a simple formula even exist?

A:

Basically you are looking for the number of surjective (onto) functions from a set of size $k$ to a set of size $n$--in your case, the set of size $n$ is $\{1, 2,...,n\}$.
This can be determined with the Principle of Inclusion and Exclusion.
For a function (or equivalently a $k$-tuple) define events: $A_1$: 1 is not used in the $k$-tuple; $A_2$: 2 is not used in the tuple, etc.
Then $A_1\cup A_2\cup \cdots \cup A_n$ is the event that at least one number is not used in the tuple.  The size of this set can be counted by inclusion/exclusion.  Then you want the size of the complementary set (since you want every number to be used in the tuple.  But as you noted, you already know the size of the parent set, namely $n^k$.


Q:

Catastrophic failure when adding a ColorItem to a list

I'm trying to build a selector to let the user choose from some colors.
I'm using the RadListPicker component, with this code:
<telerikInput:RadListPicker IsEnabled="True" Grid.Row="4" Header="Tile color: " InlineModeThreshold="3" x:Name="listPicker2" ItemsSource="{Binding Items, Source={StaticResource ColorItems}}" SelectedItem="{Binding TileColor, Mode=TwoWay}">
    <telerikInput:RadListPicker.ItemTemplate>
         <DataTemplate>
             <StackPanel Orientation="Horizontal">
                 <Rectangle Fill="{Binding ColorName}" Width="24" Height="24"/>
                 <TextBlock Text="{Binding ColorName}" Margin="12 -3 0 0"/>
             </StackPanel>
         </DataTemplate>
    </telerikInput:RadListPicker.ItemTemplate>
</telerikInput:RadListPicker>

where ColorItems is this class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using Microsoft.Phone.Net.NetworkInformation;

namespace Utils
{
    public class ColorItems
    {
        private static readonly ColorItem[] _colorItems =
        {
            new ColorItem(GetFromRGB(240, 163, 10), "Amber"),
            new ColorItem(GetFromRGB(130, 90, 44), "Brown"),
            //new ColorItem(GetFromRGB(162, 0, 37), "Crimson"),
            //new ColorItem(GetFromRGB(0, 80, 239), "Cobalt"),
            new ColorItem(GetFromRGB(27, 161, 226), "Cyan"),
            //new ColorItem(GetFromRGB(0, 138, 0),"Emerald"),
            new ColorItem(GetFromRGB(96, 169, 23),"Green"),
            new ColorItem(GetFromRGB(106, 0, 255),"Indigo"),
            new ColorItem(GetFromRGB(164, 196, 0),"Lime"),
            new ColorItem(GetFromRGB(216, 0, 115),"Magenta"),
            //new ColorItem(GetFromRGB(118, 96, 138),"Mauve"),
            new ColorItem(GetFromRGB(109, 135, 100),"Olive"),
            new ColorItem(GetFromRGB(250, 104, 0),"Orange"),
            new ColorItem(GetFromRGB(244, 114, 208),"Pink"),
            new ColorItem(GetFromRGB(229, 20, 0),"Red"),
            //new ColorItem(GetFromRGB(100, 118, 135),"Steel"),
            //new ColorItem(GetFromRGB(135, 121, 78),"Taupe"),
            new ColorItem(GetFromRGB(0, 171, 169),"Teal"),
            new ColorItem(GetFromRGB(170, 0, 255),"Violet"),
            new ColorItem(GetFromRGB(227, 200, 0),"Yellow"),
        };

        private static Color GetFromRGB(byte r, byte g, byte b)
        {
            return new Color {R = r, B = b, G = g, A = 255};
        }

        public static ColorItem GetFromColor(Color color)
        {
            return _colorItems.First(c => c.Color.Equals(color));
        }

        public static ColorItem[] Items
        {
            get
            {
                return _colorItems;
            }
        }
    }
}

and ColorItem is:
public class ColorItem
{
    public ColorItem(Color color, string name)
    {
        this.Color = color;
        this.ColorName = name;
    }

    public Color Color
    {
        get;
        set;
    }

    public string ColorName
    {
        get;
        set;
    }
}

As you can see, in ColorItems._colorItems i have some commented lines.
Without those lines, everything goes smooth.
(Please note that errors and messages have been translated from Italian, so they may not be accurate as you may expect)
But when I enable just one of them, it throws an exception saying:

First-chance exception 'System.Exception' in System.Windows.ni.dll
  Catastrophic failure (Exception from HRESULT: 0x8000FFFF
  (E_UNEXPECTED))

and I've no idea of why it throws such a scary exception!
Here's the full stack trace.
System.Windows.ni.dll!MS.Internal.XcpImports.CheckHResult(uint hr)  Unknown
System.Windows.ni.dll!MS.Internal.XcpImports.ConvertStringToTypedCValue(System.IntPtr pContext, uint cClrTypeName, string clrTypeName, uint cValue, string value, ref MS.Internal.CValue outVal, out int typeIndex) Unknown
System.Windows.ni.dll!MS.Internal.SilverlightTypeConverter.ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)    Unknown
System.Windows.ni.dll!MS.Internal.Data.DefaultValueConverter.ConvertHelper(object o, System.Type destinationType, System.Globalization.CultureInfo culture, bool isForward) Unknown
System.Windows.ni.dll!MS.Internal.Data.TargetDefaultValueConverter.Convert(object o, System.Type type, object parameter, System.Globalization.CultureInfo culture)  Unknown
System.Windows.ni.dll!MS.Internal.Data.DynamicValueConverter.Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)  Unknown
System.Windows.ni.dll!System.Windows.Data.BindingExpression.ConvertToTarget(object value = "Amber") Unknown
System.Windows.ni.dll!System.Windows.Data.BindingExpression.GetValue(System.Windows.DependencyObject d, System.Windows.DependencyProperty dp)   Unknown
System.Windows.ni.dll!System.Windows.DependencyObject.EvaluateExpression(System.Windows.DependencyProperty property = {System.Windows.CoreDependencyProperty}, System.Windows.EffectiveValueEntry oldEntry, ref System.Windows.EffectiveValueEntry newEntry = {System.Windows.EffectiveValueEntry}) Unknown
System.Windows.ni.dll!System.Windows.DependencyObject.EvaluateBaseValue(System.Windows.DependencyProperty property, System.Windows.EffectiveValueEntry oldEntry, ref System.Windows.EffectiveValueEntry newEntry, System.Windows.DependencyObject.ValueOperation operation) Unknown
System.Windows.ni.dll!System.Windows.DependencyObject.EvaluateEffectiveValue(System.Windows.DependencyProperty property, System.Windows.EffectiveValueEntry oldEntry, System.Windows.EffectiveValueEntry newEntry, System.Windows.DependencyObject.ValueOperation operation = Reevaluate)   Unknown
System.Windows.ni.dll!System.Windows.DependencyObject.UpdateEffectiveValue(System.Windows.DependencyProperty property = {System.Windows.CoreDependencyProperty}, System.Windows.EffectiveValueEntry oldEntry, ref System.Windows.EffectiveValueEntry newEntry = {System.Windows.EffectiveValueEntry}, System.Windows.DependencyObject.ValueOperation operation) Unknown
System.Windows.ni.dll!System.Windows.DependencyObject.RefreshExpression(System.Windows.DependencyProperty dp)   Unknown
System.Windows.ni.dll!System.Windows.Data.BindingExpression.SendDataToTarget()  Unknown
System.Windows.ni.dll!System.Windows.Data.BindingExpression.SourceAcquired()    Unknown
System.Windows.ni.dll!System.Windows.Data.BindingExpression.System.Windows.IDataContextChangedListener.OnDataContextChanged(object sender, System.Windows.DataContextChangedEventArgs e)    Unknown
System.Windows.ni.dll!System.Windows.Data.BindingExpression.DataContextChanged(object sender, System.Windows.DataContextChangedEventArgs e) Unknown
System.Windows.ni.dll!System.Windows.FrameworkElement.OnDataContextChanged(System.Windows.DataContextChangedEventArgs e)    Unknown
System.Windows.ni.dll!System.Windows.FrameworkElement.OnAncestorDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) Unknown
System.Windows.ni.dll!System.Windows.FrameworkElement.NotifyDataContextChanged(System.Windows.DataContextChangedEventArgs e = {System.Windows.DataContextChangedEventArgs}) Unknown
System.Windows.ni.dll!System.Windows.FrameworkElement.OnTreeParentUpdated(System.Windows.DependencyObject newParent, bool bIsNewParentAlive)    Unknown
System.Windows.ni.dll!System.Windows.DependencyObject.UpdateTreeParent(MS.Internal.IManagedPeer oldParent = null, MS.Internal.IManagedPeer newParent = {System.Windows.Controls.ContentPresenter}, bool bIsNewParentAlive, bool keepReferenceToParent = true)   Unknown
System.Windows.ni.dll!MS.Internal.FrameworkCallbacks.ManagedPeerTreeUpdate(System.IntPtr oldParentElement, System.IntPtr parentElement, System.IntPtr childElement, byte bIsParentAlive, byte bKeepReferenceToParent, byte bCanCreateParent)    Unknown
[From native to managed]
[From managed to native]
System.Windows.ni.dll!MS.Internal.XcpImports.FrameworkElement_MeasureOverride(System.Windows.FrameworkElement element = {Telerik.Windows.Controls.RadDataBoundListBoxItem}, System.Windows.Size availableSize)  Unknown
System.Windows.ni.dll!System.Windows.FrameworkElement.MeasureOverride(System.Windows.Size availableSize)    Unknown
System.Windows.ni.dll!System.Windows.FrameworkElement.MeasureOverride(System.IntPtr nativeTarget, double inWidth, double inHeight, out double outWidth = 0.0, out double outHeight = 0.0)   Unknown
[From native to managed]
[From managed to native]
System.Windows.ni.dll!MS.Internal.XcpImports.UIElement_Measure(System.Windows.UIElement element = {Telerik.Windows.Controls.RadDataBoundListBoxItem}, System.Windows.Size availableSize)    Unknown
System.Windows.ni.dll!System.Windows.UIElement.Measure(System.Windows.Size availableSize)   Unknown
telerik.windows.controls.primitives.DLL!Telerik.Windows.Controls.StackVirtualizationStrategy.MeasureContainer(Telerik.Windows.Controls.RadVirtualizingDataControlItem container = {Telerik.Windows.Controls.RadDataBoundListBoxItem})   Unknown
telerik.windows.controls.primitives.DLL!Telerik.Windows.Controls.VirtualizationStrategy.GetContainerForItem(Telerik.Windows.Data.IDataSourceItem item = {Telerik.Windows.Data.DataSourceItem}, int insertAt = 0)    Unknown
telerik.windows.controls.primitives.DLL!Telerik.Windows.Controls.StackVirtualizationStrategy.GetContainerForItem(Telerik.Windows.Data.IDataSourceItem item = {Telerik.Windows.Data.DataSourceItem}, int insertAt = 0)   Unknown
telerik.windows.controls.primitives.DLL!Telerik.Windows.Controls.VirtualizationStrategy.GetContainerForItem(Telerik.Windows.Data.IDataSourceItem item = {Telerik.Windows.Data.DataSourceItem}, bool insertLast = true)  Unknown
telerik.windows.controls.primitives.DLL!Telerik.Windows.Controls.VirtualizationStrategy.ManageLowerViewport(bool recycle = true)    Unknown
telerik.windows.controls.primitives.DLL!Telerik.Windows.Controls.RadVirtualizingDataControl.ManageViewport()    Unknown
telerik.windows.controls.primitives.DLL!Telerik.Windows.Controls.RadVirtualizingDataControl.BalanceVisualSpace()    Unknown
telerik.windows.controls.primitives.DLL!Telerik.Windows.Controls.RadVirtualizingDataControl.OnLoaded(object sender = {Telerik.Windows.Controls.RadDataBoundListBox}, System.Windows.RoutedEventArgs e = {System.Windows.RoutedEventArgs})   Unknown
telerik.windows.controls.primitives.DLL!Telerik.Windows.Controls.RadDataBoundListBox.OnLoaded(object sender = {Telerik.Windows.Controls.RadDataBoundListBox}, System.Windows.RoutedEventArgs e = {System.Windows.RoutedEventArgs})  Unknown
System.Windows.ni.dll!MS.Internal.CoreInvokeHandler.InvokeEventHandler(int typeIndex, System.Delegate handlerDelegate, object sender, object args)  Unknown
System.Windows.ni.dll!MS.Internal.JoltHelper.FireEvent(System.IntPtr unmanagedObj, System.IntPtr unmanagedObjArgs, int argsTypeIndex, int actualArgsTypeIndex, string eventName)    Unknown

Does anyone know what's going on?

A:

The Fill property is bound to ColorName property (probably instead of Color).
What is most likely happening is that instead of using your custom defined colors, the rectangle is filled with Predifined Colors (identified by names).
So in most common cases, it works because names given to your custom colors match predifined colors! But when it does not match (colors that are commented), no color to be displayed is found and a Catastrophic failure or another freaky exception could happened ;)


Q:

RxAndroid ViewObservable NetworkOnMainThreadException

I have a Button from which I create an Observable<OnClickEvent>.
When the button is clicked, I wish to fetch a file from the network, but I run into issues regarding networking and threads.
This example throws android.os.NetworkOnMainThreadException :
Observable<OnClickEvent> networkButtonObservable = ViewObservable.clicks(testNetworkButton);
networkButtonObservable
    .map(new Func1<OnClickEvent, List<String>>() {
             @Override
             public List<String> call(OnClickEvent onClickEvent) {
                 return TestAPI.getTestService().fetchTestResponse();
             }
         }
    )
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<Object>() {
                   @Override
                   public void call(Object o) {Log.w("Final result: " + o);
                   }
               }
    );

So I try from another thread.
The following throws rx.exceptions.OnErrorNotImplementedException: Observers must subscribe from the main UI thread, but was Thread[RxNewThreadScheduler-1,5,main] :
networkButtonObservable
    .subscribeOn(Schedulers.newThread())
    .map(new Func1<OnClickEvent, List<String>>() {
             @Override
             public List<String> call(OnClickEvent onClickEvent) {
                 return TestAPI.getTestService().fetchTestResponse();
             }
         }
    )
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<Object>() {
                   @Override
                   public void call(Object o) {Log.w("Final result: " + o);
                   }
               }
    );

Ok.. Now I try with a .debounce() at the start :
networkButtonObservable
    .debounce(10, TimeUnit.MILLISECONDS)
    .map(new Func1<OnClickEvent, List<String>>() {
             @Override
             public List<String> call(OnClickEvent onClickEvent) {
                 return TestAPI.getTestService().fetchTestResponse();
             }
         }
    )
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<Object>() {
                   @Override
                   public void call(Object o) {Log.w("Final result: " + o);
                   }
               }
    );

And this succeeds.
Obviously I do not like to add delays to my code, so I am trying to figure out what's going on, thread-wise. Why is the first example not also executing the code inside the .map() in a background thread?
Or what am I missing here?
--- Update
I change my TestAPI to return an Observable, and change the first call to the networkButtonObservable to .flatMap(). This also functions properly. But I still don't know why the original way using .map() should fail.
networkButtonObservable
    .flatMap(new Func1<OnClickEvent, Observable<?>>() {
        @Override
        public Observable<?> call(OnClickEvent onClickEvent) {
            return TestAPI.getTestService().fetchTestResponseObservable();
        }
    })
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<Object>() {
                   @Override
                   public void call(Object o) {Log.w("Final result: " + o);
                   }
               }
    );

A:

I'm not an expert in Android but based on the error messages, I think you need to bounce the value between the main thread and the background thread. Usually, Android examples show you to add a subscribeOn/observeOn pair to your stream processing:
Observable.just(1)
.map(v -> doBackgroundWork())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(v -> {});

but in these cases, the 'source' is usually a cold observable you are in control.
In your question, the source is a hot Observable with specific requirements that you need to subscribe on the main thread, yet you need to do a network call on a background thread and then show the results on the main thread.
In this case, you can use observeOn multiple times:
networkButtonObservable
.subscribeOn(AndroidSchedulers.mainThread()) // just in case
.observeOn(Schedulers.io())
.map(v -> TestAPI.getTestService().fetchTestResponse())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(v -> updateGUI(v));

I think fetchTestResponseObservable has its own subscribeOn or observeOn applied to it so it doesn't throw the network exception.
Also I'd like to mention that using multiple subscribeOn is functionally equivalent to using only one that is closest to the emitting source, but technically it will hog unused threading resources. Using multiple observeOn in a stream, however, has relevance because you can meaningfully 'pipeline' the stream processing between threads with them.


Q:

Express, correct way to check the presence of a parameter in the body

Which is the correct way of checking the presence of a parameter in the body?
I'm using if(req.body.hasOwnProperty('myParam')){...} but i see that someone just write if(req.body.myParam){...} but this second option will return false if the param has a numeric value of 0, doesn't it?

A:

Right.
if you want to check if the attribute exists so hasOwnProperty will do the job.
Using req.body.myParam will return false for any falsely such as 0, '', false, null or undefined.
Also note that the dot notation and the hasOwnProperty method do no have the same behavior :

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

So it can be confusing, for example, run the above snippet :

var o = new Object();

if (o.toString) {
  console.log('Dot notation can be confusing, inherited property example : ', o.__proto__.toString);
}

if (o.hasOwnProperty('toString')) {
  // nope
} else {
  console.log("that's why the hasOwnProperty method can be preferred");
}


Q:

How do I get a property value from an object in a foreach loop?

I iterate through an array(using a foreach loop) that contains two 'High Season' objects - the two objects have an id, start date and end date. I get the high season start date via getter and assign it to a variable with intentions of incrementing the month when I loop through the date difference of the high season's start date and end date. When I loop through the date difference, the Booking start date and end date are compared against the variable I have been incrementing by month, and then the variable "containing" the date is incremented by one month.
Does this variable contain a reference to the array's high season object's start date property? when I dump the high seasons array the start date has changed to the same date as the variable that has been incremented by one month. How do I get the value of the high season start date property and not the reference of the array object's start date?
I am using PHP 5.5.30.
foreach ($highseasons as $highseason) {
    $HSDate = $highseason->getStartDate();
    $diff = date_diff($highseason->getStartDate(), $highseason->getEndDate());

    $months = (int)$diff->format('%m');
    $SDBool = false;
    $EDBool = false;

    // loop through the date difference
    for ($i = 0; $i <= $months; $i++) {
        var_dump($highseasons);
        $HSMonth = $HSDate->format('m');
        $BookingStartingMonth = $value->getStartDate()->format('m');
        $BookingEndingMonth = $value->getEndDate()->format('m');

        if ($HSMonth == $BookingStartingMonth) {
            $SDBool = true;
        }

        if ($HSMonth == $BookingEndingMonth) {
            $EDBool = true;
        }

        // add one month onto the high season date
        $HSDate->add(new DateInterval('P1M'));
    }
}

A:

As the start date is a DateTime object, yes it is a reference and modifying it will change the value of the highseason's start date as well (since they are the same object).
In order to do what you are asking for, you need to clone the DateTime object:
$tempDate = clone $HSDate;

and increment the new date object instead.


Q:

GStreamer Runtime Error

It tried to run a GStreamer Tutorial Example, that already worked, but didn't work anymore right now. I didn't change the source code. I build the Project with CMake.
I get the following Error on every of my Testprograms, that are slightly different from each other:
(GStreamer_Test_AppSrc:28073): GLib-GObject-CRITICAL **: g_param_spec_boxed: assertion `G_TYPE_IS_BOXED (boxed_type)' failed
(GStreamer_Test_AppSrc:28073): GLib-GObject-CRITICAL **: g_object_class_install_property: assertion `G_IS_PARAM_SPEC (pspec)' failed
(GStreamer_Test_AppSrc:28073): GLib-GObject-WARNING **: gsignal.c:1644: parameter 1 of type `<invalid>' for signal "GstAppSrc::push_buffer" is not a value type
(GStreamer_Test_AppSrc:28073): GLib-GObject-WARNING **: cannot register existing type `GstObject'
(GStreamer_Test_AppSrc:28073): GLib-CRITICAL **: g_once_init_leave: assertion `result != 0' failed
(GStreamer_Test_AppSrc:28073): GLib-GObject-CRITICAL **: g_type_register_static: assertion `parent_type > 0' failed
(GStreamer_Test_AppSrc:28073): GLib-CRITICAL **: g_once_init_leave: assertion `result != 0' failed
(GStreamer_Test_AppSrc:28073): GStreamer-CRITICAL **: gst_element_class_set_static_metadata: assertion `GST_IS_ELEMENT_CLASS (klass)' failed
(GStreamer_Test_AppSrc:28073): GStreamer-CRITICAL **: gst_caps_ref: assertion `GST_CAPS_REFCOUNT_VALUE (caps) > 0' failed
(GStreamer_Test_AppSrc:28073): GStreamer-CRITICAL **: gst_caps_ref: assertion `GST_CAPS_REFCOUNT_VALUE (caps) > 0' failed
(GStreamer_Test_AppSrc:28073): GStreamer-CRITICAL **: gst_caps_unref: assertion `GST_CAPS_REFCOUNT_VALUE (caps) > 0' failed

A:

The Problem was, that i had installed GStreamer 0.10.x AND 1.x and mixed together both respectively CMake.
CMake remembered some Cache Settings, when i tried to compile my Project with GStreamer 1.x. After cleaning up the Out-of-Source Build Directory of the CMake-Project and rebuilt the Project again with solely GStreamer-0.10.x Dependencies, my Programs again worked as expected.


Q:

How should I respond to a 6 year old's dark drawings?

My 6 year old nephew likes to draw. Most of the drawings have been of the family, animals and locations we visit or that he would like to visit. Until recently, I wouldn't describe any of these images as being dark.
Over the last fortnight, some of the images have been dark. To cite 2 examples:

One drawing was of a saber-tooth tiger surrounded by 3 human hunters with spears. There was a lot of red on the page indicating blood
One drawing was of the family dog, who sadly passed away in October last year. Most of the drawing was fine, except the dog was urinating heavily. My nephew thought this aspect to be hilarious

Now I think it is important to give some background of his home life:

He is actually very kind. He treats younger children very well and likes meeting the neighbours' friendly pets
His parents are going through a rough patch at the moment. His father (my brother) is suffering from a midlife crisis and is having an affair. This is well known to everyone in the family except my nephew
There has been bereavement in the family. As mentioned, the family pet died a few months ago, and his paternal grandfather died 2 years' ago

When I saw the drawings I didn't know how to respond. Part of me feels that it is beneficial for him to express his feelings, whereas another part feels concerned about the social stigma associated with the drawings if other people found out about them.
My questions are:

Should I be worried about the darker aspects of his drawings?
How should I respond to them?

A:

I wouldn't consider that dark. Dark would be every drawing having family members dead or something. Specific to people you know. I used to draw medieval scenes with gruesome atrocities but it was not cause I was disturbed or anything. Still got me sent to psychologists which was a complete waste of time.
Should you be worried? I say no. Not yet.
How should you respond? I say don't. Not yet.
Now back to my own experiences - I just liked to draw. I was into knights. I drew people getting slaughtered from as far back as something like 7 or 8 years old I guess. I made flip books usually involving massacres. Lots of blood. etc. I had no resentment toward anyone. I was not angry. I was not sad. I just liked to draw and usually that's what came to mind because really think about the alternatives to young kids.
My parents took me to see psychologists. That was a huge mistake. That made me mad. When I was there, I couldn't be doing what I wanted to do, which was draw. And probably draw people being murdered. The thing is they chose to focus on what I was drawing and not what I was doing with every other aspect of my day. It's not like I was capturing animals and killing them. I was building legos... usually castles and knights where lego men got slaughtered. Making cushion forts, reading comic strip books like garfield and calvin and hobbes. Basically doing what little boys do. Aside my interest in drawing murder scenes, I was normal.
I would pay attention to all activities in his general day. If he has other interests, then casually think about what is thought process may be. If it all seems to point back to murder, then maybe ask a professional in child psychology. I despise and absolutely do not respect that vocation, but I'd still recommend giving it a try if you genuinely feel your kid thinks of murder all day long. Otherwise, he's just drawing what he's currently interested in.

A:

My three year old is fascinated by many aspects of the lifestyle of stone age hunter-gatherers, including the manufacture of stone tools, the slaughter of mammoths, and the (hypothesized) construction of shelters from their tusks and bones. He can't draw very well yet, but he play-acts all of these things.
We (my family) are omnivores, and my son understands that animals die when we eat them. I think it's perfectly normal and healthy for him to be interested in the harsh reality of where meat comes from, whether hunted or bought at the grocery store. I think this is part of being environmentally aware and responsible. It's not something to be concerned about at all, unless it becomes a fascination with causing suffering or killing for its own sake.
As for drawing the dog peeing, I find that pretty hilarious myself.

A:

I would not worry. These are not dark images in the normal sense.
First, a kid likes to draw what they see and hear, and their sense of humor may be tied to more simple things then our. So, for:

One drawing was of a saber-tooth tiger surrounded by 3 human hunters with spears. There was a lot of red on the page indicating blood

That's "normal" exploring of the cause and effect of hunting, death, and the like. It's what we do as humans. We kill animals and eat them. The animal has to die to for that to happen and this is a normal way to "explore" that. It's much better than, say, trying to stab the neighbor's dog to see what happens. Unless they are drawing a specific animal (Susan's Cat) many times, then it's really not important and just normal.

One drawing was of the family dog, who sadly passed away in October last year. Most of the drawing was fine, except the dog was urinating heavily. My nephew thought this aspect to be hilarious

Pee is just funny. Be glad you didn't have to, or don't have to go through the phase of the child peeing on things just because it's funny. Our son thought it was a blast to pee in his bedroom for about 6 weeks. He would just whip it out and let it fly, the giggle the entire time. This can happen for lots of reasons, but none of them are "warning signs".


Q:

Error while using the Auth0 spa quickstart

I'm currently working on an Angular 2 web app that will use Auth0 for user authentication.
I followed the quickstart at the Auth0 website, but I'm getting the error Cannot read property 'WebAuth' of undefined at new AuthService (auth.service.ts:9), even though AuthService is declared.
Am I missing something? Any help is very much appreciated.
This is my code
//app.component.ts
import { Component } from '@angular/core';
import { AuthService } from '../../auth/auth.service';

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {

    constructor(public auth: AuthService) {
        auth.handleAuthentication();
    }
}

//auth.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import auth0 from 'auth0-js';

@Injectable()
export class AuthService {

    auth0 = new auth0.WebAuth({
        clientID: '*****',
        domain: '*****',
        responseType: 'token id_token',
        audience: '******',
        redirectUri: 'http://localhost:4200/callback',
        scope: 'openid'
    });

    constructor(public router: Router) { }

    public login(): void {
        this.auth0.authorize();
    }

    public handleAuthentication(): void {
        this.auth0.parseHash((err, authResult) => {
            if (authResult && authResult.accessToken && authResult.idToken) {
                window.location.hash = '';
                this.setSession(authResult);
                this.router.navigate(['/home']);
            } else if (err) {
                this.router.navigate(['/home']);
                console.log(err);
            }
        });
    }

    private setSession(authResult): void {
        // Set the time that the access token will expire at
        const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
        localStorage.setItem('access_token', authResult.accessToken);
        localStorage.setItem('id_token', authResult.idToken);
        localStorage.setItem('expires_at', expiresAt);
    }

    public logout(): void {
        // Remove tokens and expiry time from localStorage
        localStorage.removeItem('access_token');
        localStorage.removeItem('id_token');
        localStorage.removeItem('expires_at');
        // Go back to the home route
        this.router.navigate(['/']);
    }

    public isAuthenticated(): boolean {
        // Check whether the current time is past the
        // access token's expiry time
        const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
        if (new Date().getTime() < expiresAt) {
            return true;
        } else {
            return false;
        }
    }

}

//app.html

            Auth0 - Angular

            <button class="btn btn-primary btn-margin"
                    routerLink="/">
                Home
            </button>

            <button class="btn btn-primary btn-margin"
                    *ngIf="!auth.isAuthenticated()"
                    (click)="auth.login()">
                Log In
            </button>

            <button class="btn btn-primary btn-margin"
                    *ngIf="auth.isAuthenticated()"
                    (click)="auth.logout()">
                Log Out
            </button>

    <router-outlet></router-outlet>

Thank you

A:

Have you tried to import it this way:
import * as auth0 from 'auth0-js';


Q:

Trouble with 'Anonymous' and 'Negotiate,NTLM' authentication in IIS7.5

I have added the following configuration section to my web.config file
<security>
  <authentication>
    <anonymousAuthentication enabled="true" />
    <windowsAuthentication enabled="true" />
  </authentication>
</security>

But when I call the *.asmx web service, I still got the following error:

The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM'.

I am using the IIS7.5 ASP.NET integrated mode.
Any clues?  I just found the IIS Authenticatino is very poor and unstable.
Thanks!

A:

It turns out that we need to grant NTFS permission to target folder for the Anonymous Authentication Authenticated As identity, besides enable Anonymous Authentication in IIS.
Windows Authentication happens in both IIS and NTFS file system. I always forget the latter one. I will cut my dummy brain.


Q:

Pygame 'pygame.Surface' object is not callable

I am  trying make a game pygame library.But there is an error.
I looked some forums but i can't anything.
If can help me , i be happy.
File C:/Users/User/PycharmProjects/zaxd/main.py", line 34, in <module>
    screen.blit(playerImg(playerX, playerY))
TypeError: pygame.Surface object is not callable

'''
       import pygame
    # Initialize library
    pygame.init()
    # Variables
    running = True
    pd = pygame.display
    pi = pygame.image
    # Create Screen
    screen = pygame.display.set_mode((800, 600))
    # Caption and Icon
    pd.set_caption("Space Invaders")
    icon = pi.load('ufo.png')
    pd.set_icon(icon)
    # Player
    playerImg = pi.load('plane.png')
    playerX = 370
    playerY = 480

    def player():
        screen.blit(playerImg(playerX, playerY))

    # Game Loop
    while running:

        screen.fill((0, 0, 0))
        for event in pygame.event.get():
            if event == pygame.QUIT:
                running = False
        # Change BG Color (Black)
        player()
        pd.update()
    '''

A:

You were missing a comma between playerImg and the (x,y) coordinates
screen.blit(playerImg,(playerX, playerY))


Q:

Inconsistencies in ASCII conversion of UTF-8 in Properties files

Does anyone know why native2ascii generates lower-case hex codes, while Properties.store() produces upper-case hex?
Example:
保存 is encoded as \u4FDD\u5B58 when using Properties.store(), but is encoded as \u4fdd\u5b58 when using native2ascii
Is there any way to control this?

A:

I don't know why but I do know it doesn't matter (to Java anyway, it may matter to you a great deal). Unicode escapes are allowed to have upper or lower case hex digits so it really doesn't matter to Java which one is used (even mixed case is valid).
The reason they're different is probably something as simple as they were written by two different people.
Is there any way to control it? Not easily from what I can see. It doesn't appear that native2ascii has any options to control that output (it allows options to control the JVM but not to that level).
Properties.store() uses an OutputStream (and Properties.load() uses an InputStream) which you could probably subclass to filter the Unicode escapes but that seems an awful lot of work for (what looks like) dubious benefit.
Perhaps if you could tell us why you need this, there may be another way.
Update 1:
One thing that you could do is to pass the native2ascii output through a filter which turns the Unicode escape sequeces into uppercase. The following code ucunicode.c should be able to do this although I've only given it cursory testing. Simply execute:
native2ascii inputFile | ucunicode

and you should see the likes of \u00EF\u00BB\u00BF instead of \u00ef\u00bb\u00bf.
#include <stdio.h>

int main (void) {
    int count = 0;     // used for converting four hex digits after "\u".
    int chminus2 = -1; // character from two passes ago.
    int chminus1 = -1; // character from one pass ago.
    int ch;            // character for this pass.

    // Standard filter loop.

    while ((ch = getc (stdin)) != EOF) {
        if (count-- > 0) {
            // If processing Unicode escape sequence, uppercase letters.

            putchar (((ch >= 'a') && (ch <= 'f')) ? ch - 'a' + 'A' : ch);
        } else {
            // Normal processing, detect escape sequence and flag it.

            if ((chminus2 != '\\') && (chminus1 == '\\') && (ch == 'u')) {
                count = 4;
            }

            // In any case, output the character.

            putchar (ch);
        }

        // Shift characters "left".

        chminus2 = chminus1;
        chminus1 = ch;
    }
    return 0;

}
There may be edge cases that this doesn't handle well. I'm pretty certain it will handle all valid input but may break on invalid input like \u1\\u0000 but, since that means your native2ascii is broken, you'll need to debug them yourself. This is a good start however.
Update 2:
Or, as a last-ditch solution, the OpenJDK project has the actual source files for native2ascii in jdk\src\share\classes\sun\tools\native2ascii\ (and just about everything else that's not encumbered by copyright) which you could bring down and compile yourself (GPL2 applies). The files are Main.java, A2NFilter.java and N2AFilter.java (and a couple of resource files). You'd simply have to change N2AFilter.java to call:
String hex = Integer.toHexString(buf[i]).toUpperCase();

instead of just:
String hex = Integer.toHexString(buf[i]);

In fact, by examining that source code, you can see that Properties.store() (in jdk/src/share/classes/java/util/Properties.java) uses the following functions to create it's Unicode escapes:
private static final char[] hexDigit = {
    '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
};
private static char toHex (int nibble) {
    return hexDigit[(nibble & 0xF)];
}

This explains why it generates upper case while native2ascii produces lower case.


Q:

From DDD perspective can I have repository for non-aggregate-root

In my current (JPA) project I have basically 2 entities. ChainOfClassesA and ClassA. Now ChainOfClassesA is basically a bidirectional list of ClassA (@OneToMany) and couple of other attributes. For me it seems that ChainOfClassesA is an aggregate root and thus has dedicated repository. Now, one use-case is to update ClassA. I know I could just create repository for ClassA but this would violate the rule "one repository for each root aggregate entity" as ClassA is not really an aggregate root, although this hints me that it could potentially be, or potentially I should "flatten ChainOfClassesA".
Now my question is should I be pragmatic and "just break the rules" and create dedicated repository for ClassA or follow the rules and replace birectional list @OneToMany in ChainOfClassesA with ID reference to ChainOfClassesA in ClassA. First approach is pragmatic and requires only a little work whereas latter approach requires also some other changes to the codebase. What are your thoughts? Especially why I should'nt create repository for non-aggregate-root (except maybe that one could then potentially use that repository so that transactional boundaries are no longer met)

A:

If ChainOfClassesA is an aggregate Root and it has a collection of ClassA. If you need a usecase to update ClassA, you define a method on ChainOfClassesA object. I don't see any reason ClassA to have reference to ChainOfClassesA because any way it can only be used in scope of ChainOfClassesA. If EF allows you to do this, it not necessary means you should do it. If you define a repo per ClassA it means it can leave totally separate with its own lifecycle. And all other aggregates are eventually consistent with it. If you remove ChainOfClassesA, does ClassA should continue to live? If yes, Then ClassA should probably be a separate aggregate.


Q:

XML As XMLNode in Actionscript/Flex

How do I get the root node of an XML object in Actionscript?
One would think that I could say this:
var Node:XMLNode = XMLVar as XMLNode;

But although XMLVar is of type XML, Node will = null.
So how do I do it?

A:

var node:XMLNode = xmlVar as XMLNode;

although xmlVar is of type XML

XML and XMLNode are not compatible in ActionScript-3. XML class of AS2 (and its related classes) has been renamed to flash.xml.XMLDocument in AS3.

The XMLNode/XMLDocument class represents the legacy XML object that was present in ActionScript 2.0 and that was renamed in ActionScript 3.0. In ActionScript 3.0, consider using the new top-level XML class and related classes instead, which support E4X (ECMAScript for XML). The XMLNode/XMLDocument class is present for backward compatibility.

An object of type XML cannot be cast directly to XMLNode. Since you're trying to cast with as keyword, it just returns null instead of raising an alarm saying the cast failed.

And as already mentioned, consider using lowerCase names for variables, as UpperCase names are normally used for naming classes.


Q:

¿"han [...] para que haya"... es correcto?

Vivo en Argentina y se me presentó el siguiente ejemplo:

Se le han dado clases de ciudadanía para que haya amado al país.

¿Es correcto pensar que está mal por el hecho de que los dos verbos ocurren en el mismo tiempo (pretérito)?
¿Seria mejor la siguiente versión o está siquiera permitida?

Se le han dado clases de ciudadanía para que ame al país.

A:

Tienes de opciones en este caso:

para que amara/se
Úsase el pretérito imperfecto del subjuntivo para indicar que
las clases no se las seguirán dando (ya tomó todas las clases)
para que ame
Empléase el presente del subjuntivo para mantener abierta la posibilidad de que haya más clases en el futuro (todavía está tomando las clases)

No creo que sea posible usar los tiempos compuestos después de para que, ya que usamos para que para hablar de acciones venideras o coetáneas.  Es por eso que tampoco sería común (si no completamente incorrecto) decir algo del tipo Trabajo para que fuese …, ya que es imposible en el presente ejercer influencia –por medio de la acción de trabajar– sobre el pasado.


Q:

How do I deploy applications in run as administrator mode?

How Do I deploy applications so that they require administrator rights without the end-user doing that by hand?
I use Delphi 2009 to build the application.

A:

You can inform Windows that your application needs to run as an administrator by using the requestedExecutionLevel element in your application manifest.
The manifest file is an XML file that looks as follows. It should be named YourApp.exe.manifest and placed in the same folder as the executable. (It can also be embedded in the resources of your application; it must have a resource type of RT_MANIFEST and an ID of 1.)
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="YourApp" type="win32"/>
  <description>Description of your application</description>
  <!-- Identify the application security requirements. -->
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
      </requestedPrivileges>
    </security>
  </trustInfo>
</assembly>

For further details on application manifests and how to create them, see Create and Embed an Application Manifest (UAC) at MSDN.
Note that the manifest is only respected by Windows Vista and later. If your user is running as a standard user on Windows XP, your application will not be launched as an administrator; you may need to write code to detect this if it will be a problem for your application.


Q:

Php Mysql select query issue and regexp

in fact im working on a small php script !
I'm using thi code
mysql_query("SELECT * FROM matieres WHERE Niveaux REGEXP ',?[8],?' AND Filieres REGEXP ',?[5],?'");

The records on rows niveaux and filiere are like this 1,2,3,4,5,6,7,8,9
the problem is that this query give me all rows Niveaux which contain 8 But it doesnt give me rows which contain fillieres 5. How can i solve it ?

A:

Please try this:
mysql_query("SELECT * FROM matieres WHERE Niveaux REGEXP ',8,' AND Filieres REGEXP ',5,'");


Q:

Pass the data from CPU to GPU without explicitly passing it as a parameter

Is it possible to pass the data from CPU to GPU without explicitly passing it as a parameter?
I don't want to pass it as a parameter primarily for syntax sugar reasons - I have about 20 constant parameters I need to pass, and also because I successively invoke two kernels with (almost) same parameters.
I want something along the lines of
__constant__ int* blah;

__global__ myKernel(...){
    ... i want to use blah inside ...
}

int main(){
    ...
    cudaMalloc(...allocate blah...)
    cudaMemcpy(copy my array from CPU to blah)

}

A:

cudaMemcpyToSymbol seems to be the function you're looking for. It works similarly to cudaMemcpy, but with an additional 'offset' argument which looks like it'll make it easier to copy across 2D arrays.
(I'm hesitant to provide code, since I'm unable to test it - but see this thread and this post for reference.)


Q:

Wordpress Options-Theme STD (default) value does not work

I'm using Wordpress Options Theme and I'm getting an issue.
Here's the code:
$options[] = array( "name" => __('Texto de botón de enlace a cotización',THEMENAME),
                    "desc" => __('Inserta el texto que aparecerá en los botones de cotización',THEMENAME),
                    "id" => "ns_custom_caps_quote_btn",
                    "std" => __('Cotizar', THEMENAME),
                    "type" => "text");

And when I reset to default, the input returns "a" instead of "Cotizar".
Any suggestion?
Thanks in advance.

A:

Values set in the 'std' key of the array,
'std' => 'your default value'

Are saved to the database on first initialization of the framework.
Once you overwrite the default value and or remove the default value, even if left as a blank field, the default no longer applies unless you hit the "restore defaults" button.


Q:

CakePHP SignBox Component

I'm trying to implement a simple login box to my web application, just a regular username and password field if no session is detected and a welcome message if there is one, i started with the following:

I thought a simple element will do the job, but i realized than i can't include css or js(not inline) from an element because the $scripts_for_layout would be already sent to the output buffer.
I'm now thinking of implementing it as a component, not sure if this would be the right architecture(is it?) but i can definitely add the js/css and output them in the head tag from there. The question is now where should i place the markup for the login box, an element or view maybe, and how do i inject them to the view? a simple $this->set('x', htmlmarkup) in the component and another echo in the view. What's right way to do it.

Thanks.
Yehia

A:

An element is definitely what you need as it is a front-end element that is reused on several pages.
To get around the issue of not being able to include CSS or JS from an element you could create separate CSS and JS files for the login box and include them in the layout.


Q:

Java Swing application won't quit after recieving TERM signal

I have a Java Swing application that is being used as a cluster application. The problem is that every time the cluster tries to terminate the Java application, it just hangs and Windows displays the "End Now" dialog. The said application is a server type one so it spawns a thread for every attempt to connect to it is made.
I learned that the cluster sends the TERM signal using the program presented in this article. BUT when the console application is used as a cluster application, the cluster can just terminate the process after a few TERM signals.
I also tried the vanilla sample desktop application that's available when making a new project using NetBeans 6.8. It also won't terminate even after receiving the signal.
From the demonstrations done above, I think that it has something to do with Swing or with the threads. Can anyone help me with this? Thank you.
EDIT: It could be killed by using the task manager though I think it sends another signal.

A:

When your Java application receives the TERM signal it will run any registered shut-down hooks before terminating.  One possibility is that one of these shut-down hooks is blocking indefinitely or else taking a long time (>30 seconds) to run, causing the Windows "End Now" dialog to be displayed.
One thing you could try is to register a shut-down hook that simply prints to the console and verify that it is indeed being called.  However, unfortunately there'll be no way to determine whether other shut-down hooks have run at this point as hooks are run in an arbitrary order.


Q:

Zend Framework Logger : Zend DB Logger

I am using Zend logger as following :-
$columnMapping = array('message' => 'message', 'created_at' => 'timestamp');
$writer = new Zend_Log_Writer_Db($dbAdapater, 'log', $columnMapping);
$logger = new Zend_Log($writer);
$logger->info('Sample log data');

Now if I want to bind more fields which are not defined as default (as we can see in $columnMapping array), e.g. user_name, user_type etc, then what should I do?
To be simple I want to achieve following:-
$columnMapping = array('user_defined_field1' => 'user_defined_val_1');
$writer = new Zend_Log_Writer_Db($dbAdapater, 'log', $columnMapping);
$logger = new Zend_Log($writer);
$logger->info('Sample log data');

Please suggest.

A:

Logger definition:
$columnMapping = array(
    'message' => 'message',
    'user_defined_field1' => 'user_defined_field1');
$writer = new Zend_Log_Writer_Db($dbAdapater, 'log', $columnMapping);
$logger = new Zend_Log($writer);

When 'user_defined_val1' data is available, call setEventItem() function:
$logger->setEventItem('user_defined_field1', 'user_defined_val1');
$logger->info('Sample log data');

More detail:
http://framework.zend.com/manual/en/zend.log.overview.html - Understanding Log events


Q:

Check if database exist

How do I check if a database exists in bash?
I'm planning to make an automated backup script, where each website's db name is:
(siteName) mysite.com  = mysite_com (dbName)

A:

You can check if a file exists with the -e bash command. MongoDB creates a Namespace file for each database, so search for those. Something like
if [ -e /data/db/$DBNAME.ns ]; then
  `mongodump -d $DBNAME --out /backup/directory`
fi

Assuming your data is stored in /data/db
Have a look at the mongodump command which can be used to backup data from your mongo db instance
http://www.mongodb.org/display/DOCS/Backups


Q:

AS3 : yet another 1009 error: where's that null object

I've got 1009 error, but I can't find that null object. Can someone point it out to me?

[Fault] exception, information=TypeError: Error #1009: Cannot access a
  property or method of a null object reference.
[Fault] exception, information=TypeError: Error #1009: Cannot access a
  property or method
  of a null object reference. at
  Square/draw()[/Users/si/Dropbox/ac3/square/src/Square.as:21] at
  Start/drawSquare()[/Users/si/Dropbox/ac3/square/src/Start.as:35] at
  starling.events::EventDispatcher/invokeEvent()[/Users/redge/Dropbox/Development/starling/starling/src/starling/events/EventDispatcher.as:146]
  at
  starling.events::EventDispatcher/dispatchEvent()[/Users/redge/Dropbox/Development/starling/starling/src/starling/events/EventDispatcher.as:117]
  at
  starling.display::DisplayObject/dispatchEvent()[/Users/redge/Dropbox/Development/starling/starling/src/starling/display/DisplayObject.as:398]
  at
  starling.display::DisplayObjectContainer/broadcastEvent()[/Users/redge/Dropbox/Development/starling/starling/src/starling/display/DisplayObjectContainer.as:379]
  at
  starling.display::DisplayObjectContainer/broadcastEventWith()[/Users/redge/Dropbox/Development/starling/starling/src/starling/display/DisplayObjectContainer.as:389]
  at
  starling.display::DisplayObjectContainer/addChildAt()[/Users/redge/Dropbox/Development/starling/starling/src/starling/display/DisplayObjectContainer.as:135]
  at
  starling.core::Starling/initializeRoot()[/Users/redge/Dropbox/Development/starling/starling/src/starling/core/Starling.as:439]
  at
  starling.core::Starling/initialize()[/Users/redge/Dropbox/Development/starling/starling/src/starling/core/Starling.as:410]
  at
  starling.core::Starling/onContextCreated()[/Users/redge/Dropbox/Development/starling/starling/src/starling/core/Starling.as:649]

It's starling project it it matters.
Here's the code:
package {
   import starling.display.*;
   import com.greensock.TweenLite;
   import com.greensock.easing.Linear;

public class Square extends Sprite implements ISquare {

    public const square:Quad = new Quad(100, 100);
    private var direction:Boolean;
    private var stopped:Boolean;
    private var speed:int;

    public function Square() {
    }

    public function draw():void{
        addChild(square);
        square.color = 0x4500FF;
        direction = new Boolean(true);
        stopped = new Boolean(false);
        speed = new int(stage.stageHeight);
        trace("vars init complete");
        down();
    }

   ...

Here's the whole soure on dropbox: https://www.dropbox.com/sh/9x2q93o2ff1fsna/AADVJgt5nipDE1pdkgozkOc1a

A:

Okay, so, let's take a look at the relevant code...
Start class
//stuff omitted like imports
public class Start extends Sprite {

    public var viewport:Quad = new Quad(1,1);
    private var swipe:SwipeGesture;
    private var call:Square = new Square();

    public function Start() {
        super();

        addEventListener(Event.ADDED_TO_STAGE, drawSquare);
    }

    private function drawSquare(event:Event):void {
        removeEventListener(Event.ADDED_TO_STAGE, drawSquare);

        viewport.width = stage.stageWidth;
        viewport.height = stage.stageHeight;
        viewport.color = 0x414141;
        addChild(viewport);

        swipe = new SwipeGesture(viewport);
        swipe.addEventListener(GestureEvent.GESTURE_RECOGNIZED, onSwipe);

        trace("gesture listener added");
        call.draw();
    }
    //stuff omitted
}

Square class
//imports omitted
public class Square extends Sprite implements ISquare {

    public const square:Quad = new Quad(100, 100);
    private var direction:Boolean;
    private var stopped:Boolean;
    private var speed:int;

    public function Square() {
    }

    public function draw():void{
        addChild(square);
        square.color = 0x4500FF;
        direction = new Boolean(true);
        stopped = new Boolean(false);
        speed = new int(stage.stageHeight);
        trace("vars init complete");
        down();
    }
    //stuff omitted
}

When I manually read your code, I see that this is what happens:

Start.constructor adds eventlistener
eventListener triggers, start.drawSquare
adds viewport, does stuff with swipegesture...
draws square
Square.draw is called
Square adds a quad to itself
sets some colors and variables
direction to true
stopped to false
speed to stage.stageHeight

Wait, stage? stage has not been mentioned around Square yet. I think it's null. And in fact, when you look at the stack trace of the error, you can see this. It says it goes wrong at at Square/draw() in /Users/si/Dropbox/ac3/square/src/Square.as:21. And line 21 of Square.as is speed = new int(stage.stageHeight); This shows that one of the mentioned objects on that line is null or otherwise undefined. Via a process of elimination, we can see that speed has already been declared, and is being assigned to and is thus irrelevant; the int class is defined or the compiling would have gone wrong; and all we are left with is either stage being null or stage.stageHeight being undefined.
The documentation says Stage.stageHeight is an int. It's a property of stage, and since it's a primitive type, it's never null or otherwise undefined (not in actionscript, anyway). So that leaves us with stage: the call instance of Start has never been added to stage, thus stage is null, thus it nulls on
speed = new int(stage.stageHeight)
To fix this, either pass the draw function of Square a reference to stage... or, and this seems to be the better solution, given what you want to do, add call (that's the Square instance) to stage before drawing it.


Q:

Ways of getting high FPS for real time computer vision processing

My goal is to get as high FPS as possible. I will be happy with BW small frames, but FPS should be maximum.
getSupportedPreviewFpsRange on HTC WildFire S returns (9, 30). But when I try to draw preview image with most simple processing it visually get at about 12-15 FPS max.
After setting Parameters and startPreview() method call I do this:
camera.setPreviewCallback(new Camera.PreviewCallback() {
          @Override
          public void onPreviewFrame(byte[] bytes, Camera camera) {
            Bitmap bitmap = Bitmap.createBitmap(size.width, size.height, Bitmap.Config.ARGB_8888);
            int[] colors = new int[size.width * size.height];
            for (int i=0; i < colors.length; i++){
              colors[i] = getBWColor(bytes[i]);
            }
            bitmap.setPixels(colors, 0, size.width, 0, 0, size.width, size.height);
            secondView.setImageBitmap(bitmap);
          }
        });
      }

private static int getBWColor(byte b){
    int res = 255;
    for(int i=0;i<3;i++){
      res = (res << 8) + b;
    }
    return res;
  }

Is there way to get it as fast as possible? =(

A:

First, use setPreviewCallbackWithBuffer(), it reuses one buffer and does not have to allocate new buffer on every frame. Check my older answer, there is an example how to use it.
Than, do not do any expensive opeartion in onPreviewFrame(), the time of the data is limited, it is rewritten on each new frame. You should do the processing in another thread.
And of course do not create new bitmap a the colors array on each frame, do it just once.

A:

I don't really understand what you're doing, but I'd guess you're killing yourself in processing.
1) Do not create a new bitmap every time.  Reuse 1 bitmap.
2) Manipulate your bitmaps in C/C++ with the NDK.  Look at the "plasma" example.  Its MUCH faster than Java.  Not because its C++ really, but because the Java version of the API tends to transform the whole thing whenever you push in a data array for pixels.  In the C++ version, you can directly manipulate the pixel values.


Q:

Deploying applications to Web Logic production Server

I am here to get some expert advice on deploying applications to WebLogic Production Server.
Is it a best practice to use Admin Server Console for deploying and redeploying applications in production. Actually I am deploying to a cluster having two managed server instances.
I have encountered this issue while i am redeploying application in the production. When i am deleting existing .ear file and adding updated .ear file will put the updated .ear file into prepared state. I can not make it Active state using Admin Server Console. If i try it will through some exceptions. But after some time it automatically goes in to active state, but i don't know what is happening inside. Sometimes i restart the server to make it active. Could anybody explain me what is the procedure when deploying application and redeploying applications in weblogic
Thanks in advance for any Help...

A:

Generally WLST (WebLogic Scripting Tool) is used to deploy the applications. Administration Console can also be used to deploy/upgrade the applications but if there are many environments that need to be upgraded then WLST (which works like a command line tool) is much better option.
Get an overview of WLST to know how to use it to deploy/undeploy/upgrade  applications.


Q:

NullPointerException CustomList ViewAdapter with base adapter Android

I am trying to create a custom listview with one image and 3 textViews, but I am getting this NullPointException error a the line "listView.setAdapter(adapter);" of my code.
By debugging the app, I could see that my List produtos is getting all the necessary data from my SQLite database, so I do not believe the issue is there. I am setting a fix image by now, because this was my first test with customs listviews. So I was trying to make this works first, then I will implement the rest.
`    My activity which should implement the custom listview--
 public class ShowAllProdutosActivity extends ActionBarActivity {
 ListView listView;
 ArrayList<Produto> produtos;
 String[] titleArray;
 String[] descriptionArray;
 String[] priceArray;
 int[] imagensArray;
 CustomListViewAdapter adapter;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
     // TODO: Implement this method
     super.onCreate(savedInstanceState);
     setContentView(R.layout.listview_procura); /*Fixed*/
     getSupportActionBar().setDisplayHomeAsUpEnabled(true);
     produtos = new ArrayList<>();
     listView = (ListView) findViewById(R.id.listaProdutos);
     final DatabaseHelper db = new DatabaseHelper(this);
     produtos = db.getAllProdutos();
     db.closeDB();
     if (!produtos.isEmpty()) {
         adapter = new CustomListViewAdapter(this,produtos);
        listView.setAdapter(adapter);
     } else {
         Toast.makeText(this, "Nenhum Produto Encontrado", Toast.LENGTH_LONG);
     }
  }
}`

`    CustomListViewAdapter.java--
public class CustomListViewAdapter extends BaseAdapter {

Context context;

protected List<Produto> listProds;
LayoutInflater inflater;

public CustomListViewAdapter(Context context, List<Produto> listProds) {
    this.listProds = listProds;
    this.inflater = LayoutInflater.from(context);
    this.context = context;
}

public int getCount() {
    return listProds.size();
}

public Produto getItem(int position) {
    return listProds.get(position);
}

public long getItemId(int position) {
    return listProds.get(position).getId();
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    View row = convertView;
    if (row == null) {

        holder = new ViewHolder();
        row = this.inflater.inflate(R.layout.listview_item,
                parent, false);

        holder.txtName = (TextView) row
                .findViewById(R.id.txtViewNomeProduto);
        holder.txtDesc = (TextView) row
                .findViewById(R.id.txtViewDescricaoProduto);
        holder.txtPrice = (TextView) row
                .findViewById(R.id.txtViewPrecoProduto);
        holder.imgProd = (ImageView) row
                .findViewById(R.id.produtoImgView);

        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }

    Produto prod = listProds.get(position);
    holder.txtName.setText(prod.getProd_name());
    holder.txtDesc.setText(prod.getProd_desc());
    holder.txtPrice.setText(prod.getProd_price() + " R$");
    holder.imgProd.setImageResource(R.mipmap.ic_launcher);

    return convertView;
}

private class ViewHolder {
    TextView txtName;
    TextView txtDesc;
    TextView txtPrice;
    ImageView imgProd;
}

    My activity layout listview_procura.xml--
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/listaProdutos"
    android:layout_alignParentTop="true" />
 </RelativeLayout>

    My item layout listview_item.xml--
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">

<ImageView
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:id="@+id/produtoImgView" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:id="@+id/txtViewNomeProduto"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/produtoImgView"
    android:layout_toEndOf="@+id/produtoImgView" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="Small Text"
    android:id="@+id/txtViewDescricaoProduto"
    android:layout_toRightOf="@+id/produtoImgView"
    android:layout_below="@+id/txtViewNomeProduto"
    android:layout_above="@+id/txtViewPrecoProduto"
    android:layout_toLeftOf="@+id/txtViewPrecoProduto"
    android:layout_toStartOf="@+id/txtViewPrecoProduto" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Large Text"
    android:id="@+id/txtViewPrecoProduto"
    android:layout_alignBottom="@+id/produtoImgView"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />
 </RelativeLayout>

    And the log I am getting--
04-12 20:36:30.533  28463-28463/com.paum.pechinchamercado E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.paum.pechinchamercado, PID: 28463
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.paum.pechinchamercado/com.paum.pechinchamercado.activities.ShowAllProdutosActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
        at android.app.ActivityThread.access$900(ActivityThread.java:161)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5356)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.paum.pechinchamercado.activities.ShowAllProdutosActivity.onCreate(ShowAllProdutosActivity.java:50)
        at android.app.Activity.performCreate(Activity.java:5426)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
        at android.app.ActivityThread.access$900(ActivityThread.java:161)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5356)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
        at dalvik.system.NativeStart.main(Native Method)

`

A:

You are setting your content view to R.layout.add_prod but you claim the layout is called listview_procura.xml.  If you are setting the content view to the wrong layout then calling findViewById() to get the ListView will return null if you don't have a ListView with that same id in add_prod.xml


Q:

Formatting of dataframe index and columns using styler

I am quite new with html and the pandas dataframe styler, but here is my problem:
I wrote the following code
import pandas as pd

df = pd.DataFrame([1000000.0, 1000000.0], index=pd.bdate_range('2017-08-01', '2017-08-02'))

styler = df.style
styler = styler.format("{:,.0f}")
styler = styler.set_properties(**{'width': '100px', 'text-align': 'right'})

Which yield the following

I understand how to format the various elements of the dataframe I am working with. However, I would like to format my index and column title. In particular, i would like to format my index as a date without the time, and I would like to align my column name to the right, like I did with my values. More specifically, is there an efficient to access the index and columns in the pandas styler.

A:

You could try something like this, see table styles:
import pandas as pd

df = pd.DataFrame([1000000.0, 1000000.0], index=pd.bdate_range('2017-08-01', '2017-08-02'))

df.index = df.index.strftime("%Y-%m-%d")
styler = df.style
styler = styler.format("{:,.0f}")
styler = styler.set_properties(**{'width': '100px', 'text-align': 'right'})

styler.set_table_styles(
# select the table header with th and set it right align
    [dict(selector="th", props=[("text-align", "right")])]
)


Q:

What container should I use for the game objects that are created and deleted frequently?

I am doing a game where I create objects and kill them frequently. I must be able to loop the list of objects linearly, in a way that the next object is always newer than previous, so the rendering of the objects will be correct (they will overlap). I also need to be able to store the pointers of each object into a quadtree, to quickly find nearby objects.
My first thought was to use std::list, but I have never done anything like this before, so I am looking for experts thoughts about this.
What container should I use?
Edit: I am not just deleting from the front: the objects can be killed at any order, but they are always added in the end of the list, so last item is newest.

A:

std::vector is the recommended container to start with when you're not sure what you're doing. Only when you know that's not going to work for you should you choose something else.
That said, if you're regularly adding to the back of the container and deleting from the front, you probably want std::deque.  [Edit] But it appears that's not what you're doing.
I'm thinking you might want two containers, one to maintain the insert order and one for your quadtree.  There are lots of quadtree implementations on the Internet, so I'll focus on the other one.  Using std::list as you suggest will make the delete operation itself faster than vector or deque.  It also has the advantage of letting you store iterators, because list won't invalidate the other iterators when an element is removed.  Your objects in the quadtree could maintain an iterator into the insert order list.  When you remove an element from the quadtree, you can remove it from the list too in O(1) time.
As always, the decision about which container to use is all about tradeoffs.  A list comes with increased memory footprint over vector and the loss of contiguous memory layout.  You might be surprised how much cache locality matters when your data set is large.  The only way to know for sure is to try various containers and see which one runs the best for your application.


Q:

How to get Select2 tags initializing correctly with Angular UI when option groups are used?

I have been trying to get my angular ui select2 directive to initialize and have been unable to get it to work with option groups.
The Code:
function testCtrl1($scope)
{
    $scope.selectedOptions = ['1'];
    $scope.categories = [
            {label: 'cat1', options: [{desc: 'one', value: 1}]},
            {label: 'cat2', options: [{desc: 'two', value: 2}]}
    ];
}

The HTML:
<select multiple ui-select2 ng-model="selectedOptions" style="width: 300px">
    <optgroup ng-repeat="category in categories" label="{{category.label}}">
      <option ng-repeat="option in category.options" value="{{option.value}}">{{option.desc}} - {{option.value}}</option>
    </optgroup>
</select>

The Fiddle:
I created the following jsfiddle.
While doing so I notice that it would initialize correctly if I included a second select2 directive that didn't include the option groups (weird). I notice some other odd behavior when including the second select2 but I am not too concerned about it since my goal is just to get testCtrl1 working.

A:

Download latest angular-ui select2 and update line 24:
repeatOption = tElm.find( 'optgroup[ng-repeat], optgroup[data-ng-repeat], option[ng-repeat], option[data-ng-repeat]' );

Now its supports option groups.

A:

Well i've gotten to the same obstacle and want to share my solution. Select2 was not watching the optgroup ng-repeat attribute. You have to add this to your angular ui select2 directive.
Change this:
repeatOption = tElm.find('option[ng-repeat], option[data-ng-repeat]');

To that:
repeatOption = tElm.find('optgroup[ng-repeat], optgroup[data-ng-repeat], option[ng-repeat], option[data-ng-repeat]');

Not sure if this is a clean solution but it works for me.
Github issue


Q:

Why doesn't iTunes detect my iPhone?

When I connect my iPhone 3GS to my computer, iTunes does not detect it. The phone displays the green battery meter indicating it's charging, System Profiler detects an "iPhone" connected to the USB bus, and I can even open iPhoto and pull some pictures off of it.
It doesn't appear under "Devices" in iTunes at all, nor does it appear in the Organizer window in Xcode.
I've tried:

Using a different sync cable.
Using a different USB port.
Restarting the phone.
Restarting the computer.
Connecting the phone to a different computer.

(I'm on OS X 10.6.6 and iTunes 10.1.2)

A:

Run Activity Monitor (Applications/Utilities);  do you see the iTunes Helper service running?  Make sure you set the view to "All processes", not "My Processes".  If it's not running, that's your problem.  Re-install iTunes and away you go.

A:

I had this problem on Lion, which doesn't allow the deletion of iTunes through the UI. Therefore, it was necessary to force the uninstall of iTunes from Terminal:

cd /Applications
sudo rm -r iTunes.app

I then pulled down the latest iTunes installer from Apple.
All my iTunes settings were maintained and my iPhone and iPad showed up again under devices.


Q:

Using math to hit exact spice level

This is a question that will combine your knowledge of food, chemistry, and beer.
Spiciness is measured in Scoville Units. Basically:

In Scoville's method, an alcohol
  extract of the capsaicin oil from a
  measured amount of dried pepper is
  added incrementally to a solution of
  sugar in water until the "heat" is
  just detectable by a panel of (usually
  five) tasters; the degree of dilution
  gives its measure on the Scoville
  scale. Thus a sweet pepper or a bell
  pepper, containing no capsaicin at
  all, has a Scoville rating of zero,
  meaning no heat detectable. The
  hottest chilis, such as habaneros and
  nagas, have a rating of 200,000 or
  more, indicating that their extract
  must be diluted over 200,000 times
  before the capsaicin presence is
  undetectable. The greatest weakness of
  the Scoville Organoleptic Test is its
  imprecision, because it relies on
  human subjectivity. Tasters taste only
  one sample per session.one sample per session.

I'm making a chili beer, and while I have an idea of what I want to do, I thought some math could come in handy. How would you take the Scoville units of, say, a habanero (200,000 units), and the volume of a batch (5 gallons), and figure out how much habanero to add to get the final beer to, say, 75,000 Scoville units?

A:

According to this professor at UNC, they make the extract with one pepper.  For the calculation I'll assume that your beer can extract capsaicin from the pepper you use as efficiently as the lab extract (which is most likely not true, but it gives you a base to start from).
This calculation is just a shot in the dark, but it makes sense to me:
First, 1 habanero (seeds and all) is approximately 1 teaspoon of ground habanero powder accourding to this spice company (we have to get a volume measurement before we do anything), so I will assume that 1 teaspoon of powder is about equal to the actual pepper on the Scoville scale (200,000 in your case).
5 gallons of beer is 3,840 teaspoons, so would dilute 1 habanero to about 196,160 Scoville units.
That way overshoots your target of 75,000, so lets try it with half a habanero (about 100,000 Scoville units).
5 gallons of beer is 7,680 half-teaspoons, so would dilute 1 habanero to about 92,320 Scoville units.  This gets pretty close to your target of 75,000, and since the heat of your exact pepper is unknown, I would say it's a pretty good approximation.
Maybe that 92,320 will get down in the 70,000-80,000 target range when you account for the capsaicin that you can't extract.
I'm, not sure how you were planning on incorporating it, but I would slice it half-wise vertically to accurately get half of the pepper, then crush the half you want to use with a mortar and pestle and stir the habanero paste in.


Q:

how to add the binaries and other files to rootfs in yocto using .bb recipes

DESCRIPTION = "Copies hello-binaries to the image"
LICENSE = "CLOSED"
FILESEXTRAPATHS_prepend := "${THISDIR}:"
SRC_URI += "file://hello "
S = "${WORKDIR}"
do_install() {
    install -d ${D}${bindir}
    install -m 0777 hello ${D}${bindir}
    }
#FILES_${PN} += "${bindir}"
INSANE_SKIP_${PN} = "ldflags"
INSANE_SKIP_${PN}-dev = "ldflags"

In the above recipe i commented the line FILES_ then also the hello binary is adding to the image how is it possible? I have no idea how the recipe is copying binaries to image.*

A:

FILES_${PN} has a default value that includes among other things "${bindir}/*". So appending to the value in the recipe isn't needed.
You can see the default value in meta/conf/bitbake.conf and check what the value ends up as with bitbake -e <hellorecipe> | grep ^FILES_


Q:

Elasticsearch 2.4 - Combining Date Range Filter with Date Histogram

I have query :
{
  "size": 0,
 "aggs": {
   "data_bulanan" : {
    "date_histogram" : {
        "field" : "creation_date",
        "interval" : "month",
        "format": "MMMM"
        },
        "aggs": {
          "SvcCharge" : {
              "sum": {
              "field": "service_tax"
              }
          },
          "GvtTax" : {
              "sum": {
              "field": "government_tax"
              }
          },
          "Discount" : {
             "sum" : {
             "field": "discount"
              }
          }

        }
    }
  }
}

And i want to add the date range from date to date . for example from 2014-01-01 to 2015-01-01 .
How to add it?
thank you

A:

If you'd like to limit the resultset to the specified dates above, you need to combine a query to your aggregation, you can do it like so
{
  "size": 0,
  "query": {
      "bool": {
          "filter": {
              "range": {
                  "creation_date": {
                      "gte": "2014-01-01",
                      "lte": "2015-01-01"
                  }
              }
          }
      }
  },
  "aggs": {
    "data_bulanan": {
      "date_histogram": {
        "field": "creation_date",
        "interval": "month",
        "format": "MMMM"
      },
      "aggs": {
        "SvcCharge": {
          "sum": {
            "field": "service_tax"
          }
        },
        "GvtTax": {
          "sum": {
            "field": "government_tax"
          }
        },
        "Discount": {
          "sum": {
            "field": "discount"
          }
        }
      }
    }
  }
}


Q:

Laplace transform on a Boundary value problem (ODE)with . Am i attempting correctly?

From a system of PDEs where i used the following ansatz: $$\theta_w(x,y) = e^{-\beta_h x} f(x) e^{-\beta_c y} g(y)$$.  $F(x) := \int f(x) \, \mathrm{d}x$ and $G(y) := \int g(y) \, \mathrm{d}y$
So, $$\theta_w(x,y) = e^{-\beta_h x} F'(x) e^{-\beta_c y} G'(y)$$
I have the following two third order linear ODEs which have been arrived at after applying separation of variables
\begin{eqnarray}
 \lambda_h F''' - 2 \lambda_h \beta_h F'' + \left( (\lambda_h \beta_h - 1) \beta_h - \mu \right) F' + \beta_h^2 F &=& 0,\\
 V \lambda_c G''' - 2 V \lambda_c \beta_c G'' + \left( (\lambda_c \beta_c - 1) V \beta_c + \mu \right) G' + V \beta_c^2 G &=& 0,
\end{eqnarray}
$F$ is $F(x)$ and $G$ is $G(y)$. The boundary conditions are
For $F$:
$$F(0)=0$$
$$\frac{F''(0)}{F'(0)}=\beta_h$$
$$\frac{F''(1)}{F'(1)}=\beta_h$$
$\lambda_h$, $\beta_h$ and $V$ are constants $>0$, while $\mu$ is the constant of separation.
I decided to apply the Laplace transform to each ODE and find the functions $F$ and $G$ individually finally obtaining $\theta_w$.
Applying Laplace transform
($\bar F$ is $\mathcal{L}F(x)$)
$$\lambda_h F''' - 2 \lambda_h \beta_h F'' + \left( (\lambda_h \beta_h - 1) \beta_h - \mu \right) F' + \beta_h^2=0$$
Taking constants before each term as $a$, $b$, $c$ and $d$ makes $a=\lambda_h$, $b=-2\lambda_h\beta_h$, $c=(\lambda_h\beta_h-1)\beta_h-\mu$ and $d={\beta_h}^2$, we have
$$a[s^3\bar F(s)-s^2 F(0)-sF'(0)-F''(0)]+b[s^2\bar F(s)-sF(0)-F'(0)]+c[s\bar F(s)-F(0)]+d[\bar F(s)]=0$$
I know that the seperation constant $\mu$ is contained in $c$ and is not a known quantity and can attain values $<,=,>0$. Ultimately after applying the first 2 b.c. i arrive at:
$$\bar F(s)[as^3+bs^2+cs+d]=F'(0)[s+b+a\beta_h]$$
I cannot proceed from here, as $F'(0)$ is not known. Also i have doubts whether my approach here to solve two variable separated ODEs with a separation constant using Laplace transform is correct in the first place or not ?

A:

I don't believe that the Laplace-transform approach will work well here, since not all conditions are given at the same point.
In general, the homogeneous third-order linear ODE with constant coefficients $a y''' + b y'' + c y' + d y = 0$ has four types of solutions, depending on the zeros of the characteristic polynomial $P(\lambda) = a \lambda^3 + b \lambda^2 + c \lambda + d$.
Such a cubic function has always one real zero, and the first distinction happens according to whether the other two zeros are real or complex.

If all zeros are real, then the solution takes one of the forms
\begin{equation}
y = C_1 e^{\lambda_1 x} + C_2 e^{\lambda_2 x} + C_3 e^{\lambda_3 x}, \quad y = (C_1 + C_2 x) e^{\lambda_1 x} + C_3 e^{\lambda_3 x}, \quad y = (C_1 + C_2 x + C_3 x^2) e^{\lambda_1 x},
\end{equation}
depending on the multiplicity of the zeros.
If only one zero is real then the solution will be of the form
\begin{equation}
y = C_1 e^{\lambda_1 x} + e^{-b_1 x} \left( C_2 \cos(b_2 x) + C_3 \sin(b_2 x) \right).
\end{equation}

You could verify these solutions and then perhaps you could exclude some types using the given conditions. The configuration of the zeros of the characteristic polynomial $P$ will depend on the value of your separation constant, and you can distinguish these cases according to a discriminant similar as in the quadratic case (https://en.wikipedia.org/wiki/Cubic_function#The_discriminant), it's just more work!
Finally, this distinction should not be made according to the sign of the separation constant $\mu$ but rather according to the sign of the discriminant of the characteristic polynomial $P$, which depends on $\mu$.