问:
Mutually referential Prolog rules in family tree
I've seen various implementations of family trees in Prolog, but I haven't found one that does what I would like to do, which is to define child and parent by referring to each other.
I want to do this because sometimes I have a fact that someone is a child of someone, at other times I have the fact that someone is the parent of someone. From either of these kinds of facts, I'd like to be able to ask who are parents and who are children.

My attempt at coding this is :-

```<code>parent(mary, fred).
child(john, peter).
child(paul, peter).

parent(P, C).
parent(P, C) :- child(C, P).
child (C, P).
child(C, P) :- parent(P, C).
</code>```

This seems to work ok except that it will continue to give me the same results duplicated over and over. Eg :-

```<code>[3]  ?- parent(peter, X).
true ;
X = john ;
X = paul ;
true ;
X = john ;
X = paul ;
true
</code>```

Is there a way I can get it to stop after it has given me the full set of results once ?

More generally, is this kind of definition a weird thing to want to do (because of the mutual recursion) ? I want to be able to have facts of either parent or child, as reported, but also to infer the "opposite" relationship from these.

Thanks !

答:
The issue with your program is that you are merging predicates.
parent/2 and child/2 are facts, you should not name a rule like a fact that is already defined in your program.

Rename the rules and all will work. Also, the base clause in your rules should add a condition, that match the fact, something like this:

```<code>parent(mary, fred).
child(john, peter).
child(paul, peter).

isparent(P, C):- parent(P, C).
isparent(P, C):- child(C, P).

ischild(C, P):- child(C, P).
ischild(C, P) :- parent(P, C).
</code>```

Now the query:

```<code>?- isparent(peter, X).
X = john
X = paul
</code>```

Also, don't use the complement rule in your condition, that's not necessary and will avoid you the recursion

Body:
I've seen various implementations of family trees in Prolog, but I haven't found one that does what I would like to do, which is to define child and parent by referring to each other.
I want to do this because sometimes I have a fact that someone is a child of someone, at other times I have the fact that someone is the parent of someone. From either of these kinds of facts, I'd like to be able to ask who are parents and who are children.

My attempt at coding this is :-

parent(mary, fred).
child(john, peter).
child(paul, peter).

parent(P, C).
parent(P, C) :- child(C, P).
child (C, P).
child(C, P) :- parent(P, C).

This seems to work ok except that it will continue to give me the same results duplicated over and over. Eg :-

[3]  ?- parent(peter, X).
true ;
X = john ;
X = paul ;
true ;
X = john ;
X = paul ;
true

Is there a way I can get it to stop after it has given me the full set of results once ?

More generally, is this kind of definition a weird thing to want to do (because of the mutual recursion) ? I want to be able to have facts of either parent or child, as reported, but also to infer the "opposite" relationship from these.

Thanks !

Body:
The issue with your program is that you are merging predicates.
parent/2 and child/2 are facts, you should not name a rule like a fact that is already defined in your program.

Rename the rules and all will work. Also, the base clause in your rules should add a condition, that match the fact, something like this:

parent(mary, fred).
child(john, peter).
child(paul, peter).

isparent(P, C):- parent(P, C).
isparent(P, C):- child(C, P).

ischild(C, P):- child(C, P).
ischild(C, P) :- parent(P, C).

Now the query:

?- isparent(peter, X).
X = john
X = paul

Also, don't use the complement rule in your condition, that's not necessary and will avoid you the recursion


来源: stackexchange

问:
Unfortunately, your computer does not support hardware accelerated virtualization. in ubundu 14.04
Unfortunately, your computer does not support hardware accelerated virtualization.
Here are some of your options:
 1) Use a physical device for testing
 2) Develop on a Windows/OSX computer with an Intel processor that supports VT-x and NX
 3) Develop on a Linux computer that supports VT-x or SVM
 4) Use an Android Virtual Device based on an ARM system image
   (This is 10x slower than hardware accelerated virtualization)</p>

答: Either your device has HAXM turned off in the BIOS, or the CPU doesn't support HAXM.  In the first case, go into BIOS and turn it on.  In the second, you can't use the emulator and have to use the much, much slower emulator (I suggest sing a real device rather than that, that's how slow it is).</p>

ContentLicense: CC BY-SA 3.0


问:
unable to locate visual studio installer
When I trying to open visual studio installer in visual studio 2017 an error message is displayed: can't locate visual studio installer. It might be because I deleted it by mistake. I tried to look for the download of visual studio installer  and did not find it. I must delete complitly visual studio 2017 from my drive as fast as it possible.

答: Run the installer again. You don't have to uninstall first. I had the same problem when updating to v15.2 today.</p>


问:
x3 linker error with separate TU
As my parser grows I separated some rules into different translation units (TU) and the linker problem rises. After weeks of several try&errors without success I reduced my ~50 rules to the (hopefully) minimal example presented here. I've read the related linking errors while separate parser using boost spirit x3 and checked, that I use at the context typedef iso8859_1::space_type and that I invoke iso8859_1::space later on. Also I don't let the compiler deduce the iterator_type.

The linker error I made more fancy by replacing some things:

```<code>In function `bool x3::rule<parser::string_literal_class, ast::string_literal, false>::parse<std::string::const_iterator, x3::context<x3::error_handler_tag, std::reference_wrapper<x3::error_handler<std::string::const_iterator > > const, x3::context<x3::skipper_tag, x3::char_class<char_encoding::iso8859_1, x3::space_tag> const, x3::unused_type> >, x3::variant<ast::string_literal> >(std::string::const_iterator&, std::string::const_iterator const&, x3::context<x3::error_handler_tag, std::reference_wrapper<x3::error_handler<std::string::const_iterator > > const, x3::context<x3::skipper_tag, x3::char_class<char_encoding::iso8859_1, x3::space_tag> const, x3::unused_type> > const&, x3::unused_type, x3::variant<ast::string_literal>&) const':

main.cpp: .text._ZNK5boost6spirit2x34ruleIN6parser20string_literal_classEN3ast14string_literalELb0EE5parseIN9__gnu_cxx17__normal_iteratorIPKcNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEENS1_7contextINS1_17error_handler_tagEKSt17reference_wrapperINS1_13error_handlerISJ_EEENSK_INS1_11skipper_tagEKNS1_10char_classINS0_13char_encoding9iso8859_1ENS1_9space_tagEEENS1_11unused_typeEEEEENS1_7variantIJS6_EEEEEbRT_RKS13_RKT0_SY_RT1_[_ZNK5boost6spirit2x34ruleIN6parser20string_literal_classEN3ast14string_literalELb0EE5parseIN9__gnu_cxx17__normal_iteratorIPKcNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEENS1_7contextINS1_17error_handler_tagEKSt17reference_wrapperINS1_13error_handlerISJ_EEENSK_INS1_11skipper_tagEKNS1_10char_classINS0_13char_encoding9iso8859_1ENS1_9space_tagEEENS1_11unused_typeEEEEENS1_7variantIJS6_EEEEEbRT_RKS13_RKT0_SY_RT1_]+0x37): undefined reference to `bool parser::parse_rule<std::string::const_iterator, x3::context<x3::error_handler_tag, std::reference_wrapper<x3::error_handler<std::string::const_iterator > > const, x3::context<x3::skipper_tag, x3::char_class<char_encoding::iso8859_1, x3::space_tag> const, x3::unused_type> >, x3::variant<ast::string_literal> >(x3::rule<parser::string_literal_class, ast::string_literal, false>, std::string::const_iterator&, std::string::const_iterator const&, x3::context<x3::error_handler_tag, std::reference_wrapper<x3::error_handler<std::string::const_iterator > > const, x3::context<x3::skipper_tag, x3::char_class<char_encoding::iso8859_1, x3::space_tag> const, x3::unused_type> > const&, x3::variant<ast::string_literal>&)'
</code>```

I'm irritated by the __gnu_cxx17 iterator (from libstdc++??). I did try g++7.1.0 with the same result.

Attached the files to reproduce the linker error using a CMake file (with option LINKER_ERROR to get or even not (monolitic build without TU)).

ast.hpp

```<code>#ifndef AST_HPP_
#define AST_HPP_

#include <boost/spirit/home/x3/support/ast/variant.hpp>
#include <string>

#include <boost/fusion/include/adapt_struct.hpp>

namespace ast {
    namespace x3 = boost::spirit::x3;

    struct string_literal {
        std::string literal;
    };

    using primary = x3::variant<string_literal>;
    using factor = x3::variant<primary>;
}

BOOST_FUSION_ADAPT_STRUCT(ast::string_literal,
    literal
)

#endif // AST_HPP_
</code>```

grammar_def.hpp

```<code>#include "ast.hpp"
#include <boost/spirit/home/x3.hpp>
#if defined(LINKER_ERROR)
#include "literal.hpp"
#endif

namespace parser {

   namespace x3 = boost::spirit::x3;

    struct factor_class;
    struct primary_class;
#if !defined(LINKER_ERROR)
    struct string_literal_class;
#endif

    typedef x3::rule<factor_class, ast::factor> factor_type;
    typedef x3::rule<primary_class, ast::primary> primary_type;
#if !defined(LINKER_ERROR)
    typedef x3::rule<string_literal_class, ast::string_literal> string_literal_type;
#endif

    factor_type const factor{ "factor" };
    primary_type const primary{ "primary" };
#if !defined(LINKER_ERROR)
    string_literal_type const string_literal{ "string_literal" };
#endif

#if defined(LINKER_ERROR)
    namespace {
        auto const& string_literal = parser_api::string_literal();
    }
#endif

    auto const factor_def = primary;

    auto const primary_def = string_literal;

#if !defined(LINKER_ERROR)
    auto const string_literal_def =
        x3::lexeme ['"' >> *x3::char_ >> '"' ]
        ;
#endif

    BOOST_SPIRIT_DEFINE(factor, primary)
#if !defined(LINKER_ERROR)
    BOOST_SPIRIT_DEFINE(
            string_literal
    )
#endif
}
</code>```

literal_def.hpp

```<code>#ifndef PARSER_LITERAL_DEF_HPP_
#define PARSER_LITERAL_DEF_HPP_

#include "literal.hpp"

namespace parser {

    namespace x3 = boost::spirit::x3;

    string_literal_type const string_literal { "string_literal" };

    auto const string_literal_def =
        x3::lexeme ['"' >> *x3::char_ >> '"' ];

    BOOST_SPIRIT_DEFINE(
        string_literal
    )
}

namespace parser_api {
    parser::string_literal_type const& string_literal()
    {
        return parser::string_literal;
    }
}

#endif /* PARSER_LITERAL_DEF_HPP_ */
</code>```

literal.cpp

```<code>#include "literal_def.hpp"
#include "parser_config.hpp"

namespace parser {
    namespace x3 = boost::spirit::x3;

    BOOST_SPIRIT_INSTANTIATE(
        string_literal_type,
        iterator_type,
        context_type
    );
}
</code>```

literal.hpp

```<code>#ifndef PARSER_LITERAL_HPP_
#define PARSER_LITERAL_HPP_

#include "ast.hpp"
#include <boost/spirit/home/x3.hpp>

namespace parser {

    namespace x3 = boost::spirit::x3;

    struct string_literal_class;
    typedef x3::rule<string_literal_class, ast::string_literal> string_literal_type;

    BOOST_SPIRIT_DECLARE(string_literal_type);
}

namespace parser_api {
    parser::string_literal_type const& string_literal();
}

#endif /* PARSER_LITERAL_HPP_ */
</code>```

main.cpp

```<code>#include "grammar_def.hpp"
#include "parser_config.hpp"
#include <iostream>

int main()
{
    namespace x3 = boost::spirit::x3;

    ast::factor  attr;

    std::string input{ "a * b" };
    parser::iterator_type iter = input.begin();
    parser::iterator_type const end = input.end();

    parser::error_handler_type error_handler(iter, end, std::cerr);

    auto const parser =
        x3::with<x3::error_handler_tag>(std::ref(error_handler))
        [
              parser::factor
        ];

    bool success = x3::phrase_parse(iter, end, parser, x3::iso8859_1::space, attr);

    return 0;
}
</code>```

parser_config.hpp

```<code>#ifndef PARSER_CONFIG_HPP_
#define PARSER_CONFIG_HPP_

#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/utility/error_reporting.hpp>

namespace parser {
    namespace x3 = boost::spirit::x3;

    template <typename Iterator>
    using error_handler = x3::error_handler<Iterator>;
    using error_handler_tag = x3::error_handler_tag;

    typedef std::string::const_iterator                 iterator_type;
    typedef error_handler<iterator_type>                error_handler_type;
    typedef x3::phrase_parse_context<
            x3::iso8859_1::space_type>::type            phrase_context_type;
    typedef x3::with_context<
        error_handler_tag
        , std::reference_wrapper<error_handler_type> const
        , phrase_context_type
    >::type                                             context_type;
}

#endif /* CONFIG_HPP_ */
</code>```

and finally the CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.6)

project(x3_linker_error LANGUAGES CXX)
find_package(Boost REQUIRED COMPONENTS system)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# lib
add_library(${PROJECT_NAME}_x3 STATIC
    literal.cpp
)
# exe
add_executable(${PROJECT_NAME}
    main.cpp
)
target_link_libraries(${PROJECT_NAME}
    PRIVATE
    ${PROJECT_NAME}_x3
    ${Boost_SYSTEM_LIBRARY}
)

set(CMAKE_VERBOSE_MAKEFILE ON)
option(LINKER_ERROR "Enforce the linker error" ON)
if(LINKER_ERROR)
message("## Build to show linker errors")
target_compile_definitions(${PROJECT_NAME}_x3 PRIVATE LINKER_ERROR)
target_compile_definitions(${PROJECT_NAME} PRIVATE LINKER_ERROR)
endif()
</code>```

The code is also at wandbox.

Setting parser_api::string_literal() into the instance file literal.cpp doesn't change the result too (as expected). Hopefully it isn't a silly fault on my side but after weeks I'm at the end...

Addendum

I also tested the tip of Joel de Guzman to insert int x = context_type{}; to literal.cpp and main.cpp to get the the context used - its both the same:

```<code>x3_linker_error/literal.cpp
'boost::spirit::x3::context<boost::spirit::x3::error_handler_tag, const std::reference_wrapper<boost::spirit::x3::error_handler<__gnu_cxx::__normal_iterator<const char*, std::__cxx11::basic_string<char> > > >, boost::spirit::x3::context<boost::spirit::x3::skipper_tag, const boost::spirit::x3::char_class<boost::spirit::char_encoding::iso8859_1, boost::spirit::x3::space_tag>, boost::spirit::x3::unused_type> >::context(<brace-enclosed initializer list>)'

x3_linker_error/main.cpp
'boost::spirit::x3::context<boost::spirit::x3::error_handler_tag, const std::reference_wrapper<boost::spirit::x3::error_handler<__gnu_cxx::__normal_iterator<const char*, std::__cxx11::basic_string<char> > > >, boost::spirit::x3::context<boost::spirit::x3::skipper_tag, const boost::spirit::x3::char_class<boost::spirit::char_encoding::iso8859_1, boost::spirit::x3::space_tag>, boost::spirit::x3::unused_type> >::context(<brace-enclosed initializer list>)'
</code>```

答:
With help of Larry Evans the problem is solved. For details please follow the spirit-general mailing list.

The code fragments as such is correct. It seems that the problem did rise up in another context as Linking error when changing > to >> some times before and discussed by Seth.

The solution is to use/clone Larry's get_rhs branch of spirit.x3

```<code>git clone --branch get_rhs https://github.com/cppljevans/spirit.git destination
</code>```

and compile with defined BOOST_ERROR_CODE_HEADER_ONLY. Spirit.X3 as of Boost 1.64 doesn't compile. I've adapted the CMake file to reflect the changes (and cloned into cppljevans) and added further defines seen by Larry's compile log:

```<code>cmake_minimum_required(VERSION 3.6)

project(x3_linker_error LANGUAGES CXX)
find_package(Boost REQUIRED COMPONENTS system)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# lib
add_library(${PROJECT_NAME}_x3 STATIC
    literal.cpp
)
target_include_directories(${PROJECT_NAME}_x3
    PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/cppljevans/include
)
target_compile_definitions(${PROJECT_NAME}_x3 PRIVATE
    BOOST_SPIRIT_GET_RHS_CRTP=1 BOOST_SPIRIT_ATTR_XFORM_IN_RULE=1
)

# exe
add_executable(${PROJECT_NAME}
    main.cpp
)
target_include_directories(${PROJECT_NAME}
    PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/cppljevans/include
)
target_compile_definitions(${PROJECT_NAME} PRIVATE
    BOOST_SPIRIT_GET_RHS_CRTP=1 BOOST_SPIRIT_ATTR_XFORM_IN_RULE=1
    BOOST_ERROR_CODE_HEADER_ONLY
)
target_link_libraries(${PROJECT_NAME}
    PRIVATE
    ${PROJECT_NAME}_x3
    ${Boost_SYSTEM_LIBRARY}
)

set(CMAKE_VERBOSE_MAKEFILE ON)

option(LINKER_ERROR "Enforce the linker error" ON)

if(LINKER_ERROR)
message("## Build to show linker errors")
target_compile_definitions(${PROJECT_NAME}_x3 PRIVATE LINKER_ERROR)
target_compile_definitions(${PROJECT_NAME} PRIVATE LINKER_ERROR)
endif()
</code>```

Title: x3 linker error with separate TU

Body:
As my parser grows I separated some rules into different translation units (TU) and the linker problem rises. After weeks of several try&errors without success I reduced my ~50 rules to the (hopefully) minimal example presented here. I've read the related linking errors while separate parser using boost spirit x3 and checked, that I use at the context typedef iso8859_1::space_type and that I invoke iso8859_1::space later on. Also I don't let the compiler deduce the iterator_type.

The linker error I made more fancy by replacing some things:

In function `bool x3::rule<parser::string_literal_class, ast::string_literal, false>::parse<std::string::const_iterator, x3::context<x3::error_handler_tag, std::reference_wrapper<x3::error_handler<std::string::const_iterator > > const, x3::context<x3::skipper_tag, x3::char_class<char_encoding::iso8859_1, x3::space_tag> const, x3::unused_type> >, x3::variant<ast::string_literal> >(std::string::const_iterator&, std::string::const_iterator const&, x3::context<x3::error_handler_tag, std::reference_wrapper<x3::error_handler<std::string::const_iterator > > const, x3::context<x3::skipper_tag, x3::char_class<char_encoding::iso8859_1, x3::space_tag> const, x3::unused_type> > const&, x3::unused_type, x3::variant<ast::string_literal>&) const':

main.cpp: .text._ZNK5boost6spirit2x34ruleIN6parser20string_literal_classEN3ast14string_literalELb0EE5parseIN9__gnu_cxx17__normal_iteratorIPKcNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEENS1_7contextINS1_17error_handler_tagEKSt17reference_wrapperINS1_13error_handlerISJ_EEENSK_INS1_11skipper_tagEKNS1_10char_classINS0_13char_encoding9iso8859_1ENS1_9space_tagEEENS1_11unused_typeEEEEENS1_7variantIJS6_EEEEEbRT_RKS13_RKT0_SY_RT1_[_ZNK5boost6spirit2x34ruleIN6parser20string_literal_classEN3ast14string_literalELb0EE5parseIN9__gnu_cxx17__normal_iteratorIPKcNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEENS1_7contextINS1_17error_handler_tagEKSt17reference_wrapperINS1_13error_handlerISJ_EEENSK_INS1_11skipper_tagEKNS1_10char_classINS0_13char_encoding9iso8859_1ENS1_9space_tagEEENS1_11unused_typeEEEEENS1_7variantIJS6_EEEEEbRT_RKS13_RKT0_SY_RT1_]+0x37): undefined reference to `bool parser::parse_rule<std::string::const_iterator, x3::context<x3::error_handler_tag, std::reference_wrapper<x3::error_handler<std::string::const_iterator > > const, x3::context<x3::skipper_tag, x3::char_class<char_encoding::iso8859_1, x3::space_tag> const, x3::unused_type> >, x3::variant<ast::string_literal> >(x3::rule<parser::string_literal_class, ast::string_literal, false>, std::string::const_iterator&, std::string::const_iterator const&, x3::context<x3::error_handler_tag, std::reference_wrapper<x3::error_handler<std::string::const_iterator > > const, x3::context<x3::skipper_tag, x3::char_class<char_encoding::iso8859_1, x3::space_tag> const, x3::unused_type> > const&, x3::variant<ast::string_literal>&)'

I'm irritated by the __gnu_cxx17 iterator (from libstdc++??). I did try g++7.1.0 with the same result.

Attached the files to reproduce the linker error using a CMake file (with option LINKER_ERROR to get or even not (monolitic build without TU)).

ast.hpp

#ifndef AST_HPP_
#define AST_HPP_

#include <boost/spirit/home/x3/support/ast/variant.hpp>
#include <string>

#include <boost/fusion/include/adapt_struct.hpp>

namespace ast {
    namespace x3 = boost::spirit::x3;

    struct string_literal {
        std::string literal;
    };

    using primary = x3::variant<string_literal>;
    using factor = x3::variant<primary>;
}

BOOST_FUSION_ADAPT_STRUCT(ast::string_literal,
    literal
)

#endif // AST_HPP_

grammar_def.hpp

#include "ast.hpp"
#include <boost/spirit/home/x3.hpp>
#if defined(LINKER_ERROR)
#include "literal.hpp"
#endif

namespace parser {

   namespace x3 = boost::spirit::x3;

    struct factor_class;
    struct primary_class;
#if !defined(LINKER_ERROR)
    struct string_literal_class;
#endif

    typedef x3::rule<factor_class, ast::factor> factor_type;
    typedef x3::rule<primary_class, ast::primary> primary_type;
#if !defined(LINKER_ERROR)
    typedef x3::rule<string_literal_class, ast::string_literal> string_literal_type;
#endif

    factor_type const factor{ "factor" };
    primary_type const primary{ "primary" };
#if !defined(LINKER_ERROR)
    string_literal_type const string_literal{ "string_literal" };
#endif

#if defined(LINKER_ERROR)
    namespace {
        auto const& string_literal = parser_api::string_literal();
    }
#endif

    auto const factor_def = primary;

    auto const primary_def = string_literal;

#if !defined(LINKER_ERROR)
    auto const string_literal_def =
        x3::lexeme ['"' >> *x3::char_ >> '"' ]
        ;
#endif

    BOOST_SPIRIT_DEFINE(factor, primary)
#if !defined(LINKER_ERROR)
    BOOST_SPIRIT_DEFINE(
            string_literal
    )
#endif
}

literal_def.hpp

#ifndef PARSER_LITERAL_DEF_HPP_
#define PARSER_LITERAL_DEF_HPP_

#include "literal.hpp"

namespace parser {

    namespace x3 = boost::spirit::x3;

    string_literal_type const string_literal { "string_literal" };

    auto const string_literal_def =
        x3::lexeme ['"' >> *x3::char_ >> '"' ];

    BOOST_SPIRIT_DEFINE(
        string_literal
    )
}

namespace parser_api {
    parser::string_literal_type const& string_literal()
    {
        return parser::string_literal;
    }
}

#endif /* PARSER_LITERAL_DEF_HPP_ */

literal.cpp

#include "literal_def.hpp"
#include "parser_config.hpp"

namespace parser {
    namespace x3 = boost::spirit::x3;

    BOOST_SPIRIT_INSTANTIATE(
        string_literal_type,
        iterator_type,
        context_type
    );
}

literal.hpp

#ifndef PARSER_LITERAL_HPP_
#define PARSER_LITERAL_HPP_

#include "ast.hpp"
#include <boost/spirit/home/x3.hpp>

namespace parser {

    namespace x3 = boost::spirit::x3;

    struct string_literal_class;
    typedef x3::rule<string_literal_class, ast::string_literal> string_literal_type;

    BOOST_SPIRIT_DECLARE(string_literal_type);
}

namespace parser_api {
    parser::string_literal_type const& string_literal();
}

#endif /* PARSER_LITERAL_HPP_ */

main.cpp

#include "grammar_def.hpp"
#include "parser_config.hpp"
#include <iostream>

int main()
{
    namespace x3 = boost::spirit::x3;

    ast::factor  attr;

    std::string input{ "a * b" };
    parser::iterator_type iter = input.begin();
    parser::iterator_type const end = input.end();

    parser::error_handler_type error_handler(iter, end, std::cerr);

    auto const parser =
        x3::with<x3::error_handler_tag>(std::ref(error_handler))
        [
              parser::factor
        ];

    bool success = x3::phrase_parse(iter, end, parser, x3::iso8859_1::space, attr);

    return 0;
}

parser_config.hpp

#ifndef PARSER_CONFIG_HPP_
#define PARSER_CONFIG_HPP_

#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/utility/error_reporting.hpp>

namespace parser {
    namespace x3 = boost::spirit::x3;

    template <typename Iterator>
    using error_handler = x3::error_handler<Iterator>;
    using error_handler_tag = x3::error_handler_tag;

    typedef std::string::const_iterator                 iterator_type;
    typedef error_handler<iterator_type>                error_handler_type;
    typedef x3::phrase_parse_context<
            x3::iso8859_1::space_type>::type            phrase_context_type;
    typedef x3::with_context<
        error_handler_tag
        , std::reference_wrapper<error_handler_type> const
        , phrase_context_type
    >::type                                             context_type;
}

#endif /* CONFIG_HPP_ */

and finally the CMakeLists.txt

cmake_minimum_required(VERSION 3.6)

project(x3_linker_error LANGUAGES CXX)
find_package(Boost REQUIRED COMPONENTS system)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# lib
add_library(${PROJECT_NAME}_x3 STATIC
    literal.cpp
)
# exe
add_executable(${PROJECT_NAME}
    main.cpp
)
target_link_libraries(${PROJECT_NAME}
    PRIVATE
    ${PROJECT_NAME}_x3
    ${Boost_SYSTEM_LIBRARY}
)

set(CMAKE_VERBOSE_MAKEFILE ON)
option(LINKER_ERROR "Enforce the linker error" ON)
if(LINKER_ERROR)
message("## Build to show linker errors")
target_compile_definitions(${PROJECT_NAME}_x3 PRIVATE LINKER_ERROR)
target_compile_definitions(${PROJECT_NAME} PRIVATE LINKER_ERROR)
endif()

The code is also at wandbox.

Setting parser_api::string_literal() into the instance file literal.cpp doesn't change the result too (as expected). Hopefully it isn't a silly fault on my side but after weeks I'm at the end...

Addendum

I also tested the tip of Joel de Guzman to insert int x = context_type{}; to literal.cpp and main.cpp to get the the context used - its both the same:

x3_linker_error/literal.cpp
'boost::spirit::x3::context<boost::spirit::x3::error_handler_tag, const std::reference_wrapper<boost::spirit::x3::error_handler<__gnu_cxx::__normal_iterator<const char*, std::__cxx11::basic_string<char> > > >, boost::spirit::x3::context<boost::spirit::x3::skipper_tag, const boost::spirit::x3::char_class<boost::spirit::char_encoding::iso8859_1, boost::spirit::x3::space_tag>, boost::spirit::x3::unused_type> >::context(<brace-enclosed initializer list>)'

x3_linker_error/main.cpp
'boost::spirit::x3::context<boost::spirit::x3::error_handler_tag, const std::reference_wrapper<boost::spirit::x3::error_handler<__gnu_cxx::__normal_iterator<const char*, std::__cxx11::basic_string<char> > > >, boost::spirit::x3::context<boost::spirit::x3::skipper_tag, const boost::spirit::x3::char_class<boost::spirit::char_encoding::iso8859_1, boost::spirit::x3::space_tag>, boost::spirit::x3::unused_type> >::context(<brace-enclosed initializer list>)'

Body:
With help of Larry Evans the problem is solved. For details please follow the spirit-general mailing list.

The code fragments as such is correct. It seems that the problem did rise up in another context as Linking error when changing > to >> some times before and discussed by Seth.

The solution is to use/clone Larry's get_rhs branch of spirit.x3

git clone --branch get_rhs https://github.com/cppljevans/spirit.git destination

and compile with defined BOOST_ERROR_CODE_HEADER_ONLY. Spirit.X3 as of Boost 1.64 doesn't compile. I've adapted the CMake file to reflect the changes (and cloned into cppljevans) and added further defines seen by Larry's compile log:

cmake_minimum_required(VERSION 3.6)

project(x3_linker_error LANGUAGES CXX)
find_package(Boost REQUIRED COMPONENTS system)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# lib
add_library(${PROJECT_NAME}_x3 STATIC
    literal.cpp
)
target_include_directories(${PROJECT_NAME}_x3
    PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/cppljevans/include
)
target_compile_definitions(${PROJECT_NAME}_x3 PRIVATE
    BOOST_SPIRIT_GET_RHS_CRTP=1 BOOST_SPIRIT_ATTR_XFORM_IN_RULE=1
)

# exe
add_executable(${PROJECT_NAME}
    main.cpp
)
target_include_directories(${PROJECT_NAME}
    PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/cppljevans/include
)
target_compile_definitions(${PROJECT_NAME} PRIVATE
    BOOST_SPIRIT_GET_RHS_CRTP=1 BOOST_SPIRIT_ATTR_XFORM_IN_RULE=1
    BOOST_ERROR_CODE_HEADER_ONLY
)
target_link_libraries(${PROJECT_NAME}
    PRIVATE
    ${PROJECT_NAME}_x3
    ${Boost_SYSTEM_LIBRARY}
)

set(CMAKE_VERBOSE_MAKEFILE ON)

option(LINKER_ERROR "Enforce the linker error" ON)

if(LINKER_ERROR)
message("## Build to show linker errors")
target_compile_definitions(${PROJECT_NAME}_x3 PRIVATE LINKER_ERROR)
target_compile_definitions(${PROJECT_NAME} PRIVATE LINKER_ERROR)
endif()


问:
Android studio 2.3.2 gradle issue
I am fairly new to Android. Installed Android studio 2.3.2. Now I have created a sample project.

But the popup of building gradle project info is shown forever.

答:
Go to c:users\UserName\.gredle\wrapper\dists\gredle-version-all\a4w5fzrkeut1ox56xslb49grt\gradle-(version)-all.zip path

If gradle-(version)-all.zip file is not available then download the file gradle-(version)-all.zip that matches to gradle-(version)-all.zip.lck from this Link http://services.gradle.org/distributions/

Paste Downloaded file in to c:users\UserName\.gredle\wrapper\dists\gredle-version-all\a4w5fzrkeut1ox56xslb49grt

Close Android studio if open and open again and try to create new Project or import Existing project

i hope it will work for you...

Title: Android studio 2.3.2 gradle issue


问:
Calculate number of UITableViewCells that will fit in fixed space
I have a fixed amount of space where I will have a UITableView. I don't want the UITableView to scroll so I want to calculate the number of cells that will fit without scrolling. The cells are all different sizes and use UITableViewAutomaticDimension to determine size. What is the best way to go about this?</p>

答:
if you don't want tableView to scroll just get visible cell of tableView
let arrayCell = tableView.indexPathsForVisibleItems()
or
let arrayCells = tableView.visibleCells()

once you get visible cell you can find number of cell are visible


问:
How to get sample rate of mp3 file using python
I need to play this mp3 file using pygame but I dont know what the sample rate of the file is. I need some way to programaticaly get the sample rate of the audio file so that I can play it at the correct rate cuz  if I dont then it just distorts the sound. Thanks for any help </p>

答:
Using pydub:

```<code>>>> from pydub import AudioSegment
>>> song = AudioSegment.from_mp3("file.mp3")
>>> song.frame_rate
44100
</code>```

Or use pydub.utils.mediainfo():

```<code>>>> from pydub.utils import mediainfo
>>> info = mediainfo("file.mp3")
>>> print(info['sample_rate'])
44100
</code>```

Body:
Using pydub:

>>> from pydub import AudioSegment
>>> song = AudioSegment.from_mp3("file.mp3")
>>> song.frame_rate
44100

Or use pydub.utils.mediainfo():

>>> from pydub.utils import mediainfo
>>> info = mediainfo("file.mp3")
>>> print(info['sample_rate'])
44100


问:
How can I save a substring of a line from a text file into an array of strings?
I have code that reads a .txt file:

```<code>Pancho: Juanka,Cony
</code>```

The idea is to find the character ':' and save it apart in an array of strings. The same with Juanka and Cony but instead, it's going to be when it finds ',' and '\0'.

答:
While strtok will solve this problem, I believe it won't be a very maintainable solution. I intend to point out some problems with using strtok, and solutions to those problems.

Problem #1: Due to hidden state, strtok is non-reentrant and non-threadsafe; if you try to tokenise two strings simultaneously (e.g. interweaving sequences of function calls, or using multiple threads), you'll run into issues.

Solution #1: strchr and strcspn can be used instead to address this issue. I've demonstrated the ability to read lines in other answers1,2 using strcspn; these could be easily adapted to use strchr instead, or to use characters other than '\n'.

Problem #2: strtok, strchr and strcspn all operate upon a string which needs an intermediate array to exist within. You're reading from a file; if you don't need that intermediate array because you can read the fields directly into their corresponding arrays, then eliminating them might expose more advanced optimisations and cleaner, more maintainable code.

Solution #2: The following code demonstrates performing the splitting directly from the file by using fscanf.

```<code>#include <stdio.h>

#define WIDTH_STR(width) #width
#define FIXED_FIELD(width) "%" WIDTH_STR(width)
#define TERMINAL(set) "[^" set "]%*1[" set "] "

#define W 1024
int parse(FILE *f) {
    char x[W+1], y[W+1], z[W+1];
    if (fscanf(f, FIXED_FIELD(W) TERMINAL(":"),  x) <= 0) { return EOF; }
    if (fscanf(f, FIXED_FIELD(W) TERMINAL(","),  y) <= 0) { return EOF; }
    if (fscanf(f, FIXED_FIELD(W) TERMINAL("\n"), z) <= 0) { return EOF; }
    printf("<%s>\n", x);
    printf("<%s>\n", y);
    printf("<%s>\n", z);
    return 0;
}

int main(void) {
    printf("parse returned: %d\n", parse(stdin));
}
</code>```

Problem #3: All of the above solutions reach peak optimality (in terms of maintainability/complexity and computational efficiency) when you assume fields are fixed width. Once that assumption becomes invalid, it makes much more sense to use fgetc to read and parse one byte at a time, reallocating as necessary to accomodate for the variadic fields.

Solution #3: I've demonstrated the ability to read words of variable length in another answer, which would be easily adapted to read and parse single tokens into separate dynamic allocations. This is likely suffer the drawback of expensive reallocation necessary to allow your users to enter enormous (multiple-megabyte) field values which wouldn't typically be supported as fixed width arrays with automatic storage duration.

Body:
I have code that reads a .txt file:

Pancho: Juanka,Cony

The idea is to find the character ':' and save it apart in an array of strings. The same with Juanka and Cony but instead, it's going to be when it finds ',' and '\0'.

Body:
While strtok will solve this problem, I believe it won't be a very maintainable solution. I intend to point out some problems with using strtok, and solutions to those problems.

Problem #1: Due to hidden state, strtok is non-reentrant and non-threadsafe; if you try to tokenise two strings simultaneously (e.g. interweaving sequences of function calls, or using multiple threads), you'll run into issues.

Solution #1: strchr and strcspn can be used instead to address this issue. I've demonstrated the ability to read lines in other answers1,2 using strcspn; these could be easily adapted to use strchr instead, or to use characters other than '\n'.

Problem #2: strtok, strchr and strcspn all operate upon a string which needs an intermediate array to exist within. You're reading from a file; if you don't need that intermediate array because you can read the fields directly into their corresponding arrays, then eliminating them might expose more advanced optimisations and cleaner, more maintainable code.

Solution #2: The following code demonstrates performing the splitting directly from the file by using fscanf.

#include <stdio.h>

#define WIDTH_STR(width) #width
#define FIXED_FIELD(width) "%" WIDTH_STR(width)
#define TERMINAL(set) "[^" set "]%*1[" set "] "

#define W 1024
int parse(FILE *f) {
    char x[W+1], y[W+1], z[W+1];
    if (fscanf(f, FIXED_FIELD(W) TERMINAL(":"),  x) <= 0) { return EOF; }
    if (fscanf(f, FIXED_FIELD(W) TERMINAL(","),  y) <= 0) { return EOF; }
    if (fscanf(f, FIXED_FIELD(W) TERMINAL("\n"), z) <= 0) { return EOF; }
    printf("<%s>\n", x);
    printf("<%s>\n", y);
    printf("<%s>\n", z);
    return 0;
}

int main(void) {
    printf("parse returned: %d\n", parse(stdin));
}

Problem #3: All of the above solutions reach peak optimality (in terms of maintainability/complexity and computational efficiency) when you assume fields are fixed width. Once that assumption becomes invalid, it makes much more sense to use fgetc to read and parse one byte at a time, reallocating as necessary to accomodate for the variadic fields.

Solution #3: I've demonstrated the ability to read words of variable length in another answer, which would be easily adapted to read and parse single tokens into separate dynamic allocations. This is likely suffer the drawback of expensive reallocation necessary to allow your users to enter enormous (multiple-megabyte) field values which wouldn't typically be supported as fixed width arrays with automatic storage duration.


问:
JFileChooser: Cannot select Desktop when Selection Mode is File and Directories
I ran into an issue with JFileChooser and wanted to see if there is a workaround.

If the JFileChooser is created and the setFileSelectionMode is FILES_AND_DIRECTORIES, when a user clicks a shortcut button on the left (in XP) such as Desktop or My Documents or drop down to Desktop, the field is not placed in the File Name JTextPane. And when clicking the "Select/Accept" button, nothing happens (because isDirectorySelected() returns false for some reason).

Overriding the approveSeletion does not work because the Event Handler function in BasicFileChooser does not call it.

How would I make it so the Desktop can be selected without having to navigate to it manually, but by clicking the shortcut on the left?

Thanks

答:
Found the following code in the BasicFileChooserUI:

```<code>if (fc.getFileSelectionMode() == JFileChooser.FILES_AND_DIRECTORIES
&&  fc.getFileSystemView().isFileSystem(dir)) {
    setFileName(dir.getAbsolutePath());
}
</code>```

So it looks like "special folders" are purposely ignored. The code is in a private method so it would be hard to create you own UI.

As a hack you might be able to add a PropertyChangeListener to the file chooser:

```<code>public void propertyChange(final PropertyChangeEvent e)
{
    String prop = e.getPropertyName();

    if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop))
    {
        JFileChooser fileChooser = (JFileChooser)e.getSource();
        File currentDirectory = (File)e.getNewValue();

        String directory = currentDirectory.toString();

        if (directory.endsWith("Desktop")
        ||  directory.endsWith("My Documents"))
        {
            File selectedFile = fileChooser.getSelectedFile();

            if (selectedFile == null || ! selectedFile.equals(currentDirectory))
            {
                fileChooser.removePropertyChangeListener( this );
                fileChooser.setSelectedFile( currentDirectory );
                fileChooser.addPropertyChangeListener( this );
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Found the following code in the BasicFileChooserUI:

if (fc.getFileSelectionMode() == JFileChooser.FILES_AND_DIRECTORIES
&&  fc.getFileSystemView().isFileSystem(dir)) {
    setFileName(dir.getAbsolutePath());
}

So it looks like "special folders" are purposely ignored. The code is in a private method so it would be hard to create you own UI.

As a hack you might be able to add a PropertyChangeListener to the file chooser:

public void propertyChange(final PropertyChangeEvent e)
{
    String prop = e.getPropertyName();

    if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop))
    {
        JFileChooser fileChooser = (JFileChooser)e.getSource();
        File currentDirectory = (File)e.getNewValue();

        String directory = currentDirectory.toString();

        if (directory.endsWith("Desktop")
        ||  directory.endsWith("My Documents"))
        {
            File selectedFile = fileChooser.getSelectedFile();

            if (selectedFile == null || ! selectedFile.equals(currentDirectory))
            {
                fileChooser.removePropertyChangeListener( this );
                fileChooser.setSelectedFile( currentDirectory );
                fileChooser.addPropertyChangeListener( this );
            }
        }
    }
}


问:
Java program given string to replace character in the place of another character
Example String str ="Java"; get output as "jXavXa".

hint: replace every 'a' with 'Xa'. and another one in same pgrm replace only last occurrence of 'e' to 'Xa'

example: I/p = "experience" and o/p= "experiencXe" .

答:
For the first case you can use a simple replace call:

```<code>str = str.replace("a","Xa");
</code>```

For the case of replacing last occurrence, i don't think theres a direct way to do it, but you can implement your own using lastIndexOf(string) to find where in the string you will replace.

Body:
For the first case you can use a simple replace call:

str = str.replace("a","Xa");

For the case of replacing last occurrence, i don't think theres a direct way to do it, but you can implement your own using lastIndexOf(string) to find where in the string you will replace.


问:
Dropdownlists in Microsoft Outlook VSTO Add-In not responding
The Outlook add-in I build worked before, but now some of the users have notified me that the dropdownlists does not respond anymore. The add-in is an adjoining window below a new compose message. The Add-in window uses a System.Windows.Forms.WebBrowser to access a page on a website I created with all the dropdownlists.

I have uninstalled recent Microsoft updates but it did nothing.

It does the same if 'n run it in debug mode.

Same happens when I run the website on localhost.

The checkboxes works and can be checked it is just the dropdownlists which are unable to open, but if I press the down key I can access the lists items but the dropdown window does not show.

I presume it must be some change to Outlook and how it interacts with the WebBrowser control? It is the only thing that could have changed.

--EDIT--
Here is my code:

Dropdownlist asp.net code on website

```<code><asp:DropDownList ID="ddlDiscipline" runat="server" AutoPostBack="True" ForeColor="Black" OnSelectedIndexChanged="ddlDiscipline_SelectedIndexChanged" Width="136px" TabIndex="6" Visible="True">
</asp:DropDownList>
</code>```

C# Code part

```<code>protected void ddlDiscipline_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            foreach (ListItem item in ddlDiscipline.Items)
            {
                if (item.Selected)
                {
                    if (txtDiscipline.Text == "")
                    {
                        txtDiscipline.Text = item.Text;
                    }
                    else
                    {
                        txtDiscipline.Text = txtDiscipline.Text + "," + item.Text;
                    }
                }
            }
            ddlDiscipline.SelectedIndex = 0;
        }
        catch { }
    }
</code>```

What happens is that the Outlook Add-In uses the WebBrowser control to access this webpage. If the dropdownlist text changed event fires the selected item is added to a textbox.

This dropdownlists just stopped from opening suddenly without any changes to the code. There is no reference used to the dropdownlist in the VSTO program. It only needs the user to select it.

The dropdownlist responds in Internet Explorer:

It does not open in the Add-In window in Outlook:

答:
Do you get the same results with a windows form application?

Try to use any .net web browser control based on the Chromium engine. Based on my experience only the DotNetBrowser control works without issues for COM add-ins (including VSTO based). You may also consider open-source .net browsers such as Awesomium and CefSharp.

Body:
The Outlook add-in I build worked before, but now some of the users have notified me that the dropdownlists does not respond anymore. The add-in is an adjoining window below a new compose message. The Add-in window uses a System.Windows.Forms.WebBrowser to access a page on a website I created with all the dropdownlists.

I have uninstalled recent Microsoft updates but it did nothing.

It does the same if 'n run it in debug mode.

Same happens when I run the website on localhost.

The checkboxes works and can be checked it is just the dropdownlists which are unable to open, but if I press the down key I can access the lists items but the dropdown window does not show.

I presume it must be some change to Outlook and how it interacts with the WebBrowser control? It is the only thing that could have changed.

--EDIT--
Here is my code:

Dropdownlist asp.net code on website

<asp:DropDownList ID="ddlDiscipline" runat="server" AutoPostBack="True" ForeColor="Black" OnSelectedIndexChanged="ddlDiscipline_SelectedIndexChanged" Width="136px" TabIndex="6" Visible="True">
</asp:DropDownList>

C# Code part

protected void ddlDiscipline_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            foreach (ListItem item in ddlDiscipline.Items)
            {
                if (item.Selected)
                {
                    if (txtDiscipline.Text == "")
                    {
                        txtDiscipline.Text = item.Text;
                    }
                    else
                    {
                        txtDiscipline.Text = txtDiscipline.Text + "," + item.Text;
                    }
                }
            }
            ddlDiscipline.SelectedIndex = 0;
        }
        catch { }
    }

What happens is that the Outlook Add-In uses the WebBrowser control to access this webpage. If the dropdownlist text changed event fires the selected item is added to a textbox.

This dropdownlists just stopped from opening suddenly without any changes to the code. There is no reference used to the dropdownlist in the VSTO program. It only needs the user to select it.

The dropdownlist responds in Internet Explorer:

It does not open in the Add-In window in Outlook:


问:
Different groups of checkbox not working in jquery
I prefer to get checked checkboxes from a specific checkbox group, depending on which button I have clicked, I used $('input[name="' + groupName + '"]:checked'). This will ensure that the checked checkboxes from only the coffee or animals checkbox group are selected. But it's not working as I expected.

```<code><body>
    <div>
        <input type="checkbox" value="Lion" name="animals" checked />Lion<br>
        <input type="checkbox" value="Tiger" name="animals" />Tiger<br>
        <input type="checkbox" value="Elephant" name="animals" />Elephant<br>
        <input type="checkbox" value="Girafee" name="animals" />Girafee<br>
        <input type="submit" id="__mainAnimals" />
        <br><br><br><br><br><br>
        <input type="checkbox" value="Coffe" name="drinks" checked />Coffe<br>
        <input type="checkbox" value="Tea" name="drinks" />Tea<br>
        <input type="checkbox" value="Milk" name="drinks" />Milk<br>
        <input type="checkbox" value="Mocha" name="drinks" />Mocha<br>
        <input type="submit" id="__mainDrinks" />
    </div>
    <div id="__DIVresult"></div>

    <script type="text/javascript">
        $(document).ready(function () {
        $('#__mainAnimals').click(function () {
            getSelectedCheckBoxes('animals');
        });

        $('#__mainDrinks').click(function () {
            getSelectedCheckBoxes('drinks');
        });

        var getSelectedCheckBoxes = function (groupName) {
            var result = $('input[name="' + groupName + '"]:checked');
            if (result.length > 0) {
                var resultString = result.length + " checkboxe(s) checked<br/>";
                result.each(function () {
                    resultString += $(this).val() + "<br/>";
                });
                $('__DIVresult').html(resultString);
            }
            else {
                $('__DIVresult').html("No checkbox checked");
            }
        };
    });

    </script>

</body>
</code>```

答:
```<code><script>

     function updateTextArea() {
 var allVals = [];
 $('.ads_Checkbox:checked').each(function() {
   allVals.push($(this).val());
 });
 $('#t').val(allVals);
</code>```

}

```<code>    $('#save_value').click(function(){
        $('.ads_Checkbox:checked').each(function(){
                updateTextArea();
        });
    });
</code>```

Inside this code I have named each animal and placed them in a class so I could recall them from an array. I hoped this helped.

Body:
I prefer to get checked checkboxes from a specific checkbox group, depending on which button I have clicked, I used $('input[name="' + groupName + '"]:checked'). This will ensure that the checked checkboxes from only the coffee or animals checkbox group are selected. But it's not working as I expected.

        <input type="checkbox" value="Lion" name="animals" checked />Lion

        <input type="checkbox" value="Tiger" name="animals" />Tiger

        <input type="checkbox" value="Elephant" name="animals" />Elephant

        <input type="checkbox" value="Girafee" name="animals" />Girafee

        <input type="submit" id="__mainAnimals" />

        <input type="checkbox" value="Coffe" name="drinks" checked />Coffe

        <input type="checkbox" value="Tea" name="drinks" />Tea

        <input type="checkbox" value="Milk" name="drinks" />Milk

        <input type="checkbox" value="Mocha" name="drinks" />Mocha

        <input type="submit" id="__mainDrinks" />

Body:
<script>

     function updateTextArea() {
 var allVals = [];
 $('.ads_Checkbox:checked').each(function() {
   allVals.push($(this).val());
 });
 $('#t').val(allVals);

}

    $('#save_value').click(function(){
        $('.ads_Checkbox:checked').each(function(){
                updateTextArea();
        });
    });

Inside this code I have named each animal and placed them in a class so I could recall them from an array. I hoped this helped.


问:
How to add resources in Maven Classpath
I am new to Spring and Maven. I am trying to build a spring app using maven archetypes. So i have set up the project with maven pom.xml.  All things work fine but the only issue is my IDE (netbeans) is not including my spring.xml in the classpath. As a result the build fails with file not found exception. I have to specifically give the fully qualified path of the spring.xml to get this working.

So the below fails -
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

If i change it as below it works -

```<code>AbstractApplicationContext context = new ClassPathXmlApplicationContext("file:///Users/shoukat/NetBeansProjects/csm/src/main/java/spring.xml");
</code>```

I find that this is happening because my classpath does not include the main/java directory.  Below are the results when i try to print the classloader URLs using the below code-

```<code>        ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();

        //Get the URLs
        URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();

        for(int i=0; i< urls.length; i++)
        {
            System.out.println(urls[i].getFile());
        }
</code>```

Result -

```<code>/Users/shoukat/NetBeansProjects/csm/target/classes/
/Users/shoukat/.m2/repository/commons-logging/commons-logging/1.1.3/commons-logging-1.1.3.jar
/Users/shoukat/.m2/repository/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar
/Users/shoukat/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.5/jcl-over-slf4j-1.7.5.jar
/Users/shoukat/.m2/repository/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar
/Users/shoukat/.m2/repository/org/springframework/spring-context/4.0.0.RELEASE/spring-context-4.0.0.RELEASE.jar
/Users/shoukat/.m2/repository/org/springframework/spring-aop/4.0.0.RELEASE/spring-aop-4.0.0.RELEASE.jar
/Users/shoukat/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar
/Users/shoukat/.m2/repository/org/springframework/spring-beans/4.0.0.RELEASE/spring-beans-4.0.0.RELEASE.jar
/Users/shoukat/.m2/repository/org/springframework/spring-core/4.0.0.RELEASE/spring-core-4.0.0.RELEASE.jar
</code>```

Ideally this should also include the src directory as i am putting my resources spring.xml file in there. What do i need to change so the my src/main directory is included in classpath and i do not have to hardcode my program with the fully qualified system path of my spring.xml file?

Thanks

答:
When using ClassPathXmlApplicationContext search spring.xml in your classpath but maven when compile ignore resources like * .xml put in src/main/java

For this to work you have to create the resource folder and the folder tree is like:

```<code>src/main/java/..
src/main/resources/spring.xml
</code>```

Then you can use:

AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

Maven - Introduction to the Standard Directory Layout

Title: How to add resources in Maven Classpath

Body:
I am new to Spring and Maven. I am trying to build a spring app using maven archetypes. So i have set up the project with maven pom.xml.  All things work fine but the only issue is my IDE (netbeans) is not including my spring.xml in the classpath. As a result the build fails with file not found exception. I have to specifically give the fully qualified path of the spring.xml to get this working.

So the below fails -
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

If i change it as below it works -

AbstractApplicationContext context = new ClassPathXmlApplicationContext("file:///Users/shoukat/NetBeansProjects/csm/src/main/java/spring.xml");

I find that this is happening because my classpath does not include the main/java directory.  Below are the results when i try to print the classloader URLs using the below code-

        ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();

        //Get the URLs
        URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();

        for(int i=0; i< urls.length; i++)
        {
            System.out.println(urls[i].getFile());
        }

Result -

/Users/shoukat/NetBeansProjects/csm/target/classes/
/Users/shoukat/.m2/repository/commons-logging/commons-logging/1.1.3/commons-logging-1.1.3.jar
/Users/shoukat/.m2/repository/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar
/Users/shoukat/.m2/repository/org/slf4j/jcl-over-slf4j/1.7.5/jcl-over-slf4j-1.7.5.jar
/Users/shoukat/.m2/repository/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar
/Users/shoukat/.m2/repository/org/springframework/spring-context/4.0.0.RELEASE/spring-context-4.0.0.RELEASE.jar
/Users/shoukat/.m2/repository/org/springframework/spring-aop/4.0.0.RELEASE/spring-aop-4.0.0.RELEASE.jar
/Users/shoukat/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar
/Users/shoukat/.m2/repository/org/springframework/spring-beans/4.0.0.RELEASE/spring-beans-4.0.0.RELEASE.jar
/Users/shoukat/.m2/repository/org/springframework/spring-core/4.0.0.RELEASE/spring-core-4.0.0.RELEASE.jar

Ideally this should also include the src directory as i am putting my resources spring.xml file in there. What do i need to change so the my src/main directory is included in classpath and i do not have to hardcode my program with the fully qualified system path of my spring.xml file?

Thanks

Body:
When using ClassPathXmlApplicationContext search spring.xml in your classpath but maven when compile ignore resources like * .xml put in src/main/java

For this to work you have to create the resource folder and the folder tree is like:

src/main/java/..
src/main/resources/spring.xml

Then you can use:

AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

Maven - Introduction to the Standard Directory Layout


问:
JavaScript array.sort with multiple values (strings and numbers)
I'd like to sort an array by subject (string, alphabetical), then level (int, ascending), then name (string, alphabetical). I have found numerous other threads on SO but I haven't found any which sort by multiple variable types. I thought I had it, but it isn't sorting properly.

The sort function:

```<code>scipads.sort(function (a, b) {
    if (a.subject != b.subject)
        return a.subject < b.subject;
    if (a.level != b.level)
        return a.level - b.level;
    return a.name < b.name;
});
</code>```

The  array:

```<code>var scipads = [{
        "name": "L2 Physics Externals",
        "level": 2,
        "subject": "physics",
    }, {
        "name": "L2 Physics Internals",
        "level": 2,
        "subject": "physics",
    }, {
        "name": "L2 Chem Externals",
        "level": 2,
        "subject": "chemistry",
    }, {
        "name": "L2 Chem Internals",
        "level": 2,
        "subject": "chemistry",
    }, {
        "name": "L2 Bio Internals",
        "level": 2,
        "subject": "biology",
    }, {
        "name": "L2 Bio Externals",
        "level": 2,
        "subject": "biology",
    }, {
        "name": "L1 Electricity & Magnetism",
        "level": 1,
        "subject": "physics",
    }, {
        "name": "L1 Wave Behaviour",
        "level": 1,
        "subject": "physics",
    }, {
        "name": "L1 Heat",
        "level": 1,
        "subject": "physics",
    }, {
        "name": "L1 Carbon Chemistry",
        "level": 1,
        "subject": "chemistry",
    }, {
        "name": "L1 Selected Elements",
        "level": 1,
        "subject": "chemistry",
    }, {
        "name": "L1 Chemical Reactions",
        "level": 1,
        "subject": "chemistry",
    },
];
</code>```

How can I sort by subject, then level, then name?

答:
Your sort compare function is close, but not quite on. You should be returning -1 for less than, 0 for equal, and 1 for greater than. See here for documentation.

Example: change return a.subject < b.subject to return a.subject < b.subject ? -1 : 1;

Body:
I'd like to sort an array by subject (string, alphabetical), then level (int, ascending), then name (string, alphabetical). I have found numerous other threads on SO but I haven't found any which sort by multiple variable types. I thought I had it, but it isn't sorting properly.

The sort function:

scipads.sort(function (a, b) {
    if (a.subject != b.subject)
        return a.subject < b.subject;
    if (a.level != b.level)
        return a.level - b.level;
    return a.name < b.name;
});

The  array:

var scipads = [{
        "name": "L2 Physics Externals",
        "level": 2,
        "subject": "physics",
    }, {
        "name": "L2 Physics Internals",
        "level": 2,
        "subject": "physics",
    }, {
        "name": "L2 Chem Externals",
        "level": 2,
        "subject": "chemistry",
    }, {
        "name": "L2 Chem Internals",
        "level": 2,
        "subject": "chemistry",
    }, {
        "name": "L2 Bio Internals",
        "level": 2,
        "subject": "biology",
    }, {
        "name": "L2 Bio Externals",
        "level": 2,
        "subject": "biology",
    }, {
        "name": "L1 Electricity & Magnetism",
        "level": 1,
        "subject": "physics",
    }, {
        "name": "L1 Wave Behaviour",
        "level": 1,
        "subject": "physics",
    }, {
        "name": "L1 Heat",
        "level": 1,
        "subject": "physics",
    }, {
        "name": "L1 Carbon Chemistry",
        "level": 1,
        "subject": "chemistry",
    }, {
        "name": "L1 Selected Elements",
        "level": 1,
        "subject": "chemistry",
    }, {
        "name": "L1 Chemical Reactions",
        "level": 1,
        "subject": "chemistry",
    },
];

How can I sort by subject, then level, then name?


问:
Do .Net Collection Classes Use .Equals() on contained members to evaluate .Contains()?
The subject pretty much says it all.

Does a collection class use an (overridden) .Equals() method to determine if the collection class .Contains() an element or not?  Or does it use reference equality or some other method?

I would like the collection class to ignore a single field on contained members when determining if the collection .Contains() an element or not.

答:
This is demanding a personal test case. :)

Write a test, construct a list with one mock object, execute .Contains().

Now check the mock object - did .Equals() get called?
What about the hash value?


问:
Calculating the software keyboard height - iOS and Android
In my Cordova app I'd like to be able to tell if a particular element is offscreen, and scroll it to the center of the viewport if it is. Unfortunately, my calculations all seem to be thrown off by the various sizes of the iOS and Android keyboards -- the height varies based on the keyboard used, whether auto-suggestions are on, whether the screen is in portrait or landscape mode, etc.

On iOS, Cordova has the cordova-plugin-keyboard plugin that gives us the height in the KeyboardHeightWillChange event. I see that there is something in native code for Android mentioned in this blog post: https://pspdfkit.com/blog/2016/keyboard-handling-on-android/. Has anyone found a means to determine the height of the keyboard in Cordova-land on both iOS and Android?

答:
As far as i checked, this plugin's - Cordova native keyboard plugin onKeyboardWillShow &  onKeyboardDidShow options does what you are expecting.

Unfortunately this plugin is commercial as the author has mentioned that it was a beast to implement. But he is also open for suggestion regarding the costing. You can mail him to check out the options. Cheers


问:
Upserting with Mongoose
I have a schema that is defined like

```<code>var UserSchema = mongoose.Schema({
    user: {
        ipAddress: String,
        pollIDs: [{
            id: String
        }]
    }
});

var User = module.exports = mongoose.model('User', UserSchema);
</code>```

What I want to create is a route that checks the requests ip address, see if it exists in the database, if it doesn't create a new document with the ipAddress property set accordingly and the current req.body.poll_id to be an element in the pollIDs array.

However, if there is a document with that ip address I want the req.body.poll_id to be pushed into the pollIDs array.

I would demonstrate my first attempt, but I know that I've messed up the parameters on the findOneAndUpdate call.

答:
Should be as simple as:

```<code>User.findOneAndUpdate(
    {'user.ipAddress': req.body.ipAddress},
    {$push: {'user.pollIDs': {id: req.body.poll_id}}},
    {upsert: true, new: true},
    (err, doc) => {...});
</code>```

The upsert will take the query object and apply the update operation to it in the case where it needs to insert a new document.

Title: Upserting with Mongoose

Body:
I have a schema that is defined like

var UserSchema = mongoose.Schema({
    user: {
        ipAddress: String,
        pollIDs: [{
            id: String
        }]
    }
});

var User = module.exports = mongoose.model('User', UserSchema);

What I want to create is a route that checks the requests ip address, see if it exists in the database, if it doesn't create a new document with the ipAddress property set accordingly and the current req.body.poll_id to be an element in the pollIDs array.

However, if there is a document with that ip address I want the req.body.poll_id to be pushed into the pollIDs array.

I would demonstrate my first attempt, but I know that I've messed up the parameters on the findOneAndUpdate call.

Body:
Should be as simple as:

User.findOneAndUpdate(
    {'user.ipAddress': req.body.ipAddress},
    {$push: {'user.pollIDs': {id: req.body.poll_id}}},
    {upsert: true, new: true},
    (err, doc) => {...});

The upsert will take the query object and apply the update operation to it in the case where it needs to insert a new document.


答:
Use localeCompare for comparing strings

var scipads=[{name:"L2 Physics Externals",level:2,subject:"physics"},{name:"L2 Physics Internals",level:2,subject:"physics"},{name:"L2 Chem Externals",level:2,subject:"chemistry"},{name:"L2 Chem Internals",level:2,subject:"chemistry"},{name:"L2 Bio Internals",level:2,subject:"biology"},{name:"L2 Bio Externals",level:2,subject:"biology"},{name:"L1 Electricity & Magnetism",level:1,subject:"physics"},{name:"L1 Wave Behaviour",level:1,subject:"physics"},{name:"L1 Heat",level:1,subject:"physics"},{name:"L1 Carbon Chemistry",level:1,subject:"chemistry"},{name:"L1 Selected Elements",level:1,subject:"chemistry"},{name:"L1 Chemical Reactions",level:1,subject:"chemistry"}];

scipads.sort(function(a, b) {
  if (a.subject != b.subject)
    return a.subject.localeCompare(b.subject);
  else if (a.level != b.level)
    return a.level - b.level;
  return a.name.localeCompare(b.name);
});

console.log(scipads);```

Title: JavaScript array.sort with multiple values (strings and numbers)


问:
Deploy azure arm template from local git
I know you can push from local git and deploy code is azure web app.

But i want

first Deploy complete arm template from scratch using local git push.
and in the same push i want to deploy website code.

Now question is if arm template is creating web app from scratch then which git repo to push .

i am confused in this can some body tell me proper way to achieve this.

答:
well, you would need to create a hook, that would launch a script that would deploy your template. After the deployment is complete your script would get the git url from the webapp it deployed and push from local git to that repo.

That being said, it is 100 times easier to just place files on github and configure continuous delivery that would happen on its own. all you would need to do is to push to git from local repo.

Reference:

https://learn.microsoft.com/en-us/azure/app-service-web/app-service-deploy-local-git

https://learn.microsoft.com/en-us/azure/app-service-web/app-service-continuous-deployment


问:
Is 'cast' dangerous in user-submitted content in classic ASP?
The legacy web app I have inherited, which was custom-written for Oxfam New Zealand in classic ASP, runs a string replace on user-submitted inputs removing the string 'cast' presumably because of the cast function.

However this means that none of our participants can have a name or email address that contains that string. This is causing problems for someone with the surname Hardcastle.

This seems completely over the top security-wise - or at least there must be a way to ensure the user inputs are safe without changing the inputs of people with 'cast' in their name or email address.

The actual replace is done with:

```<code>strString = (Replace(strString, "cast", "", 1, -1, vbTextCompare))
</code>```

I'm considering just commenting that line out, would that be safe to do?

答:
The legacy app is doing it wrong.

Rather than filtering the content at the source,  the content should be property encoded wherever it is used.  In other words, if it's being used in a query, the value would be encoded prior to adding it to the SQL statement or better yet placed unmolested into a stored procedure parameter.

So yes, you can remove that code, but make sure strString is being used safely elsewhere.

Body:
The legacy web app I have inherited, which was custom-written for Oxfam New Zealand in classic ASP, runs a string replace on user-submitted inputs removing the string 'cast' presumably because of the cast function.

However this means that none of our participants can have a name or email address that contains that string. This is causing problems for someone with the surname Hardcastle.

This seems completely over the top security-wise - or at least there must be a way to ensure the user inputs are safe without changing the inputs of people with 'cast' in their name or email address.

The actual replace is done with:

strString = (Replace(strString, "cast", "", 1, -1, vbTextCompare))

I'm considering just commenting that line out, would that be safe to do?


答:
Comparison should return an integer. Here's an example:</p>

```<code>scipads.sort((a, b) => {
    if (a.subject != b.subject) {
        return a.subject < b.subject ? -1 : 1;
    }
    if (a.level != b.level) {
        return a.level - b.level;
    }
    return a.name < b.name ? -1 : 1;
})
</code>```

Body:
Comparison should return an integer. Here's an example:

scipads.sort((a, b) => {
    if (a.subject != b.subject) {
        return a.subject < b.subject ? -1 : 1;
    }
    if (a.level != b.level) {
        return a.level - b.level;
    }
    return a.name < b.name ? -1 : 1;
})


问:
Shouldn't this code make the whole picture black?
In p5.js, I am trying to process each pixel of an image for a personal project so I thought I would start out slow and just try to make each pixel black. For some reason the screen is just staying white and I have no idea why the pixels aren't being updated. Here's the code:

```<code>var Canvas;
var srcImg;
var defaultImg = "http://i.imgur.com/ARg0OOy.jpg";

function preload() {
srcImg = loadImage(defaultImg);
}

function setup () {
  createCanvas(srcImg.width,srcImg.height);
  noLoop();
}

function draw() {
  srcImg.loadPixels();
  for (var x = 0; x < srcImg.width; x++) {
    for (var y = 0; y < srcImg.height; y++) {
      var loc = x + y*srcImg.width;
      srcImg.pixels[loc] = color(224,29,29);
    }
  }
  console.log(loc);
  console.log(srcImg.width);
  console.log(srcImg.height);
  console.log(srcImg.width * srcImg.height);
  srcImg.updatePixels();
  //image(srcImg, 0,0,srcImg.width, srcImg.height);
}
</code>```

Also, if I uncomment the last line, I see the original picture and it is cut off at the top (and it hasn't turned every pixel black). You can see for yourself here. Any thoughts on why this is happening?

Edit: I tried even doing one row of pixels to be a vibrant red color and the reason I'm getting a white screen is because no matter what color I set the pixels to, they become white... Also, when I tried making the whole row this red color, it stopped at about 1/4 the way through as shown here (and is still white). I  don't know why this is happening.

答:
You're making all of the pixels black, but then you're drawing srcImage on top of those black pixels. So all you see is srcImage.

Try commenting out the image(srcImg, 0,0,srcImg.width, srcImg.height); line to see the black pixels.

Body:
In p5.js, I am trying to process each pixel of an image for a personal project so I thought I would start out slow and just try to make each pixel black. For some reason the screen is just staying white and I have no idea why the pixels aren't being updated. Here's the code:

var Canvas;
var srcImg;
var defaultImg = "http://i.imgur.com/ARg0OOy.jpg";

function preload() {
srcImg = loadImage(defaultImg);
}

function setup () {
  createCanvas(srcImg.width,srcImg.height);
  noLoop();
}

function draw() {
  srcImg.loadPixels();
  for (var x = 0; x < srcImg.width; x++) {
    for (var y = 0; y < srcImg.height; y++) {
      var loc = x + y*srcImg.width;
      srcImg.pixels[loc] = color(224,29,29);
    }
  }
  console.log(loc);
  console.log(srcImg.width);
  console.log(srcImg.height);
  console.log(srcImg.width * srcImg.height);
  srcImg.updatePixels();
  //image(srcImg, 0,0,srcImg.width, srcImg.height);
}

Also, if I uncomment the last line, I see the original picture and it is cut off at the top (and it hasn't turned every pixel black). You can see for yourself here. Any thoughts on why this is happening?

Edit: I tried even doing one row of pixels to be a vibrant red color and the reason I'm getting a white screen is because no matter what color I set the pixels to, they become white... Also, when I tried making the whole row this red color, it stopped at about 1/4 the way through as shown here (and is still white). I  don't know why this is happening.


问:
PL/SQL Switching two columns from two tables
Suppose I have two tables (tblA and tblB) and want to switch the second column of each table (tblA.Grade and tblB.Grade) as shown:

```<code>+-------------------------------------+
|    table a               table b    |
+-------------------------------------+
| name  grade           name    grade |
| a     60              f       50    |
| b     45              g       70    |
| c     30              h       90    |
+-------------------------------------+
</code>```

Now, I would like to switch the grade column from table a to table b and the the grade column from table b to table a.  The result should look like this:

```<code>+-----------------------------------------+
|      table a               table b      |
+-----------------------------------------+
|     name  grade           name    grade |
|     a     50              f       60    |
|     b     70              g       45    |
|     c     90              h       30    |
+-----------------------------------------+
</code>```

I have created the tables, loaded them into cursors using bulk collect and the following code to complete the transformation:

```<code>insert into tblA values('a',60);
insert into tblA values('b',45);
insert into tblA values('c',30);
insert into tblb values('f',70);
insert into tblb values('g',80);
insert into tblb values('h',90);
</code>```

.

```<code>DECLARE
    TYPE tbla_type IS TABLE OF tbla%ROWTYPE;
    l_tbla tbla_type;
    TYPE tblb_type IS TABLE OF tblb%ROWTYPE;
    l_tblb tblb_type;

BEGIN
-- All rows at once...
SELECT *
BULK COLLECT INTO l_tbla
FROM tbla;

SELECT *
BULK COLLECT INTO l_tblb
FROM tblb;

    DBMS_OUTPUT.put_line (l_tblb.COUNT);

    FOR indx IN 1 .. l_tbla.COUNT
  LOOP
    DBMS_OUTPUT.put_line (l_tbla(indx).lname);
        update tbla set grade = l_tblb(indx).grade
          where l_tbla(indx).lname= tbla.lname;

              update tblb set grade = l_tbla(indx).grade
          where l_tblb(indx).lname= tblb.lname;
  END LOOP;
END;
</code>```

So, although I did the task, I am wondering if there is a more simple solution that I have not thought of?

Please let me know if anyone knows if there may be a more simple solution?

答:
Note that there is nothing called first or second record in databases as there is no guarantee that the first record entered will be the first one returned. So there should always be an order by to decide first/second etc.

So assuming you want the records to be ordered by name and then swap grade of smallest name of first table with grade of smallest name of second table,

Now assuming you fix the order thingy in your existing code, and if it is working, I believe it would be faster than the way I would do it below. Something like

Create a temp table and put names and grade ordered by name.

Reason of using temp table is mostly because later if I want to correct or revert the data, I can use the same temp table to reverse the merge.

```<code>    create table tmp1 as
    with ta as
    (select t.* ,
    row_number() over (order by name) as rnk
    from tblA t)
    ,tb as
    (select t.* ,
    row_number() over (order by name) as rnk
    from tblb t)
    select ta.name as ta_name,ta.grade as ta_grade,
    tb.name as tb_name,tb.grade as tb_grade
    from ta inner join tb
    on ta.rnk=tb.rnk
</code>```

Output of tmp1

```<code>+---------+----------+---------+----------+
| TA_NAME | TA_GRADE | TB_NAME | TB_GRADE |
+---------+----------+---------+----------+
| a       |       60 | f       |       70 |
| b       |       45 | g       |       80 |
| c       |       30 | h       |       90 |
+---------+----------+---------+----------+
</code>```

Then use merge to swap value from tmp1.

```<code>merge  into tbla t1
using  tmp1 t
on (t1.name=t.ta_name)
when matched then update
set t1.grade=t.tb_grade;

merge  into tblb t1
using  tmp1 t
on (t1.name=t.tb_name)
when matched then update
set t1.grade=t.ta_grade;
</code>```

If satisfied with result, drop the temp table later

```<code>drop table tmp1;
</code>```

Body:
Suppose I have two tables (tblA and tblB) and want to switch the second column of each table (tblA.Grade and tblB.Grade) as shown:

+-------------------------------------+
|    table a               table b    |
+-------------------------------------+
| name  grade           name    grade |
| a     60              f       50    |
| b     45              g       70    |
| c     30              h       90    |
+-------------------------------------+

Now, I would like to switch the grade column from table a to table b and the the grade column from table b to table a.  The result should look like this:

+-----------------------------------------+
|      table a               table b      |
+-----------------------------------------+
|     name  grade           name    grade |
|     a     50              f       60    |
|     b     70              g       45    |
|     c     90              h       30    |
+-----------------------------------------+

I have created the tables, loaded them into cursors using bulk collect and the following code to complete the transformation:

insert into tblA values('a',60);
insert into tblA values('b',45);
insert into tblA values('c',30);
insert into tblb values('f',70);
insert into tblb values('g',80);
insert into tblb values('h',90);

.

DECLARE
    TYPE tbla_type IS TABLE OF tbla%ROWTYPE;
    l_tbla tbla_type;
    TYPE tblb_type IS TABLE OF tblb%ROWTYPE;
    l_tblb tblb_type;

BEGIN
-- All rows at once...
SELECT *
BULK COLLECT INTO l_tbla
FROM tbla;

SELECT *
BULK COLLECT INTO l_tblb
FROM tblb;

    DBMS_OUTPUT.put_line (l_tblb.COUNT);

    FOR indx IN 1 .. l_tbla.COUNT
  LOOP
    DBMS_OUTPUT.put_line (l_tbla(indx).lname);
        update tbla set grade = l_tblb(indx).grade
          where l_tbla(indx).lname= tbla.lname;

              update tblb set grade = l_tbla(indx).grade
          where l_tblb(indx).lname= tblb.lname;
  END LOOP;
END;

So, although I did the task, I am wondering if there is a more simple solution that I have not thought of?

Please let me know if anyone knows if there may be a more simple solution?

Body:
Note that there is nothing called first or second record in databases as there is no guarantee that the first record entered will be the first one returned. So there should always be an order by to decide first/second etc.

So assuming you want the records to be ordered by name and then swap grade of smallest name of first table with grade of smallest name of second table,

Now assuming you fix the order thingy in your existing code, and if it is working, I believe it would be faster than the way I would do it below. Something like

Create a temp table and put names and grade ordered by name.

Reason of using temp table is mostly because later if I want to correct or revert the data, I can use the same temp table to reverse the merge.

    create table tmp1 as
    with ta as
    (select t.* ,
    row_number() over (order by name) as rnk
    from tblA t)
    ,tb as
    (select t.* ,
    row_number() over (order by name) as rnk
    from tblb t)
    select ta.name as ta_name,ta.grade as ta_grade,
    tb.name as tb_name,tb.grade as tb_grade
    from ta inner join tb
    on ta.rnk=tb.rnk

Output of tmp1

+---------+----------+---------+----------+
| TA_NAME | TA_GRADE | TB_NAME | TB_GRADE |
+---------+----------+---------+----------+
| a       |       60 | f       |       70 |
| b       |       45 | g       |       80 |
| c       |       30 | h       |       90 |
+---------+----------+---------+----------+

Then use merge to swap value from tmp1.

merge  into tbla t1
using  tmp1 t
on (t1.name=t.ta_name)
when matched then update
set t1.grade=t.tb_grade;

merge  into tblb t1
using  tmp1 t
on (t1.name=t.tb_name)
when matched then update
set t1.grade=t.ta_grade;

If satisfied with result, drop the temp table later

drop table tmp1;


问:
Angular 2 form validation pattern regex error
I'm creating a form in angular that requires the name field only contain alphanumeric characters and spaces. To do this I use the pattern attribute:

```<code><input type="text" class="form-control" placeholder="Name" name="Name" [(ngModel)]="name" required pattern="/^[a-z\d-_\s]+$/i" #nameField="ngModel">
</code>```

and I have the following error message I want to show when the string does not match:

```<code><div *ngIf="nameField.errors">
   <div [hidden]="!nameField.errors.pattern">
       <p class="has-error">
          Only spaces, letters, and numbers are allowed.
       </p>
   </div>
</div>
</code>```

However, it seems that even when the string should match the regular expression, I can still see the error message. Any ideas?

答:
I guess the issue here is that the syntax of regex not correctly formed:

```<code> <form novalidate #f="ngForm" novalidate>
    <input type="text"
    class="form-control"
    placeholder="Name" name="Name"
    [(ngModel)]="name"
    required pattern="^[A-Z\\a-z\\d-_\\s]+$"
    #nameField="ngModel" >
    <div>
      <div *ngIf="nameField.errors?.pattern">
        <p class="has-error">
          Only spaces, letters, and numbers are allowed.
        </p>
        hame: {{nameField.errors | json}}
     </div>
    </div>
  </form>
</code>```

look at this plunkr

Body:
I'm creating a form in angular that requires the name field only contain alphanumeric characters and spaces. To do this I use the pattern attribute:

<input type="text" class="form-control" placeholder="Name" name="Name" [(ngModel)]="name" required pattern="/^[a-z\d-_\s]+$/i" #nameField="ngModel">

and I have the following error message I want to show when the string does not match:

          Only spaces, letters, and numbers are allowed.

However, it seems that even when the string should match the regular expression, I can still see the error message. Any ideas?

Body:
I guess the issue here is that the syntax of regex not correctly formed:

 <form novalidate #f="ngForm" novalidate>
    <input type="text"
    class="form-control"
    placeholder="Name" name="Name"
    [(ngModel)]="name"
    required pattern="^[A-Z\\a-z\\d-_\\s]+$"
    #nameField="ngModel" >
    <div>
      <div *ngIf="nameField.errors?.pattern">
        <p class="has-error">
          Only spaces, letters, and numbers are allowed.
        </p>
        hame: {{nameField.errors | json}}
     </div>
    </div>
  </form>

look at this plunkr


问:
VBA: Cumulative addition of data across columns for a set number of times
I am new to using Excel VBA and I have tried to solve this but can't for the life of me get my head around how to do it.

I have a set of data listed in column A and another set of data listed in Column E.
I would like to calculate and display the following addition of A2 and E2 in Column K. The number of times this would be done is determined by the value displayed in C2, i.e.:

```<code>A2 + E2
A2 + (E2*2)
A2 + (E2*3)
.
.
A2 + (E2*C2)
</code>```

I then would like to display the cumulative addition of A3 and E3 in Column K+3 (three columns along), and A4+E3 in Column K+6, and so on. I would like to repeat this until all rows with numbers in Column A have been dealt with.

Here is an image of what the spreadsheet would look like with the first three columns of calculations filled in (please note a number of columns have been hidden):

Screenshot of spreadsheet with values calculated using formulae

I hope this all makes sense.. And thank you ever so much for your help with this!

答:
Here is the code for others to copy and use:</p>

```<code>Option Explicit

Sub TDatapoints()
    With Worksheets("sheet1")
        With .Cells(2, "k").Resize(.Cells(2, "c").Value2, .Cells(.Rows.Count, "a").End(xlUp).Row - 1)
            .Formula = "=index($a:$a, column(b:b), 1)+index($e:$e, column(b:b), 1)*(row(1:1)-1)"
            .Value = .Value2
        End With
    End With
End Sub
</code>```

Body:
I am new to using Excel VBA and I have tried to solve this but can't for the life of me get my head around how to do it.

I have a set of data listed in column A and another set of data listed in Column E.
I would like to calculate and display the following addition of A2 and E2 in Column K. The number of times this would be done is determined by the value displayed in C2, i.e.:

A2 + E2
A2 + (E2*2)
A2 + (E2*3)
.
.
A2 + (E2*C2)

I then would like to display the cumulative addition of A3 and E3 in Column K+3 (three columns along), and A4+E3 in Column K+6, and so on. I would like to repeat this until all rows with numbers in Column A have been dealt with.

Here is an image of what the spreadsheet would look like with the first three columns of calculations filled in (please note a number of columns have been hidden):

Screenshot of spreadsheet with values calculated using formulae

I hope this all makes sense.. And thank you ever so much for your help with this!

Body:
Here is the code for others to copy and use:

Option Explicit

Sub TDatapoints()
    With Worksheets("sheet1")
        With .Cells(2, "k").Resize(.Cells(2, "c").Value2, .Cells(.Rows.Count, "a").End(xlUp).Row - 1)
            .Formula = "=index($a:$a, column(b:b), 1)+index($e:$e, column(b:b), 1)*(row(1:1)-1)"
            .Value = .Value2
        End With
    End With
End Sub


问:
Laravel 5.4: Storing the 'Where' clause in a variable
I want to write a dynamic update query in Laravel which accepts arguments and can be used in whole project.

Following is my Controller function:

```<code>public function editquery(Request $request)
    {

    $city_id   = $request->input('city_id');
    $city_name = $request->input('city_name');

    $tbl  = 'city';
    $data = ['city_name'=>$city_name];
    $wher = ('city_id',1);

    General_model::editrecord($data,$wher,$tbl);

    return redirect()->action('Admin_controller@cities_page')->with('status','Record Updated Successfully!');;

    }
</code>```

Below is my Model function:

```<code>public static function editrecord($data,$wher,$tbl)
    {
      return DB::table($tbl)->where($wher)->update($data);
    }
</code>```

The only problem here is that I cannot store the value ('city_id',1) in the $wher variable. This is the screenshot of the error:
link to the image file

Is there any other way to do this. Please Help.

答:
The where method accepts an array of conditions.

```<code>$table  = 'city';
$conditions = [
    ['city_id', '=', '1']
];
$data = ['city_name' => $city_name];

General_model::editRecord($table, $conditions, $data);

// In your model

public static function editRecord($table, $conditions, $data)
{
    return DB::table($table)->where($conditions)->update($data);
}
</code>```

You can also set multiple conditions.

```<code>$conditions = [
    ['city_id', '=', '1'],
    ['test', '=', 'test'],
];
</code>```

Edit

This is the default where method

```<code>where($column, $operator = null, $value = null, $boolean = 'and')
</code>```

Setting the fourth parameter to or will make the condition orWhere.

Example

```<code>$conditions = [
    ['city_id', '=', '1'],
    ['test', '=', 'test', 'or'],
];
</code>```

Body:
I want to write a dynamic update query in Laravel which accepts arguments and can be used in whole project.

Following is my Controller function:

public function editquery(Request $request)
    {

    $city_id   = $request->input('city_id');
    $city_name = $request->input('city_name');

    $tbl  = 'city';
    $data = ['city_name'=>$city_name];
    $wher = ('city_id',1);

    General_model::editrecord($data,$wher,$tbl);

    return redirect()->action('Admin_controller@cities_page')->with('status','Record Updated Successfully!');;

    }

Below is my Model function:

public static function editrecord($data,$wher,$tbl)
    {
      return DB::table($tbl)->where($wher)->update($data);
    }

The only problem here is that I cannot store the value ('city_id',1) in the $wher variable. This is the screenshot of the error:
link to the image file

Is there any other way to do this. Please Help.

Body:
The where method accepts an array of conditions.

$table  = 'city';
$conditions = [
    ['city_id', '=', '1']
];
$data = ['city_name' => $city_name];

General_model::editRecord($table, $conditions, $data);

// In your model

public static function editRecord($table, $conditions, $data)
{
    return DB::table($table)->where($conditions)->update($data);
}

You can also set multiple conditions.

$conditions = [
    ['city_id', '=', '1'],
    ['test', '=', 'test'],
];

Edit

This is the default where method

where($column, $operator = null, $value = null, $boolean = 'and')

Setting the fourth parameter to or will make the condition orWhere.

Example

$conditions = [
    ['city_id', '=', '1'],
    ['test', '=', 'test', 'or'],
];


问:
Printing an arraylist with an enhanced foor loop - error: cannot find symbol and variable already defined in method
I am new to java and am trying to write a method that will print out an ArrayList using an enhanced for loop. Whenever I compile, the fore loop gives me the following errors:

error: cannot find symbol

error: variable list2 is already defined in
     method printLists(ArrayList,ArrayList)
           for(String list2: list)

```<code>public static void printLists(ArrayList <String> list1, ArrayList <String> list2 )
{
    System.out.println("list1.txt contains:");
    for(String list1: list)
        System.out.println(list1+ " ");

    System.out.println("list2.txt contains:");
    for(String list2: list)
        System.out.println(list2+ " ");
}
</code>```

Can someone please explain to me what these errors mean?

答:
The use of the for-each loop is incorrect:

```<code>for(String list1: list)
</code>```

Two problems with this line:

As error says you are trying to define a new variable names list1 of type String but you already have such a variable name in the scope.

There is nothing defined as list. Basically the syntax is that: for(#item : #collection)

You are looking for something like

```<code>for(String item : list1)
</code>```

Read more on How does the Java 'for each' loop work?

A nicer way to print list will be to use String.join as seen here

```<code>System.out.println(String.join(" ", list1));
</code>```

Body:
I am new to java and am trying to write a method that will print out an ArrayList using an enhanced for loop. Whenever I compile, the fore loop gives me the following errors:

error: cannot find symbol

error: variable list2 is already defined in
     method printLists(ArrayList,ArrayList)
           for(String list2: list)

public static void printLists(ArrayList <String> list1, ArrayList <String> list2 )
{
    System.out.println("list1.txt contains:");
    for(String list1: list)
        System.out.println(list1+ " ");

    System.out.println("list2.txt contains:");
    for(String list2: list)
        System.out.println(list2+ " ");
}

Can someone please explain to me what these errors mean?

Body:
The use of the for-each loop is incorrect:

for(String list1: list)

Two problems with this line:

As error says you are trying to define a new variable names list1 of type String but you already have such a variable name in the scope.

There is nothing defined as list. Basically the syntax is that: for(#item : #collection)

You are looking for something like

for(String item : list1)

Read more on How does the Java 'for each' loop work?

A nicer way to print list will be to use String.join as seen here

System.out.println(String.join(" ", list1));


问:
InsertionSort on Linked List , with Data from text file. Java
I'm doing insertion sort with my Linked List, and I have faced an issue.

My Data file:

```<code>Myjob 66
Junk   17
Fun    25
Vital       99
Important   96
MoreFun    28
Work      69
Assignment  44
</code>```

Here is my code for Insertion Sort

```<code>public Node insertSort(Node node){
   Node sortedNode = null;
   while(node != null){
    Node current = node;
    node = node.next;
    Node x;
    Node previous = null;
    for(x = sortedNode; x != null; x = x.next){
        if(current.getData().getNum() > x.getData().getNum()){
                break;
         }
         previous = x;
    }
    if(previous == null){
          current.next = sortedNode;
          sortedNode = current;
    }
    else{
       current.next = previous.next;
       previous.next = current;
    }
  }
   sortedNode=head;
  return sortedNode; }
</code>```

My currently output:

```<code>Name = Myjob            Priority=66
Name = Assignment            Priority=44
Name = MoreFun            Priority=28
Name = Fun            Priority=25
Name = Junk            Priority=17
null
</code>```

they skip whatever greater than 66. Do anyone have any ideas how to fix this issue, so it can display from 99 down to 17? I tried rearranging the order in the text file a little bit, with the highest first. then the program can perform sorting from 99 back to 17 perfectly. But with the original order, my program just can perform sorting from 66 to lowest. I don't know why, and how to fix it? Please help.  I'm very new in Java. Thank you so much.

My Data Class

```<code>public class Data {

private String name;
private int num;

public Data(){
}

public Data(String name,int num){
    this.name=name;
    this.num=num;
}

public String getName(){
    return name;
}

public void setName(String name){
    this.name=name;
}

public int getNum(){
    return num;
}

public void setNume(int num){
    this.num=num;
}

public String toString()
{
    return "Name = " + name + "            Priority=" + num ;
}

}
</code>```

Here is my LinkedList Class:

```<code>public class LinkedList {
Node head;
Node prev;
Node cur;

public LinkedList(){

}

public LinkedList(Node head){
    head = null;
}

//getter to get head
public Node gethead(){
    return head;
}

public void printLinkedList(){
    System.out.println(head);
}

public void initializeLL(){
    Node currentNode = head;
    try
    {
        File file = new File("Asg2Data.txt");
        Scanner sc = new Scanner(file);
        while (sc.hasNext())
        {
            Data d = new Data(sc.next(), sc.nextInt());
            Node n = new Node(d);

            if(currentNode == null){
                currentNode = n;
                head = n;
            }else{
                currentNode.setNext(n);
                currentNode = n;
            }
        }
        sc.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

public static void main(String[] args) throws FileNotFoundException{

        LinkedList l1 = new LinkedList();
        l1.initializeLL();
        l1.insertSort(l1.head);
        l1.printLinkedList();
        System.out.println("************");
}
}
</code>```

Here is my Node Class:

```<code>public class Node{
Data dt;
Node next;

public Node(){

}
public Node(Data dt){
    this.dt=dt;
}

public Node getNext(){
    return next;
}

public void setNext(Node next){
    this.next=next;
}

public Data getData(){
    return dt;
}

public void setData(Data dt){
    this.dt=dt;
}

public String toString()
{
    StringBuilder sb = new StringBuilder();
    sb.append(dt).append(System.getProperty("line.separator"));
    sb.append(next).append(System.getProperty("line.separator"));

    return sb.toString();

}
}
</code>```

The insertionSort method is inside the LinkedList Class.

答:
There are a couple of things going on here. Firstly you have some bugs in your code like returning head which has not been updated. This can easily explain the behaviour you are seeing, by starting the iteration halfway through the list.

More importantly this does not seem to be an implementation of insertion sort to me. Insertion sort is done by inserting into an already sorted list at the correct point. So would look like:

```<code>sortedList Sort(unsortedlist):
   sortedList = []
   foreach item in unsortedlist:
     sortedList.InsertAtTheRighPlace(item)
   return sortedList
</code>```

Body:
I'm doing insertion sort with my Linked List, and I have faced an issue.

My Data file:

Myjob 66
Junk   17
Fun    25
Vital       99
Important   96
MoreFun    28
Work      69
Assignment  44

Here is my code for Insertion Sort

public Node insertSort(Node node){
   Node sortedNode = null;
   while(node != null){
    Node current = node;
    node = node.next;
    Node x;
    Node previous = null;
    for(x = sortedNode; x != null; x = x.next){
        if(current.getData().getNum() > x.getData().getNum()){
                break;
         }
         previous = x;
    }
    if(previous == null){
          current.next = sortedNode;
          sortedNode = current;
    }
    else{
       current.next = previous.next;
       previous.next = current;
    }
  }
   sortedNode=head;
  return sortedNode; }

My currently output:

Name = Myjob            Priority=66
Name = Assignment            Priority=44
Name = MoreFun            Priority=28
Name = Fun            Priority=25
Name = Junk            Priority=17
null

they skip whatever greater than 66. Do anyone have any ideas how to fix this issue, so it can display from 99 down to 17? I tried rearranging the order in the text file a little bit, with the highest first. then the program can perform sorting from 99 back to 17 perfectly. But with the original order, my program just can perform sorting from 66 to lowest. I don't know why, and how to fix it? Please help.  I'm very new in Java. Thank you so much.

My Data Class

public class Data {

private String name;
private int num;

public Data(){
}

public Data(String name,int num){
    this.name=name;
    this.num=num;
}

public String getName(){
    return name;
}

public void setName(String name){
    this.name=name;
}

public int getNum(){
    return num;
}

public void setNume(int num){
    this.num=num;
}

public String toString()
{
    return "Name = " + name + "            Priority=" + num ;
}

}

Here is my LinkedList Class:

public class LinkedList {
Node head;
Node prev;
Node cur;

public LinkedList(){

}

public LinkedList(Node head){
    head = null;
}

//getter to get head
public Node gethead(){
    return head;
}

public void printLinkedList(){
    System.out.println(head);
}

public void initializeLL(){
    Node currentNode = head;
    try
    {
        File file = new File("Asg2Data.txt");
        Scanner sc = new Scanner(file);
        while (sc.hasNext())
        {
            Data d = new Data(sc.next(), sc.nextInt());
            Node n = new Node(d);

            if(currentNode == null){
                currentNode = n;
                head = n;
            }else{
                currentNode.setNext(n);
                currentNode = n;
            }
        }
        sc.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

public static void main(String[] args) throws FileNotFoundException{

        LinkedList l1 = new LinkedList();
        l1.initializeLL();
        l1.insertSort(l1.head);
        l1.printLinkedList();
        System.out.println("************");
}
}

Here is my Node Class:

public class Node{
Data dt;
Node next;

public Node(){

}
public Node(Data dt){
    this.dt=dt;
}

public Node getNext(){
    return next;
}

public void setNext(Node next){
    this.next=next;
}

public Data getData(){
    return dt;
}

public void setData(Data dt){
    this.dt=dt;
}

public String toString()
{
    StringBuilder sb = new StringBuilder();
    sb.append(dt).append(System.getProperty("line.separator"));
    sb.append(next).append(System.getProperty("line.separator"));

    return sb.toString();

}
}

The insertionSort method is inside the LinkedList Class.

Body:
There are a couple of things going on here. Firstly you have some bugs in your code like returning head which has not been updated. This can easily explain the behaviour you are seeing, by starting the iteration halfway through the list.

More importantly this does not seem to be an implementation of insertion sort to me. Insertion sort is done by inserting into an already sorted list at the correct point. So would look like:

sortedList Sort(unsortedlist):
   sortedList = []
   foreach item in unsortedlist:
     sortedList.InsertAtTheRighPlace(item)
   return sortedList