问:
bug-tracker and wiki for project specifications

SHORT QUESTION

If you want to skip the details below, here's the short question:

I want to know if you keep your app's specifications similarly, in a bugtracker + a wiki and how do you split the information for good management. I look for a simple solution or just a point to start.

DETAILS

I need to keep track of the features for a web app that I want to build. So, I've used MediaWiki to gather a list of features.

For each feature, I have a wiki page where I include functional specs, technical specs and various related brainstormings in FreeMind format or plain text. Also, I include a series of open-questions related to it as TODOs and lots of images for various use cases. I found the wiki to be an excellent place where to keep all these.

I have a page in the wiki with all features transcluded manually so I can see them all in one page, in a specific format.
I also have a page in the wiki where I state what's the goal for v1.0, and a manually transcluded list of features for this version.

In the bug tracker(I use ClockingIT), I want to keep track of the tasks, bugs, etc. in order to build version 1.0 of the product.

ISSUE

Since I keep all features(well, the major features at least) in the wiki, I now feel the need to duplicate them in the bug tracker. Also, after brainstorming on V1.0, I realized there are many smaller features(that are too small to include in the wiki) that I'll need to keep track of in the bug tracker.

The problem is that I end up with 2 systems that will keep and manage the set of features and lots of duplicates will appear, like:

which features get in V1.0 -> this exists in the wiki as a page and the bugtracker keeps a milestone for this; moving a feature from v1.0 to another version, will mean to update both the bugtracker and the wiki

in the bugtracker I add comments as logs for what I do while working on the feature, so the wiki will get deprecated because some part of the brainstorming moves into the bugtracker

the wiki will tend to contain the major features while the bugtracker will contain minor features(like add a button to show/hide a section or something)...but the limit between major and minor features is very subjective and will tend to get messy so I'll have a hard time searching for a feature - I'll have to search in both wiki and bugtracker or I'll have to remember if it was a major or a minor feature

QUESTION

Since I need to keep the features in the wiki because it is an excellent tool for brainstorming, information keeping, etc. what should I include in the bugtracker? How can I efficiently separate these two tools' functionality so they integrate well with each-other and I don't get to duplicate any(or small amount of) data?

Thank you!

答:
I use something mixed. On the wiki, there is a requirements page (among other pages), which describes the features and delivery data. Some features has separated topics where design/implementation details are explained. The requirements topic includes links to bugs with a short description of the bug/feature. Not all features are reflected as bugs. All bugs are listed in the current release section, if they are planned to be fixed in that release. A separated link goes to bug-tracking system to show all the bugs for the product (there are many products in the bug tracker). So:

all features, bug fixes are listed on the requirements page under a particular release;

bug tracking system contains bugs found during testing;

there is no exact definition which requests go to the bug tracker and which don't. An external reviewer may report feature requests as tickets in the bug tracker.

the key point is to keep all the requirements together and organized per release.

Maybe there are better ways to organize things, but this one is the simplest to me, and doesn't require lots of time.


来源: stackexchange

问:
XSLT: How to update element from other xml document?
I need to update an element, BrightcoveVideoID in an xml document by matching a different element in another xml document. The common element is called LegacyId.

The original xml has 10 items (2 items are shown here) Each item is enclosed in tags, PubFactoryMetadata. Each PubFactoryMetadata tag set has a LegacyID.

```<code><?xml version="1.0" encoding="UTF-8"?>
<Content>
    <PubFactoryMetadata>
        <RSuite_Id>W1735_XYZ.xml</RSuite_Id>
        <regular_title>Abdominal Aortic Aneurysm</regular_title>
        <content_type>Video</content_type>
        <content_type_subtype>Classic Patient Ed</content_type_subtype>
        <LegacyId>W1735 </LegacyId>
        <BrightcoveVideoID>W1735</BrightcoveVideoID>
    </PubFactoryMetadata>

    <PubFactoryMetadata>
        <file>videos-v2_W1739_Metadata_es.xml</file>
        <RSuite_Id>W1739_XYZ.xml</RSuite_Id>
        <regular_title>Abdominal Aortic Aneurysm</regular_title>
        <content_type>Video</content_type>
        <content_type_subtype>Classic Patient Ed</content_type_subtype>
        <LegacyId>W1739</LegacyId>
        <BrightcoveVideoID>W1739</BrightcoveVideoID>
    </PubFactoryMetadata>
</Content>
</code>```

The Update file has a LegacyId and BrightcoveVideoID. I need to match the LegacyId element in the original and the update and then update copy the BrightcoveVideoID to the original.

```<code><?xml version="1.0" encoding="UTF-8"?>
<Content>
   <PubFactoryMetadata>
       <LegacyId>W1735_testering</LegacyId>
       <BrightcoveVideoID>66063558001</BrightcoveVideoID>
   </PubFactoryMetadata>
   <PubFactoryMetadata>
        <LegacyId>W1739</LegacyId>
        <BrightcoveVideoID>66063562001</BrightcoveVideoID>
    </PubFactoryMetadata>
    <PubFactoryMetadata>
        <LegacyId>K1892</LegacyId>
        <BrightcoveVideoID>5273514858001</BrightcoveVideoID>
    </PubFactoryMetadata>
</Content>
</code>```

The desired output is to have each PubFactoryMetadata item set is to have the BrightcoveVideoID updated from the update file.

```<code><Content>
<PubFactoryMetadata>
<RSuite_Id>W1735_XYZ.xml</RSuite_Id>
        <regular_title>Abdominal Aortic Aneurysm</regular_title>
        <content_type>Video</content_type>
         <content_type_subtype>Classic Patient Ed</content_type_subtype>
        <LegacyId>W1735</LegacyId>
        <BrightcoveVideoID>66063558001</BrightcoveVideoID>
    </PubFactoryMetadata>

<PubFactoryMetadata>
    <file>videos-v2_W1739_Metadata_es.xml</file>
    <RSuite_Id>W1739_XYZ.xml</RSuite_Id>
    <regular_title>Abdominal Aortic Aneurysm</regular_title>
    <content_type>Video</content_type>
    <content_type_subtype>Classic Patient Ed</content_type_subtype>
    <LegacyId>W1739</LegacyId>
    <BrightcoveVideoID>66063562001</BrightcoveVideoID>
</Content>
</code>```

Here is my XSLT

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs" version="2.0">

    <!-- fileName = update information file name
     updates = document to be updated -->
    <xsl:param name="fileName" select="'PF_Update.xml'"/>
    <xsl:param name="updates" select="document($fileName)"/>

    <!-- Update_Data = orginal node tree -->
    <xsl:variable name="Update_BrightCoveId"       select="$updates/Content/PubFactoryMetadata/BrightcoveVideoID"/>

<!--Identity -->
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<!-- In the original match -->
<xsl:template match="PubFactoryMetadata">

    <xsl:copy>
        LegacyId: <xsl:value-of select="LegacyId"/>

        <xsl:apply-templates select="$Update_BrightCoveId" />

    </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
</code>```

I've tried several examples but I haven't been able to figure out how to match one LegacyID and then update the BrightCoveId in the original to a result set.

答:
First define a key that enables you to find things quickly in your lookup document:

```<code><xsl:key name="lookup" match="PubFactoryMetadata" use="LegacyID"/>
</code>```

Then define your template rule like this:

```<code><xsl:template match="BrightcoveVideoID">
  <xsl:copy>
    <xsl:value-of
         select="key('lookup', ../LegacyID, document($filename))
                 /BrightcoveVideoID"/>
  </xsl:copy>
</xsl:template>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to update an element, BrightcoveVideoID in an xml document by matching a different element in another xml document. The common element is called LegacyId.

The original xml has 10 items (2 items are shown here) Each item is enclosed in tags, PubFactoryMetadata. Each PubFactoryMetadata tag set has a LegacyID.

<?xml version="1.0" encoding="UTF-8"?>
<Content>
    <PubFactoryMetadata>
        <RSuite_Id>W1735_XYZ.xml</RSuite_Id>
        <regular_title>Abdominal Aortic Aneurysm</regular_title>
        <content_type>Video</content_type>
        <content_type_subtype>Classic Patient Ed</content_type_subtype>
        <LegacyId>W1735 </LegacyId>
        <BrightcoveVideoID>W1735</BrightcoveVideoID>
    </PubFactoryMetadata>

    <PubFactoryMetadata>
        <file>videos-v2_W1739_Metadata_es.xml</file>
        <RSuite_Id>W1739_XYZ.xml</RSuite_Id>
        <regular_title>Abdominal Aortic Aneurysm</regular_title>
        <content_type>Video</content_type>
        <content_type_subtype>Classic Patient Ed</content_type_subtype>
        <LegacyId>W1739</LegacyId>
        <BrightcoveVideoID>W1739</BrightcoveVideoID>
    </PubFactoryMetadata>
</Content>

The Update file has a LegacyId and BrightcoveVideoID. I need to match the LegacyId element in the original and the update and then update copy the BrightcoveVideoID to the original.

<?xml version="1.0" encoding="UTF-8"?>
<Content>
   <PubFactoryMetadata>
       <LegacyId>W1735_testering</LegacyId>
       <BrightcoveVideoID>66063558001</BrightcoveVideoID>
   </PubFactoryMetadata>
   <PubFactoryMetadata>
        <LegacyId>W1739</LegacyId>
        <BrightcoveVideoID>66063562001</BrightcoveVideoID>
    </PubFactoryMetadata>
    <PubFactoryMetadata>
        <LegacyId>K1892</LegacyId>
        <BrightcoveVideoID>5273514858001</BrightcoveVideoID>
    </PubFactoryMetadata>
</Content>

The desired output is to have each PubFactoryMetadata item set is to have the BrightcoveVideoID updated from the update file.

<Content>
<PubFactoryMetadata>
<RSuite_Id>W1735_XYZ.xml</RSuite_Id>
        <regular_title>Abdominal Aortic Aneurysm</regular_title>
        <content_type>Video</content_type>
         <content_type_subtype>Classic Patient Ed</content_type_subtype>
        <LegacyId>W1735</LegacyId>
        <BrightcoveVideoID>66063558001</BrightcoveVideoID>
    </PubFactoryMetadata>

<PubFactoryMetadata>
    <file>videos-v2_W1739_Metadata_es.xml</file>
    <RSuite_Id>W1739_XYZ.xml</RSuite_Id>
    <regular_title>Abdominal Aortic Aneurysm</regular_title>
    <content_type>Video</content_type>
    <content_type_subtype>Classic Patient Ed</content_type_subtype>
    <LegacyId>W1739</LegacyId>
    <BrightcoveVideoID>66063562001</BrightcoveVideoID>
</Content>

Here is my XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs" version="2.0">

    <xsl:param name="fileName" select="'PF_Update.xml'"/>
    <xsl:param name="updates" select="document($fileName)"/>

    <xsl:variable name="Update_BrightCoveId"       select="$updates/Content/PubFactoryMetadata/BrightcoveVideoID"/>

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="PubFactoryMetadata">

    <xsl:copy>
        LegacyId: <xsl:value-of select="LegacyId"/>

        <xsl:apply-templates select="$Update_BrightCoveId" />

    </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

I've tried several examples but I haven't been able to figure out how to match one LegacyID and then update the BrightCoveId in the original to a result set.

Body:
First define a key that enables you to find things quickly in your lookup document:

<xsl:key name="lookup" match="PubFactoryMetadata" use="LegacyID"/>

Then define your template rule like this:

<xsl:template match="BrightcoveVideoID">
  <xsl:copy>
    <xsl:value-of
         select="key('lookup', ../LegacyID, document($filename))
                 /BrightcoveVideoID"/>
  </xsl:copy>
</xsl:template>


问:
How to rewrite qi parsers with qi::_1/qi::_N in x3?
Let's say we want to parse an inner product expression and get the result.

```<code>"SUM({1, 2, 3} .* {4, 5, 6})"
</code>```

qi::_1 and qi::_2 are very convenient to reference the ith attributes in the parser.

```<code>void Test(std::string const& input) {
    qi::rule<decltype(boost::begin(input)), int(), qi::ascii::space_type> ruleSum =
        (
            qi::lit("SUM") >> '(' >>
            '{' >> (qi::int_ % ',') >> '}' >>
            ".*" >>
            '{' >> (qi::int_ % ',') >> '}' >>
            ')'
        )[qi::_pass=phx::bind(
            [](std::vector<int> const& vec1, std::vector<int> const& vec2, int& result) {
                if(vec1.size() != vec2.size())
                    return false;
                result = std::inner_product(boost::begin(vec1), boost::end(vec1), boost::begin(vec2), 0);
                return true;
            },
            qi::_1, qi::_2, qi::_val
        )];
    int attr = 0;
    if( qi::phrase_parse(boost::begin(input), boost::end(input), ruleSum >> qi::eoi, qi::ascii::space, attr) ) {
        std::cout<<"Match! result = "<<attr<<std::endl;
    } else {
        std::cout<<"Not match!"<<std::endl;
    }
}
</code>```

In spirit x3, there are no such qi::_1 ... qi::_N. Should I use a pair of vectors as the attribute? What is the recommended way to parse something like this inner product?

```<code>namespace inner_product {
    x3::rule<struct idInnerProduct, int> const ruleInnerProduct("InnerProduct");
    auto const ruleInnerProduct_def =
        (
            x3::rule<struct _, std::pair<std::vector<int>, std::vector<int>>>{} =
                x3::lit("SUM") >> '(' >>
                '{' >> (x3::int_ % ',') >> '}' >>
                ".*" >>
                '{' >> (x3::int_ % ',') >> '}' >>
                ')'
        )[([](auto& ctx){
            if(_attr(ctx).first.size() != _attr(ctx).second.size()) {
                _pass(ctx) = false;
            } else {
                x3::_val(ctx) = std::inner_product(
                    boost::begin(x3::_attr(ctx).first),
                    boost::end(x3::_attr(ctx).first),
                    boost::begin(x3::_attr(ctx).second),
                    0
                );
            }
        })];
    BOOST_SPIRIT_DEFINE(ruleInnerProduct)
}
</code>```

答:
The attribute is a fusion sequence. Its members are vector<int>.

A fusion sequence is not a pair, so you can't use .first or .second.

I'd write:

```<code>void Test(std::string const& input) {
    namespace x3 = boost::spirit::x3;

    auto ruleSum = x3::rule<struct _, int> {} =
        (
            x3::lit("SUM") >> '(' >>
            '{' >> (x3::int_ % ',') >> '}' >> ".*" >>
            '{' >> (x3::int_ % ',') >> '}' >>
            ')'
        )[( [](auto& ctx) {
                using boost::fusion::at_c;
                // dissect context
                auto& pass = x3::_pass(ctx);
                auto& result = x3::_val(ctx);
                std::vector<int> const& vec1 = at_c<0>(x3::_attr(ctx));
                std::vector<int> const& vec2 = at_c<1>(x3::_attr(ctx));

                // do the work
                pass = (vec1.size() == vec2.size());
                if (pass)
                    result = std::inner_product(boost::begin(vec1), boost::end(vec1), boost::begin(vec2), 0);
            })
        ];

    int attr = 0;
    if( x3::phrase_parse(boost::begin(input), boost::end(input), ruleSum >> x3::eoi, x3::ascii::space, attr) ) {
        std::cout<<"Match! result = "<<attr<<std::endl;
    } else {
        std::cout<<"Not match!"<<std::endl;
    }
}
</code>```

See it Live On Coliru

Prints:

```<code>Match! result = 32
</code>```

Body:
Let's say we want to parse an inner product expression and get the result.

"SUM({1, 2, 3} .* {4, 5, 6})"

qi::_1 and qi::_2 are very convenient to reference the ith attributes in the parser.

void Test(std::string const& input) {
    qi::rule<decltype(boost::begin(input)), int(), qi::ascii::space_type> ruleSum =
        (
            qi::lit("SUM") >> '(' >>
            '{' >> (qi::int_ % ',') >> '}' >>
            ".*" >>
            '{' >> (qi::int_ % ',') >> '}' >>
            ')'
        )[qi::_pass=phx::bind(
            [](std::vector<int> const& vec1, std::vector<int> const& vec2, int& result) {
                if(vec1.size() != vec2.size())
                    return false;
                result = std::inner_product(boost::begin(vec1), boost::end(vec1), boost::begin(vec2), 0);
                return true;
            },
            qi::_1, qi::_2, qi::_val
        )];
    int attr = 0;
    if( qi::phrase_parse(boost::begin(input), boost::end(input), ruleSum >> qi::eoi, qi::ascii::space, attr) ) {
        std::cout<<"Match! result = "<<attr<<std::endl;
    } else {
        std::cout<<"Not match!"<<std::endl;
    }
}

In spirit x3, there are no such qi::_1 ... qi::_N. Should I use a pair of vectors as the attribute? What is the recommended way to parse something like this inner product?

namespace inner_product {
    x3::rule<struct idInnerProduct, int> const ruleInnerProduct("InnerProduct");
    auto const ruleInnerProduct_def =
        (
            x3::rule<struct _, std::pair<std::vector<int>, std::vector<int>>>{} =
                x3::lit("SUM") >> '(' >>
                '{' >> (x3::int_ % ',') >> '}' >>
                ".*" >>
                '{' >> (x3::int_ % ',') >> '}' >>
                ')'
        )[([](auto& ctx){
            if(_attr(ctx).first.size() != _attr(ctx).second.size()) {
                _pass(ctx) = false;
            } else {
                x3::_val(ctx) = std::inner_product(
                    boost::begin(x3::_attr(ctx).first),
                    boost::end(x3::_attr(ctx).first),
                    boost::begin(x3::_attr(ctx).second),
                    0
                );
            }
        })];
    BOOST_SPIRIT_DEFINE(ruleInnerProduct)
}

Body:
The attribute is a fusion sequence. Its members are vector<int>.

A fusion sequence is not a pair, so you can't use .first or .second.

I'd write:

void Test(std::string const& input) {
    namespace x3 = boost::spirit::x3;

    auto ruleSum = x3::rule<struct _, int> {} =
        (
            x3::lit("SUM") >> '(' >>
            '{' >> (x3::int_ % ',') >> '}' >> ".*" >>
            '{' >> (x3::int_ % ',') >> '}' >>
            ')'
        )[( [](auto& ctx) {
                using boost::fusion::at_c;
                // dissect context
                auto& pass = x3::_pass(ctx);
                auto& result = x3::_val(ctx);
                std::vector<int> const& vec1 = at_c<0>(x3::_attr(ctx));
                std::vector<int> const& vec2 = at_c<1>(x3::_attr(ctx));

                // do the work
                pass = (vec1.size() == vec2.size());
                if (pass)
                    result = std::inner_product(boost::begin(vec1), boost::end(vec1), boost::begin(vec2), 0);
            })
        ];

    int attr = 0;
    if( x3::phrase_parse(boost::begin(input), boost::end(input), ruleSum >> x3::eoi, x3::ascii::space, attr) ) {
        std::cout<<"Match! result = "<<attr<<std::endl;
    } else {
        std::cout<<"Not match!"<<std::endl;
    }
}

See it Live On Coliru

Prints:

Match! result = 32


问:
Using MongoDB locally (electron)?
I need to store some data as part of my electron application. I know how to set up a REST API, and serve my application like so. However, is it also possible to use (e.g.) MongoDB locally, and implement something similar to a REST API locally? I would like to not assume an internet connection for this project.</p>

答:
Yes it is possible, you have nodejs in electron so you can use mongoose:
https://github.com/Automattic/mongoose

But in this case every person who use your application have to install mongodb in his machine.

Title: Using MongoDB locally (electron)?


问:
Creating submodule in gfortran
This is code:

```<code>Program Submodules_0

Use Const_Var
Use Baz_Var

Implicit none

Call Pro_Baz

End Program Submodules_0

Module Const_Var

Implicit none

Integer::i
Integer,parameter::Br_NaNi=3
Real,parameter::S_baz=3.15E+06
Real,parameter,dimension(Br_NaNi)::V_baz=[110.0E+03,20.0E+03,0.40E+03]
Real,dimension(Br_NaNi)::I_baz,Z_baz,Y_baz

End module Const_Var

Module Baz_Var

Use Const_Var

Implicit none

Interface

Module subroutine Pro_Baz

End subroutine Pro_Baz

End interface

End module Baz_Var

Submodule(Baz_Var) Baz_Var_Main

Contains

Subroutine Pro_Baz

Implicit none

Do concurrent(i=1:Br_NaNi)

   I_baz(i)=(S_baz)/((sqrt(3.0))*V_baz(i))
   Z_baz(i)=(V_baz(i)**2)/(S_baz)
   Y_baz(i)=1/(Z_baz(i))

End Do

Return
End Subroutine Pro_Baz

End submodule Baz_Var_Main
</code>```

I want to create submodules which contains subroutine Pro_Baz and when I start this program I got a this message:

Error: Unclassifiable statement

The message was on this line: Module subroutine Pro_Baz

What is wrong with this program?

答:
Compiler support for submodules was introduced in gfortran in version 6.0.

Within an interface block, an interface body starting module subroutine ... is specific to the submodule facility.  A complaint about an unclassifiable statement for this interface body is, then, an indication of a lack of submodule understanding.  The compiler doesn't wait to complain on reaching a submodule statement.

The version of gcc/gfortran bundled with Code::Blocks 16.01 appears to be 4.9.2.

You will need to install, and configure the IDE to use, a more recent version of the compiler.  This is whether you are using the Windows version with a bundled default compiler, or a version on any OS with a separate compiler installation.

Title: Creating submodule in gfortran

Body:
This is code:

Program Submodules_0

Use Const_Var
Use Baz_Var

Implicit none

Call Pro_Baz

End Program Submodules_0

Module Const_Var

Implicit none

Integer::i
Integer,parameter::Br_NaNi=3
Real,parameter::S_baz=3.15E+06
Real,parameter,dimension(Br_NaNi)::V_baz=[110.0E+03,20.0E+03,0.40E+03]
Real,dimension(Br_NaNi)::I_baz,Z_baz,Y_baz

End module Const_Var

Module Baz_Var

Use Const_Var

Implicit none

Interface

Module subroutine Pro_Baz

End subroutine Pro_Baz

End interface

End module Baz_Var

Submodule(Baz_Var) Baz_Var_Main

Contains

Subroutine Pro_Baz

Implicit none

Do concurrent(i=1:Br_NaNi)

   I_baz(i)=(S_baz)/((sqrt(3.0))*V_baz(i))
   Z_baz(i)=(V_baz(i)**2)/(S_baz)
   Y_baz(i)=1/(Z_baz(i))

End Do

Return
End Subroutine Pro_Baz

End submodule Baz_Var_Main

I want to create submodules which contains subroutine Pro_Baz and when I start this program I got a this message:

Error: Unclassifiable statement

The message was on this line: Module subroutine Pro_Baz

What is wrong with this program?


问:
SSIS package fails with error "If 64-bit driver not installed, run in 32-bit mode"
I am receiving the following error when trying to run the package from the Integration Services catalog in SSMS. I changed the 64BitRuntime option to FALSE but it still does not work. The error below is followed by an error that a connection cannot be made to my Excel connection manager. Any suggestions?

Package Error: The requested OLE DB provider Microsoft.Jet.OLEDB 4.0
  is not registered. If the 64-bit driver is not installed, run the
  package in 32-bit mode. Error code: 0x00000000

答:
if you are executing the SSIS package from job , there is an option in job configuration a checkbox "enable 32 bit".

OR

if you are executing the SSIS package from BIDS or SSDT , go to project properties=> Configuration => debugging => turn 64BitRuntime from "True" to "False" as it is set to True by default.


问:
Javascript RegExp for matching different values with $ (dollar sign) as part of the string
I'm looking for a way to construct a RegExp object from a user input value that will match against some values which contains a dollar character $ (currency).

As I know this character must be escaped I have issues getting it to work correctly, especially in combination with other operators and characters.

I'm looking for to construct a RegExp that will work based on user input and hence it needs to be dynamic. Trying try to explain the scenario, something in this fashion:

User input: "$50" or "50"

```<code>"$50" // match
"$50 + $5" // match as it matches on "$50"
"$500 + $50" // match as it matches on "$50"
"$500" // should not match
"$5000" // should not match
"$5.50" // should not match
</code>```

user input: "$5000" or "5000"

```<code>"$5000" // match
"$5,000" // match as it resembles the same value
"$5000 + $500" // match
"$5.000" // should not match
"$5000.50" // should not match
</code>```

So basically it should only match the exact user input, with the exception of the dollar character ($), if there's a value that follows it but they are separated by a plus symbol (but still the same string), or if the value has a comma which is commonly used when writing larger numbers (for example 5,000).

Is this possible with a RegExp object?

答:
Converting $ to \$ and adding ,? to userInput value, makes regex pattern

```<code>var userInput = "500000000" ;
if(userInput.substring(0,1) != "$"){userInput = "$"+userInput ;}
var c = userInput.length-2;
for(var i = Math.floor(c/3)*3 ; i>0 ; i-=3){
  userInput = userInput.substring(0,userInput.length-i) + ",?" + userInput.substr(-i) ;
}
userInput = "(?:^|\\b)" + userInput.replace("$","\\\$\?") + "(?=\\s|$)" ;
</code>```

for 5000, out put is:

```<code>\$?5,?000
//updated to
(?:^|\b)\$?5,?000(?=\s|$)
</code>```

see Demo

Updates done:

Changed (?:..) to (?=..) to stop matching after found number

missed assign of replacing of "$" with "\$?" to userInput

Body:
I'm looking for a way to construct a RegExp object from a user input value that will match against some values which contains a dollar character $ (currency).

As I know this character must be escaped I have issues getting it to work correctly, especially in combination with other operators and characters.

I'm looking for to construct a RegExp that will work based on user input and hence it needs to be dynamic. Trying try to explain the scenario, something in this fashion:

User input: "$50" or "50"

"$50" // match
"$50 + $5" // match as it matches on "$50"
"$500 + $50" // match as it matches on "$50"
"$500" // should not match
"$5000" // should not match
"$5.50" // should not match

user input: "$5000" or "5000"

"$5000" // match
"$5,000" // match as it resembles the same value
"$5000 + $500" // match
"$5.000" // should not match
"$5000.50" // should not match

So basically it should only match the exact user input, with the exception of the dollar character ($), if there's a value that follows it but they are separated by a plus symbol (but still the same string), or if the value has a comma which is commonly used when writing larger numbers (for example 5,000).

Is this possible with a RegExp object?

Body:
Converting $ to \$ and adding ,? to userInput value, makes regex pattern

var userInput = "500000000" ;
if(userInput.substring(0,1) != "$"){userInput = "$"+userInput ;}
var c = userInput.length-2;
for(var i = Math.floor(c/3)*3 ; i>0 ; i-=3){
  userInput = userInput.substring(0,userInput.length-i) + ",?" + userInput.substr(-i) ;
}
userInput = "(?:^|\\b)" + userInput.replace("$","\\\$\?") + "(?=\\s|$)" ;

for 5000, out put is:

\$?5,?000
//updated to
(?:^|\b)\$?5,?000(?=\s|$)

see Demo

Updates done:

Changed (?:..) to (?=..) to stop matching after found number

missed assign of replacing of "$" with "\$?" to userInput


问:
How can I scrape/parse this data using regular expressions?
I'm really a beginner when it comes to regular expressions, and I'm not really sure where to start. I have some html code scraped from a web page and stored in a variable, and it looks something like this:

```<code><thead><tr>
<th></th>
<th>GENERAL INFORMATION</th>
<th></th>
<th>DETAILED DATA</th>
</tr></thead>
<tbody><tr>
<th>ID</th>
<td>123456789ABCD</td>
<th>Field1</th>
<td>6 = (Some-Specification (3 or more details))</td>

</tr></tbody>
<tbody><tr>
<th>AGL</th>
<td>1 - United States ; TH - Some Data</td>
<th>Field2</th>
<td>7 = (Option/Other Option)</td>
</tr></tbody>
<tbody><tr>
<th>MANUFACTURER</th>
<td>2010 SPECIFICATION  (ADSD: HMKC)</td>
<th>Field3</th>

<td>8 = (My Type)</td>
</tr></tbody>
<tbody><tr>
<th>MODEL</th>
<td>6X4 MY-MODEL/SOME_SPECS LONG SPECIFICATION, BLAH</td>
<th>Field4</th>
<td>9 = (STUFF/OTHER STUFF)</td>
</tr></tbody>
<tbody>
</code>```

And then there is more of the same... I would like to parse the data from these cells into variables. (e.g. parse "123456789ABCD" into an ID variable) I'm working in ColdFusion and was thinking of using methods like REFindNoCase, REReplaceNoCase, SpanExcluding... Any idea how I can accomplish this? Or if you're not familiar with ColdFusion, even just the regular expressions necessary to parse this data would be very useful.

答:
Don't use Regex for HTML. It will destroy you.

If you are doing a lot of this you should get an HTML tool such as TagSoup which normalizes the HTML. If you are working with web pages from one site, then you can create an XSLT stylesheet (or a DOM tool using XPath) which extracts the cells you want.

An Xpath for your cell (I have omitted the HTML namespace) could be

```<code>//tbody/tr[1]/td[1]
</code>```

or you may wish to find rows by ID

```<code>//tbody/tr[th='ID']]/td
</code>```

[The HTML looks rather messy - it uses th and td in the same tr which is not idiomatic.]

ContentLicense: CC BY-SA 2.5

Body:
I'm really a beginner when it comes to regular expressions, and I'm not really sure where to start. I have some html code scraped from a web page and stored in a variable, and it looks something like this:

GENERAL INFORMATION

DETAILED DATA

ID
123456789ABCD
Field1
6 = (Some-Specification (3 or more details))

AGL
1 - United States ; TH - Some Data
Field2
7 = (Option/Other Option)

MANUFACTURER
2010 SPECIFICATION  (ADSD: HMKC)
Field3

8 = (My Type)

MODEL
6X4 MY-MODEL/SOME_SPECS LONG SPECIFICATION, BLAH
Field4
9 = (STUFF/OTHER STUFF)

And then there is more of the same... I would like to parse the data from these cells into variables. (e.g. parse "123456789ABCD" into an ID variable) I'm working in ColdFusion and was thinking of using methods like REFindNoCase, REReplaceNoCase, SpanExcluding... Any idea how I can accomplish this? Or if you're not familiar with ColdFusion, even just the regular expressions necessary to parse this data would be very useful.

Body:
Don't use Regex for HTML. It will destroy you.

If you are doing a lot of this you should get an HTML tool such as TagSoup which normalizes the HTML. If you are working with web pages from one site, then you can create an XSLT stylesheet (or a DOM tool using XPath) which extracts the cells you want.

An Xpath for your cell (I have omitted the HTML namespace) could be

//tbody/tr[1]/td[1]

or you may wish to find rows by ID

//tbody/tr[th='ID']]/td

[The HTML looks rather messy - it uses th and td in the same tr which is not idiomatic.]


问:
How to make default Password Reset functionality work in ASP.NET Core
I'm following this Official NET Core tutorial where I've also chosen the Authentication mode as Individual User Accounts. When I try to call ResetPassword Get action method inside the built-in AccountController from a link in the default Index.cshtml view below it, as expected, sends the code parameter to the action method as null. And, as a result, the default error.cshtml page is displayed instead of ResetPassword.cshtml view. Question: How do I call the ResetPassword Get action method so its input parameter code is not null?

Snapshot of Index.cshtml with Reset Password link:

```<code><div class="row">
    <div class="col-md-3">
        <h2>Application uses</h2>
        <ul>
            <li>Sample pages using ASP.NET Core MVC</li>
            <li><a href="http://go.microsoft.com/fwlink/?LinkId=518004">Bower</a> for managing client-side libraries</li>
            <li>Theming using <a href="http://go.microsoft.com/fwlink/?LinkID=398939">Bootstrap</a></li>
            <li><a asp-controller="Account" asp-action="ResetPassword">Reset Password</a></li>
        </ul>
    </div>
    <div class="col-md-3">
        <h2>How to</h2>
        <ul>
....
</div>
</code>```

ResetPassword Action method in AccountController

```<code>[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
    return code == null ? View("Error") : View();
}
</code>```

答:
Under normal use that action expects to have the code bound from the querystring. If you take a look at the ForgotPassword POST action, that has code (commented out by default) that can send a link to the user that includes their id and a uniquely generated code (token).

There's a link in that action to a MS page, which guides you further on setting it up. You can test by writing the callBackUrl to debug if you want, then when you follow that link to reset password it should contain a valid token.

The reset password action then accepts the code, which within Identity will be validated to ensure it's valid.

Body:
I'm following this Official NET Core tutorial where I've also chosen the Authentication mode as Individual User Accounts. When I try to call ResetPassword Get action method inside the built-in AccountController from a link in the default Index.cshtml view below it, as expected, sends the code parameter to the action method as null. And, as a result, the default error.cshtml page is displayed instead of ResetPassword.cshtml view. Question: How do I call the ResetPassword Get action method so its input parameter code is not null?

Snapshot of Index.cshtml with Reset Password link:

Application uses

Sample pages using ASP.NET Core MVC

Bower for managing client-side libraries

Theming using Bootstrap

Reset Password

How to

....

ResetPassword Action method in AccountController

[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
    return code == null ? View("Error") : View();
}


问:
Get Device Owner profile information - Ionic
I would like to get informations concerning phone owner (nation, age, sex etc) to perform an automatic profiling.

I saw there are some opportunities:

In Android there are these plugins:

https://github.com/vliesaputra/DeviceInformationPlugin

https://github.com/loicknuchel/cordova-device-accounts

they both allow to get account info, if everybody then have a google account, I'm wondering if is it possible to query google API to get public profile info, without requiring an authentication. Anybody has experiences in this kind of approach? Maybe also fb can be interrogated in this way

It seems that on iOS there isn't this kind of freedom

Query for all contacts and get the one of the user, I think this is an hit or miss approach and don't know if there exists a way to know if a profile is surely the one of the owner.

Do you have any other experienced approach to perform a transparent user profiling with ionic? I'm wondering how to perform an useful approach both Android on and  on iOS

Thank you

答:
You can get the following information from http://ngcordova.com/docs/plugins/device/

Platform

Version

UUID

Model


问:
MySQL - Join table on column A unless column A = x then join on column b instead
Is it possible to Join a table on a different column if the first column is equal to a specific value.

See below:

tableA

```<code>  .----+-----------------.
  | ID | Name            |
  +----+-----------------+
  |  1 | Name goes here1 |
  |  2 | Name goes here2 |
  |  3 | Name goes here3 |
  |  4 | Name goes here4 |
  .----+-----------------+
</code>```

tableB

```<code>  .----+-----------------+-----------------.
  | ID | id1             | id2             |
  +----+-----------------+-----------------+
  |  1 | ID goes here    | ID goes here    |
  |  2 | ID goes here    | ID goes here    |
  |  3 | ID goes here    | ID goes here    |
  |  4 | ID goes here    | ID goes here    |
  .----+-----------------+-----------------.
</code>```

So for example, I would like to join tableA ON tableA.ID = tableB.id1 UNLESS tableB.id1 = x THEN JOIN ON tableB.id2

答:
You can express this as basic logic in the on clause:

```<code>on (a.id = b.id1 and b.id1 <> x) or
   (a.id = b.id2 and b.id1 = x)
</code>```

The logic is slightly more complicated if x can be NULL, but you can definitely use the same idea.  If the idea is to test for NULL, then an easier way to express the query is:

```<code>on a.id = coalesce(b.id1, b.id2)
</code>```

Body:
Is it possible to Join a table on a different column if the first column is equal to a specific value.

See below:

tableA

  .----+-----------------.
  | ID | Name            |
  +----+-----------------+
  |  1 | Name goes here1 |
  |  2 | Name goes here2 |
  |  3 | Name goes here3 |
  |  4 | Name goes here4 |
  .----+-----------------+

tableB

  .----+-----------------+-----------------.
  | ID | id1             | id2             |
  +----+-----------------+-----------------+
  |  1 | ID goes here    | ID goes here    |
  |  2 | ID goes here    | ID goes here    |
  |  3 | ID goes here    | ID goes here    |
  |  4 | ID goes here    | ID goes here    |
  .----+-----------------+-----------------.

So for example, I would like to join tableA ON tableA.ID = tableB.id1 UNLESS tableB.id1 = x THEN JOIN ON tableB.id2

Body:
You can express this as basic logic in the on clause:

on (a.id = b.id1 and b.id1 <> x) or
   (a.id = b.id2 and b.id1 = x)

The logic is slightly more complicated if x can be NULL, but you can definitely use the same idea.  If the idea is to test for NULL, then an easier way to express the query is:

on a.id = coalesce(b.id1, b.id2)


问:
Make link to Application folder
Sublime Text editor has in DMG file link to Applications dir (blue icons with arrow). It has small size.

How to make such link on my own folder? It must work in all Macs.

答:
Open the terminal, use cd to open the folder where you want to create the symbolic link (this is how that kind of link is called, in case you want to research a bit more about it). Example:

```<code>cd /Users/MyUser/Desktop/
</code>```

Note: In case the path has spaces, write it with backslashes before each space, like that:

```<code>cd /Users/MyUser/Desktop/My\ Folder/
</code>```

Then, use that command to create it:

```<code>ln -s /Applications/ Applications
</code>```

It will create a symbolic link which opens the path /Applications/, which means that it will work in any macOS computer.

Reference:
https://apple.stackexchange.com/a/115648

Title: Make link to Application folder

Body:
Open the terminal, use cd to open the folder where you want to create the symbolic link (this is how that kind of link is called, in case you want to research a bit more about it). Example:

cd /Users/MyUser/Desktop/

Note: In case the path has spaces, write it with backslashes before each space, like that:

cd /Users/MyUser/Desktop/My\ Folder/

Then, use that command to create it:

ln -s /Applications/ Applications

It will create a symbolic link which opens the path /Applications/, which means that it will work in any macOS computer.

Reference:
https://apple.stackexchange.com/a/115648


问:
How can I quote iframe's javascript variable in parent's window
In A.html I open an iframe with B.html in it.

in B.html,I write js:

```<code><script type="javascript">
    var b=0;

   function test(){
       alert(b);
       return b;
   }
</script>
</code>```

so in A.html I want quote the variable b in B.html
I write this:

```<code><script type="javascript">
    var a;

    a=window.frames[0].b;
    alert(a);
</script>
</code>```

but the resault is "undefined";
however,I quote the function test in A.html

```<code><script type="javascript">
    var a;

    a=window.frames[0]. test();
    alert(a);
</script>
</code>```

both the variable a and b could alert correctly

so why the second quote method could not work?

答:
This works for me.

Which browser do you use?
Are you sure that the document inside the frame is already loaded when you access the property?

Body:
In A.html I open an iframe with B.html in it.

in B.html,I write js:

so in A.html I want quote the variable b in B.html
I write this:

but the resault is "undefined";
however,I quote the function test in A.html

both the variable a and b could alert correctly

so why the second quote method could not work?


问:
How to show and hide side menu in angular2
In my application i have to implement hide and show side menu. By default the page menu is open while clicking the toggle menu i have to hide the side menu. How can i implement this.

what i have is:

app.component.html, nav.component.html

        Name

```
</div>
</div>
</p>

<p>Myservice.ts</p>

```export class GlobalService {
public collapse;

constructor() { }

setValue(val: boolean) {
    this.collapse = val;
}

getValue() {
    return this.collapse;
}
```

<p>EDIT</p>

<p>app.component.html</p>

```

```

<p>app.component.ts</p>

```import { GlobalService } from "path";

export class AppComponent {
toggle() {
this.globalService.setValue(false);

 }
}
```

how can i hide this list(in nav.html) while clicking menu toggle (app.compnent.html)? Any help will really appreciable. i am new to angular.

答:
If use of service is not the priority then you can simply maintain simple variable to do this task.

Your app.component.ts

```
<code>

    export class AppComponent {
      showMenu : boolean = true;
    }

</code>
```

Your app.component.html

```<code><div (click)="showMenu = !showMenu" class="menu-toggler sidebar-toggler"><span></span>
</div>
<ul *ngIf="showMenu">
    <!-- used showMenu to hide/show -->
    <li class="nav-item  ">
        <a class="nav-link nav-toggle">
            <i class="icon-diamond"></i>
            <span class="title">Name</span>
            <span class="arrow"></span>
        </a>
    </li>
</ul>
</code>```

hope this helps ...

Body:
In my application i have to implement hide and show side menu. By default the page menu is open while clicking the toggle menu i have to hide the side menu. How can i implement this.

what i have is:

app.component.html, nav.component.html

        Name

Myservice.ts

export class GlobalService {
public collapse;

constructor() { }

setValue(val: boolean) {
    this.collapse = val;
}

getValue() {
    return this.collapse;
}

EDIT

app.component.html

app.component.ts

import { GlobalService } from "path";

export class AppComponent {
toggle() {
this.globalService.setValue(false);

 }
}

how can i hide this list(in nav.html) while clicking menu toggle (app.compnent.html)? Any help will really appreciable. i am new to angular.

Body:
If use of service is not the priority then you can simply maintain simple variable to do this task.

Your app.component.ts

    export class AppComponent {
      showMenu : boolean = true;
    }

Your app.component.html

<div (click)="showMenu = !showMenu" class="menu-toggler sidebar-toggler"><span></span>
</div>
<ul *ngIf="showMenu">
    <!-- used showMenu to hide/show -->
    <li class="nav-item  ">
        <a class="nav-link nav-toggle">
            <i class="icon-diamond"></i>
            <span class="title">Name</span>
            <span class="arrow"></span>
        </a>
    </li>
</ul>

hope this helps ...


问:
Swfit: Firebase DB / Dictionary look for highest Int
I have a Firebase database which looks like in the image

When I get these values in my code via a NSDictionary, I want to check what is the highest integer, so in this case 4.

This is how the NSdictionary looks (I can't do dictionaryName[ 1 ] like when I have an array  to get the value so...):

```<code>  {
   1 =     {
      driverName = chauffeur1;
      latitude = "37.33022769";
      longitude = "-122.03439793";
  };
  4 =     {
      driverName = kees;
  };
}
</code>```

Is there any option in Firebase or in Dictionary's which could help me to get this functional?
I've already looked up some solutions but all of them were not what I was looking for. Maybe someone knows how to?

I'll be glad to know

Edit 1:
The problem is that I get my Dictionary from firebase like this:

```<code>DBProvider.Instance.dbRef.child("driverLocations").observeSingleEvent(of: .value, with: { (snapshot) in
        if let data = snapshot.value as? NSDictionary {
            print(data)
            let keys = data.allKeys
            let sortedKeys = Array(keys).sorted(by: { $0 > $1 }) // highest will be the first
            let highestKey = sortedKeys[0]
        }
    })
</code>```

I can't typ it like:

```<code> if let data = snapshot.value as? NSDictionary[Int: Any]
</code>```

Maybe I'm just a little bit stupid doing it wrong.. Do you know how I can fix it?

Edit 2 (snapshot.value data)

```<code>Optional({
1 =     {
    driverName = chauffeur1;
    latitude = "37.33193453";
    longitude = "-122.03777128";
};
4 =     {
    driverName = kees;
};
})
</code>```

答:
```<code>let dict = ["1": ["driverName": "chauffeur1",
                "latitude": 37.33022769,
                "longitude": -122.03439793],
            "4": ["driverName": "kees"]]

if let maxElememt = dict.max(by: { $0.key<$1.key }) {
    maxElememt.key    // "4"
    maxElememt.value    // ["driverName": "kees"]
}

let maxValue = dict.max{$0.key<$1.key}.map{$0.value}
maxValue   // ["driverName": "kees"]
</code>```

if you need it just sorted by your keys decreasing their value

```<code>let sortedDic = dict.sorted{ $0.key>$1.key }

sortedDic.first          //  (key "4", ["driverName": "kees"])
sortedDic.first?.key     //  "4"
sortedDic.first?.value   // ["driverName": "kees"]
sortedDic.first?.value["driverName"] // "kees"
</code>```

Body:
I have a Firebase database which looks like in the image

When I get these values in my code via a NSDictionary, I want to check what is the highest integer, so in this case 4.

This is how the NSdictionary looks (I can't do dictionaryName[ 1 ] like when I have an array  to get the value so...):

  {
   1 =     {
      driverName = chauffeur1;
      latitude = "37.33022769";
      longitude = "-122.03439793";
  };
  4 =     {
      driverName = kees;
  };
}

Is there any option in Firebase or in Dictionary's which could help me to get this functional?
I've already looked up some solutions but all of them were not what I was looking for. Maybe someone knows how to?

I'll be glad to know

Edit 1:
The problem is that I get my Dictionary from firebase like this:

DBProvider.Instance.dbRef.child("driverLocations").observeSingleEvent(of: .value, with: { (snapshot) in
        if let data = snapshot.value as? NSDictionary {
            print(data)
            let keys = data.allKeys
            let sortedKeys = Array(keys).sorted(by: { $0 > $1 }) // highest will be the first
            let highestKey = sortedKeys[0]
        }
    })

I can't typ it like:

 if let data = snapshot.value as? NSDictionary[Int: Any]

Maybe I'm just a little bit stupid doing it wrong.. Do you know how I can fix it?

Edit 2 (snapshot.value data)

Optional({
1 =     {
    driverName = chauffeur1;
    latitude = "37.33193453";
    longitude = "-122.03777128";
};
4 =     {
    driverName = kees;
};
})

Body:
let dict = ["1": ["driverName": "chauffeur1",
                "latitude": 37.33022769,
                "longitude": -122.03439793],
            "4": ["driverName": "kees"]]

if let maxElememt = dict.max(by: { $0.key<$1.key }) {
    maxElememt.key    // "4"
    maxElememt.value    // ["driverName": "kees"]
}

let maxValue = dict.max{$0.key<$1.key}.map{$0.value}
maxValue   // ["driverName": "kees"]

if you need it just sorted by your keys decreasing their value

let sortedDic = dict.sorted{ $0.key>$1.key }

sortedDic.first          //  (key "4", ["driverName": "kees"])
sortedDic.first?.key     //  "4"
sortedDic.first?.value   // ["driverName": "kees"]
sortedDic.first?.value["driverName"] // "kees"


问:
Get the length of a video in Android
I want to get the length of a saved video from my device. I have tried with MediaMetadataRetriever but my application crashes. I am testing it on Android 6.0 but it is not working at all.

Below is my Activity.

```<code>    public class MainActivity extends AppCompatActivity {

    private static final int PICK_IMAGE_REQUEST = 1; // put it on the top.
    private Button btnOpenGallery;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnOpenGallery = (Button)findViewById(R.id.btnOpenGallery);
        btnOpenGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent();
                intent.setType("video/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            Uri selectedImageUri = data.getData();
            String strPath = selectedImageUri.getPath();
            Log.e("Path is ","===>"+strPath);

            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(strPath); // Enter Full File Path Here
            String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            long timeInmillisec = Long.parseLong(time);
            Log.e("Media duration in ","==>"+timeInmillisec);

        }
    }
}
</code>```

答:
try this one

```<code>MediaPlayer mp = MediaPlayer.create(getActivity(), Uri.parse(Environment.getExternalStorageDirectory() + "/Downloads/" + "vid" + ".mp4")); // Downloads is the folder and vid is video file.
int duration = mp.getDuration();
mp.release();
</code>```

This was worked for me.

Title: Get the length of a video in Android

Body:
I want to get the length of a saved video from my device. I have tried with MediaMetadataRetriever but my application crashes. I am testing it on Android 6.0 but it is not working at all.

Below is my Activity.

    public class MainActivity extends AppCompatActivity {

    private static final int PICK_IMAGE_REQUEST = 1; // put it on the top.
    private Button btnOpenGallery;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnOpenGallery = (Button)findViewById(R.id.btnOpenGallery);
        btnOpenGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent();
                intent.setType("video/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            Uri selectedImageUri = data.getData();
            String strPath = selectedImageUri.getPath();
            Log.e("Path is ","===>"+strPath);

            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(strPath); // Enter Full File Path Here
            String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            long timeInmillisec = Long.parseLong(time);
            Log.e("Media duration in ","==>"+timeInmillisec);

        }
    }
}

Body:
try this one

MediaPlayer mp = MediaPlayer.create(getActivity(), Uri.parse(Environment.getExternalStorageDirectory() + "/Downloads/" + "vid" + ".mp4")); // Downloads is the folder and vid is video file.
int duration = mp.getDuration();
mp.release();

This was worked for me.


问:
Android - when ever my app is installed, by default "No permission allowed" is set?
My app when-ever is installed via Google Play or USB
(which use microphone, camera just like all other general app), by default the app gets "No permission allowed".

As a result it never works after the installation as fresh install.

Unless someone manually go in the app settings and change it.

What am i doing wrong? why its causing default into permission denied mode?

AndroidManifest.xml:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
</code>```

EDIT:

```<code>C:\cordova\tpt>cordova plugin add cordova.plugins.diagnostic
Fetching plugin "cordova.plugins.diagnostic" via npm
Installing "cordova.plugins.diagnostic" for android
ANDROID_HOME=C:\Users\tpt\AppData\Local\Android\sdk
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_121
Subproject Path: CordovaLib
null
org.xwalk:xwalk_core_library:23+
Incremental java compilation is an incubating feature.
:clean FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':clean'.
> Unable to delete directory: C:\cordova\tpt\platforms\android\build\outputs\apk

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 3.83 secs
Failed to install 'cordova.plugins.diagnostic':Error: cmd: Command failed with exit code 1
    at ChildProcess.whenDone (C:\cordova\tpt\platforms\android\cordova\node_modules\cordova-common\src\superspawn.js:169:23)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:886:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
Error: cmd: Command failed with exit code 1
</code>```

答:
From Android M and further, you need to ask for runtime permission for each permissions needed.

An example of asking permission for CONTACTS will be :-

```<code>if (ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.READ_CONTACTS)
    != PackageManager.PERMISSION_GRANTED) {

if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
        Manifest.permission.READ_CONTACTS)) {

} else {

    ActivityCompat.requestPermissions(thisActivity,
            new String[]{Manifest.permission.READ_CONTACTS},
            MY_PERMISSIONS_REQUEST_READ_CONTACTS);
 }
}
</code>```

Body:
My app when-ever is installed via Google Play or USB
(which use microphone, camera just like all other general app), by default the app gets "No permission allowed".

As a result it never works after the installation as fresh install.

Unless someone manually go in the app settings and change it.

What am i doing wrong? why its causing default into permission denied mode?

AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CAMERA" />

EDIT:

C:\cordova\tpt>cordova plugin add cordova.plugins.diagnostic
Fetching plugin "cordova.plugins.diagnostic" via npm
Installing "cordova.plugins.diagnostic" for android
ANDROID_HOME=C:\Users\tpt\AppData\Local\Android\sdk
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_121
Subproject Path: CordovaLib
null
org.xwalk:xwalk_core_library:23+
Incremental java compilation is an incubating feature.
:clean FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':clean'.
> Unable to delete directory: C:\cordova\tpt\platforms\android\build\outputs\apk

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 3.83 secs
Failed to install 'cordova.plugins.diagnostic':Error: cmd: Command failed with exit code 1
    at ChildProcess.whenDone (C:\cordova\tpt\platforms\android\cordova\node_modules\cordova-common\src\superspawn.js:169:23)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:886:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
Error: cmd: Command failed with exit code 1

Body:
From Android M and further, you need to ask for runtime permission for each permissions needed.

An example of asking permission for CONTACTS will be :-

if (ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.READ_CONTACTS)
    != PackageManager.PERMISSION_GRANTED) {

if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
        Manifest.permission.READ_CONTACTS)) {

} else {

    ActivityCompat.requestPermissions(thisActivity,
            new String[]{Manifest.permission.READ_CONTACTS},
            MY_PERMISSIONS_REQUEST_READ_CONTACTS);
 }
}


问:
If IQueryable<T> inherits IEnumerable<T> , how come IQueryable<T> is LINQ to SQL?
IEnumerable<T> case is LINQ-to-object and IQueryable<T> is the interface that allows LINQ-to-SQL , however IQueryable<T> inherits IEnumerable<T> , so how is it possible to IQueryable<T> to filter rows in the Database while IEnumerable<T> filters objects in the memory ?

答:
how is it possible to IQueryable to filter rows in the Database while IEnumerable filters objects in the memory ?

They don't, that is an inaccurate statement.

The actual implementation code is inside extension methods which are selective for either IEnumerable or IQueryable.

In EF there is a

```<code>Where<T>(this IQueryable<T>, Expression<Predicate<T>> )
</code>```

and in System.Linq there is

```<code>Where<T>(this IEnumerable<T>, Predicate<T>)
</code>```

The resoluton rules will prefer an IQueryable extension over the basic Linq one, and the magic is enabled through the Expression<> parameter.

Body:
how is it possible to IQueryable to filter rows in the Database while IEnumerable filters objects in the memory ?

They don't, that is an inaccurate statement.

The actual implementation code is inside extension methods which are selective for either IEnumerable or IQueryable.

In EF there is a

Where<T>(this IQueryable<T>, Expression<Predicate<T>> )

and in System.Linq there is

Where<T>(this IEnumerable<T>, Predicate<T>)

The resoluton rules will prefer an IQueryable extension over the basic Linq one, and the magic is enabled through the Expression<> parameter.


问:
Warning: mysql_num_rows(): supplied argument is not a valid
Hi i'm receiving the error below, i've double checked everything and don't know why its being displayed.
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/namebob/public_html/site_reg/statlookup.php on line 6</p>

```<code><?php
    include_once('common.php');
    $cid        =   $_REQUEST['cid'];
    $_elmID     =   $_REQUEST['elmID'];
    $scan = mysql_query("SELECT  `id`, `state` FROM `mast_state` WHERE `countryid` = $cid");
    if(mysql_num_rows($scan)>0)
    {
...
</code>```

答:
```<code>$scan = mysql_query("SELECT  `id`, `state` FROM `mast_state` WHERE `countryid` = $cid");
    $stock_num = '';
    if($scan )
    {
        while($row=mysql_fetch_object($scan))
        {
            if($row->state)
            $state  = $row->state;
        }
    }
</code>```

Body:
Hi i'm receiving the error below, i've double checked everything and don't know why its being displayed.
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/namebob/public_html/site_reg/statlookup.php on line 6

<?php
    include_once('common.php');
    $cid        =   $_REQUEST['cid'];
    $_elmID     =   $_REQUEST['elmID'];
    $scan = mysql_query("SELECT  `id`, `state` FROM `mast_state` WHERE `countryid` = $cid");
    if(mysql_num_rows($scan)>0)
    {
...


问:
Gridview scroll slow
I'm trying to create an gallery app, just to show images to the user.

The app is already working, but the grid scroll is slow and not smooth.

I don't know what else I can do to make performance better. I'm already using LruCache and Async task to load images.

GridAdapter

```<code>package abcde.xyz;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

import java.util.ArrayList;

/**
 * Created by Lucas on 25/03/2017.
 */

public class GridImagesAdapter extends ArrayAdapter {

    private Context context;
    private int layoutResourceId;
    private ArrayList data = new ArrayList();
    public static LruCache<Integer, Bitmap> mMemoryCache;

    public GridImagesAdapter(Context context, int layoutResourceId, ArrayList<Integer> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;

        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

        final int cacheSize = maxMemory / 4;
        if(mMemoryCache == null){
            mMemoryCache = new LruCache<Integer, Bitmap>(cacheSize) {
                @Override
                protected int sizeOf(Integer key, Bitmap bitmap) {
                    return bitmap.getByteCount() / 1024;
                }
            };
        }
        mMemoryCache.evictAll();

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            ImageView image = (ImageView)row.findViewById(R.id.image);
            final Integer item = (Integer)data.get(position);

            image.setImageBitmap(null);
            ImageGridHandler handler = new ImageGridHandler(context, image);
            handler.execute(item);
        }

        return row;
    }
}
</code>```

ImageGridHandler

```<code>package abcde.xyz;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;

import java.lang.ref.WeakReference;

/**
 * Created by Lucas on 29/03/2017.
 */

public class ImageGridHandler extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;
    private Context context;
    public ImageGridHandler(Context context, ImageView img){
        imageViewReference = new WeakReference<ImageView>(img);
        this.context = context;
    }

    @Override
    protected Bitmap doInBackground(Integer... params) {

        return loadBitmap(params[0]);

    }

    @Override
    protected void onPostExecute(Bitmap result) {
        final ImageView imageView = imageViewReference.get();

        if(imageView != null) {
            //imageView.setScaleType(ImageView.ScaleType.CENTER);
            imageView.setImageBitmap(result);
        }
    }

    public void addBitmapToMemoryCache(Integer key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            GridImagesAdapter.mMemoryCache.put(key, bitmap);
        }
    }

    public Bitmap getBitmapFromMemCache(Integer key) {
        return GridImagesAdapter.mMemoryCache.get(key);
    }

    public Bitmap loadBitmap(Integer resId) {

        Bitmap bitmap = getBitmapFromMemCache(resId);
        if (bitmap == null) {

           Log.d("ImageGridHandler", "Loading: " + resId);
            if(resId != null) {
                bitmap = MediaStore.Images.Thumbnails.getThumbnail(
                        context.getContentResolver(), resId,
                        MediaStore.Images.Thumbnails.MICRO_KIND,
                        null);
                if(bitmap != null) {
                    addBitmapToMemoryCache(resId, bitmap);
                }
            }

            Log.d("GRIDADAPTER", "ImageLoaded");
        }

        return bitmap;
    }

}
</code>```

Layouts

content_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="umdev.images24.MainActivity"
    tools:showIn="@layout/activity_main">
    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swipeRefresh"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp">

     <GridView
         android:id="@+id/gridView"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_margin="0dp"
         android:drawSelectorOnTop="true"
         android:gravity="center"
         android:columnWidth="100dp"
         android:numColumns="auto_fit"
         android:stretchMode="columnWidth"
         android:verticalSpacing="0dp"
         android:focusable="true"
         android:clickable="true"
         android:fastScrollEnabled="true"/>

    </android.support.v4.widget.SwipeRefreshLayout>
</android.support.constraint.ConstraintLayout>
</code>```

grid_item_layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:background="#fff">

    <ImageView
        android:id="@+id/image"
        android:layout_width="120dp"
        android:layout_height="120dp" />

</LinearLayout>
</code>```

答:
You can use Glide , Picassa or ImageLoader to load the image and avoid
  scrolling issue that occures due to time taken to load image in image
  view

For example in Glide

```<code>Glide.with(getActivity()).load(Uri.fromFile(new File(String.valueOf(getItem(position))))).into(ivPhoto);
</code>```

Title: Gridview scroll slow

Body:
I'm trying to create an gallery app, just to show images to the user.

The app is already working, but the grid scroll is slow and not smooth.

I don't know what else I can do to make performance better. I'm already using LruCache and Async task to load images.

GridAdapter

package abcde.xyz;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

import java.util.ArrayList;

/**
 * Created by Lucas on 25/03/2017.
 */

public class GridImagesAdapter extends ArrayAdapter {

    private Context context;
    private int layoutResourceId;
    private ArrayList data = new ArrayList();
    public static LruCache<Integer, Bitmap> mMemoryCache;

    public GridImagesAdapter(Context context, int layoutResourceId, ArrayList<Integer> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;

        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

        final int cacheSize = maxMemory / 4;
        if(mMemoryCache == null){
            mMemoryCache = new LruCache<Integer, Bitmap>(cacheSize) {
                @Override
                protected int sizeOf(Integer key, Bitmap bitmap) {
                    return bitmap.getByteCount() / 1024;
                }
            };
        }
        mMemoryCache.evictAll();

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            ImageView image = (ImageView)row.findViewById(R.id.image);
            final Integer item = (Integer)data.get(position);

            image.setImageBitmap(null);
            ImageGridHandler handler = new ImageGridHandler(context, image);
            handler.execute(item);
        }

        return row;
    }
}

ImageGridHandler

package abcde.xyz;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;

import java.lang.ref.WeakReference;

/**
 * Created by Lucas on 29/03/2017.
 */

public class ImageGridHandler extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;
    private Context context;
    public ImageGridHandler(Context context, ImageView img){
        imageViewReference = new WeakReference<ImageView>(img);
        this.context = context;
    }

    @Override
    protected Bitmap doInBackground(Integer... params) {

        return loadBitmap(params[0]);

    }

    @Override
    protected void onPostExecute(Bitmap result) {
        final ImageView imageView = imageViewReference.get();

        if(imageView != null) {
            //imageView.setScaleType(ImageView.ScaleType.CENTER);
            imageView.setImageBitmap(result);
        }
    }

    public void addBitmapToMemoryCache(Integer key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            GridImagesAdapter.mMemoryCache.put(key, bitmap);
        }
    }

    public Bitmap getBitmapFromMemCache(Integer key) {
        return GridImagesAdapter.mMemoryCache.get(key);
    }

    public Bitmap loadBitmap(Integer resId) {

        Bitmap bitmap = getBitmapFromMemCache(resId);
        if (bitmap == null) {

           Log.d("ImageGridHandler", "Loading: " + resId);
            if(resId != null) {
                bitmap = MediaStore.Images.Thumbnails.getThumbnail(
                        context.getContentResolver(), resId,
                        MediaStore.Images.Thumbnails.MICRO_KIND,
                        null);
                if(bitmap != null) {
                    addBitmapToMemoryCache(resId, bitmap);
                }
            }

            Log.d("GRIDADAPTER", "ImageLoaded");
        }

        return bitmap;
    }

}

Layouts

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="umdev.images24.MainActivity"
    tools:showIn="@layout/activity_main">
    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swipeRefresh"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp">

     <GridView
         android:id="@+id/gridView"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_margin="0dp"
         android:drawSelectorOnTop="true"
         android:gravity="center"
         android:columnWidth="100dp"
         android:numColumns="auto_fit"
         android:stretchMode="columnWidth"
         android:verticalSpacing="0dp"
         android:focusable="true"
         android:clickable="true"
         android:fastScrollEnabled="true"/>

    </android.support.v4.widget.SwipeRefreshLayout>
</android.support.constraint.ConstraintLayout>

grid_item_layout.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:background="#fff">

    <ImageView
        android:id="@+id/image"
        android:layout_width="120dp"
        android:layout_height="120dp" />

</LinearLayout>

Body:
You can use Glide , Picassa or ImageLoader to load the image and avoid
  scrolling issue that occures due to time taken to load image in image
  view

For example in Glide

Glide.with(getActivity()).load(Uri.fromFile(new File(String.valueOf(getItem(position))))).into(ivPhoto);


问:
Jquery dotdotdot only fired properly on window resize
In order to create an ellipsis after the second line within an element, I'm using  jquery dotdotdot.
I'm using it with the google font 'source sans pro', however it doesn't work properly until after the window is resized.

this is how the text appears before the window is resized (the ellipsis is created too early)

this is how the text appears after the window is resized (the ellipsis is in the proper position)

(I'm assuming this is happening because the font isn't fully loaded on the page's load, but I could be wrong?)

This is the way that I call the jquery dotdotdot.

```<code>    $(document).ready(function(){
        doResize();
        $(window).on('resize', doResize);
    });
    function doResize() {
        $(".col-mid a").dotdotdot({
            ellipsis: '...',
            height  : 40
        });
    }
</code>```

How would I make it so it works properly? I've tried delaying the time that the dotdotdot function is called but this seems hacky, and like a bad solution.

Here's a jsfiddle of relevant code. (Weirdly enough it seems to work fine on jsfiddle, however it doesn't work on my computer.)

答:
You can add option through dotodotdot by  watch: 'window' </p>

```<code>$(".content-class").dotdotdot({
    ellipsis    : '... ',
    watch       : 'window',
});
</code>```

Body:
In order to create an ellipsis after the second line within an element, I'm using  jquery dotdotdot.
I'm using it with the google font 'source sans pro', however it doesn't work properly until after the window is resized.

this is how the text appears before the window is resized (the ellipsis is created too early)

this is how the text appears after the window is resized (the ellipsis is in the proper position)

(I'm assuming this is happening because the font isn't fully loaded on the page's load, but I could be wrong?)

This is the way that I call the jquery dotdotdot.

    $(document).ready(function(){
        doResize();
        $(window).on('resize', doResize);
    });
    function doResize() {
        $(".col-mid a").dotdotdot({
            ellipsis: '...',
            height  : 40
        });
    }

How would I make it so it works properly? I've tried delaying the time that the dotdotdot function is called but this seems hacky, and like a bad solution.

Here's a jsfiddle of relevant code. (Weirdly enough it seems to work fine on jsfiddle, however it doesn't work on my computer.)

Body:
You can add option through dotodotdot by  watch: 'window'

$(".content-class").dotdotdot({
    ellipsis    : '... ',
    watch       : 'window',
});


问:
How to access the nested JSON objects
I want to access nested JSON object values by iterating.

I tried console.log(test[0].Invoice[0].Cost.NO[0]); but it's not working.

var test = [{
  "Invoice": {
    "NO": "869",
    "$$hashKey": "object:186"
  },
  "Cost": [{
    "NO": 183,
    "Amnt": 100
  }, {
    "NO": 184,
    "Amnt": 200
  }]
}, {
  "Invoice": {
    "NO": "698",
    "$$hashKey": "object:189"
  },
  "Cost": [{
    "NO": 110,
    "Amnt": 150
  }, {
    "NO": 142,
    "Amnt": 263
  }]
}];

console.log(test[0].Invoice[0].Cost.NO[0]);```

答:
This is your JSON:

```<code>var test = [{
  "Invoice": {
    "NO": "869"
  },
  "Cost": [{
    "NO": 183,
    "Amnt": 100
  }, {
    "NO": 184,
    "Amnt": 200
  }]
}, {
  "Invoice": {
    "NO": "698"
  },
  "Cost": [{
    "NO": 110,
    "Amnt": 150
  }, {
    "NO": 142,
    "Amnt": 263
  }]
}];
</code>```

console.log(test[0].Cost[0].NO);
would be 183

You can check your structure in development with console.log(test) if you are not used to JSON.

To iterate you should use a loop as described here: https://www.w3schools.com/jsref/jsref_forEach.asp

Short example:

```<code> var myFunction = function(item,index){
    console.log(item.Cost[0].No);
 }
 test.forEach(myFunction)
</code>```

Title: How to access the nested JSON objects

Body:
This is your JSON:

var test = [{
  "Invoice": {
    "NO": "869"
  },
  "Cost": [{
    "NO": 183,
    "Amnt": 100
  }, {
    "NO": 184,
    "Amnt": 200
  }]
}, {
  "Invoice": {
    "NO": "698"
  },
  "Cost": [{
    "NO": 110,
    "Amnt": 150
  }, {
    "NO": 142,
    "Amnt": 263
  }]
}];

console.log(test[0].Cost[0].NO);
would be 183

You can check your structure in development with console.log(test) if you are not used to JSON.

To iterate you should use a loop as described here: https://www.w3schools.com/jsref/jsref_forEach.asp

Short example:

 var myFunction = function(item,index){
    console.log(item.Cost[0].No);
 }
 test.forEach(myFunction)


问:
getting error "Caused by: org.apache.kafka.common.errors.TopicExistsException: Topic "ticktock2.time" already exists"
While deploying the basic stream, gets error topic already exists

Caused by: org.apache.kafka.common.errors.TopicExistsException: Topic "ticktock2.time" already exists

答:
It is possible that there could be race condition when the apps are deployed and the apps trying to create the topic as they are being deployed.

Which deployer do you use? For instance, in case of local deployer, it spins off a new process for each app and it is possible that one of the apps creates a topic (the common destination name for the source/sink) while the other fails to create as the topic already exists.

Do you see this behaviour consistently every time you deploy the stream?


问:
Recyclerview last item not shown inside coordinator layout
My last item inside recyclerview is not shown. The top bar should remain visible once it gains focus. It should not scroll upwards.
My code is below:

```<code><android.support.design.widget.CoordinatorLayout
    android:id="@+id/content_parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="invisible"
    tools:visibility="visible"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:visibility="invisible"
        app:elevation="0dp"
        app:layout_behavior="haygot.togyah.app.newDesign.home.FlingBehaviour"
        tools:visibility="visible"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/transparent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/transparent"
                android:minHeight="?android:attr/actionBarSize"
                app:contentInsetStart="0dp"
                app:layout_collapseMode="pin">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <android.support.v7.widget.AppCompatImageView
                        android:id="@+id/leaderboard_iv"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="@dimen/spacing_large"
                        android:src="@drawable/ic_leaderboard_icon" />

                    <haygot.togyah.app.widget.TextView.TextViewPlus
                        android:id="@+id/title"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_centerInParent="true"
                        android:layout_toLeftOf="@+id/doubts"
                        android:layout_toRightOf="@+id/leaderboard_iv"
                        android:alpha="0"
                        android:gravity="center"
                        android:text="What would you like to learn today?"
                        android:textAppearance="@style/CollapsingToolbarTitle" />

                    <android.support.v7.widget.AppCompatImageView
                        android:id="@+id/doubts"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:paddingRight="@dimen/spacing_large"
                        android:src="@drawable/ic_doubt_home" />

                </RelativeLayout>
            </android.support.v7.widget.Toolbar>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"

                app:layout_collapseMode="parallax">

                <android.support.v7.widget.AppCompatImageView
                    android:id="@+id/home_icon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:background="@drawable/ic_dash_profile_icon"

                    android:visibility="visible" />

                <haygot.togyah.app.widget.TextView.TextViewPlus
                    android:id="@+id/message"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/home_icon"
                    android:layout_marginBottom="@dimen/spacing_36dp"
                    android:layout_marginTop="-20dp"
                    android:gravity="center"
                    android:letterSpacing="-.03"
                    android:lineSpacingExtra="4dp"
                    android:minLines="3"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/app_text_size_xxxlarge"
                    android:textStyle="bold"
                    app:customFont="@string/font_proxima_nova_bold"
                    tools:text="Hello Anudeep, \n let's learn something\n new today!" />

            </RelativeLayout>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:nestedScrollingEnabled="true"
        android:id="@+id/subjects_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipChildren="true"
        android:paddingBottom="@dimen/spacing_small"
        android:paddingLeft="@dimen/spacing_small"
        android:paddingRight="@dimen/spacing_small"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>
</code>```

As I move upwards, the last item in the recycler is partially visible.
How should I resolve this?

答:
Make your AppBarLayout to have specific height, save that value in dimens.xml. And apply that much margin from bottom to RecyclerView:

```<code><android.support.v7.widget.RecyclerView
    ...
    android:layout_marginBottom="@dimen/app_bar_height"
    .../>
</code>```

Body:
My last item inside recyclerview is not shown. The top bar should remain visible once it gains focus. It should not scroll upwards.
My code is below:

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/content_parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="invisible"
    tools:visibility="visible"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:visibility="invisible"
        app:elevation="0dp"
        app:layout_behavior="haygot.togyah.app.newDesign.home.FlingBehaviour"
        tools:visibility="visible"
        android:fitsSystemWindows="true">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/transparent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/transparent"
                android:minHeight="?android:attr/actionBarSize"
                app:contentInsetStart="0dp"
                app:layout_collapseMode="pin">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <android.support.v7.widget.AppCompatImageView
                        android:id="@+id/leaderboard_iv"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="@dimen/spacing_large"
                        android:src="@drawable/ic_leaderboard_icon" />

                    <haygot.togyah.app.widget.TextView.TextViewPlus
                        android:id="@+id/title"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_centerInParent="true"
                        android:layout_toLeftOf="@+id/doubts"
                        android:layout_toRightOf="@+id/leaderboard_iv"
                        android:alpha="0"
                        android:gravity="center"
                        android:text="What would you like to learn today?"
                        android:textAppearance="@style/CollapsingToolbarTitle" />

                    <android.support.v7.widget.AppCompatImageView
                        android:id="@+id/doubts"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:layout_centerVertical="true"
                        android:paddingRight="@dimen/spacing_large"
                        android:src="@drawable/ic_doubt_home" />

                </RelativeLayout>
            </android.support.v7.widget.Toolbar>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"

                app:layout_collapseMode="parallax">

                <android.support.v7.widget.AppCompatImageView
                    android:id="@+id/home_icon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:background="@drawable/ic_dash_profile_icon"

                    android:visibility="visible" />

                <haygot.togyah.app.widget.TextView.TextViewPlus
                    android:id="@+id/message"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/home_icon"
                    android:layout_marginBottom="@dimen/spacing_36dp"
                    android:layout_marginTop="-20dp"
                    android:gravity="center"
                    android:letterSpacing="-.03"
                    android:lineSpacingExtra="4dp"
                    android:minLines="3"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/app_text_size_xxxlarge"
                    android:textStyle="bold"
                    app:customFont="@string/font_proxima_nova_bold"
                    tools:text="Hello Anudeep, \n let's learn something\n new today!" />

            </RelativeLayout>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:nestedScrollingEnabled="true"
        android:id="@+id/subjects_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipChildren="true"
        android:paddingBottom="@dimen/spacing_small"
        android:paddingLeft="@dimen/spacing_small"
        android:paddingRight="@dimen/spacing_small"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

As I move upwards, the last item in the recycler is partially visible.
How should I resolve this?

Body:
Make your AppBarLayout to have specific height, save that value in dimens.xml. And apply that much margin from bottom to RecyclerView:

<android.support.v7.widget.RecyclerView
    ...
    android:layout_marginBottom="@dimen/app_bar_height"
    .../>


问:
How to type EOF in ARMv8 Assembly?
I am using the ARMv8 instruction set with Aarch64 execution state. The problem I am having, is were supposed to translate C code into assembly, and I am stuck on the following:

```<code>while (c != '\n' && c != EOF)
    c = getchar();
</code>```

I know the basic setup for the while loop, as well as how to test c != '\n' but the issue I have is how to write EOF in assembly.
Can i just type

```<code>cmp c_r, EOF
b.eq skipwhile
</code>```

or is it something else?

答:
It depends on what code you're using in assembly for getchar() -

If you're just using a call to the assembly version of standard C library getchar(), then you can test with the C library's definition of EOF - normally -1.

If you're implementing your own getchar() in assembly, then you need to match your test to the return value of your getchar() implementation when it gets to the end-of-file.

Title: How to type EOF in ARMv8 Assembly?

Body:
I am using the ARMv8 instruction set with Aarch64 execution state. The problem I am having, is were supposed to translate C code into assembly, and I am stuck on the following:

while (c != '\n' && c != EOF)
    c = getchar();

I know the basic setup for the while loop, as well as how to test c != '\n' but the issue I have is how to write EOF in assembly.
Can i just type

cmp c_r, EOF
b.eq skipwhile

or is it something else?


问:
CSS rotate div 10deg full width
I have found the following Website.
Special the Section: Social News on the half of the side.

I wonder how to get the rotated divs (i think about 10 deg) over the full width.
Is there any possibility to do that responsive? So i can use the rotated div on a mobile phone?
I`m not as fit to rotate the div. How can i do this using css?

I`ve tried this:

```<code><div class="container"></div>
</code>```

Ans using following css:

```<code>.container {
   transform: rotate(10deg);
   width: 100%;
   height: 200px;
   background: red;
}
</code>```

But the Container is not full width.

答:
As well as transforming by rotation, you could also scale it up, and set the div parent 's overflow style to hidden - which, if scaled up enough, should cover the full width.

div.parent {
  overflow: hidden;
  height: 100vh;
  background-color: lightblue;
}

div.container {
  margin-top: 42px;
  transform: rotate(10deg) scale(1.2);
  background-color: red;
  height: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="container"></div>
</div></code>```

Title: CSS rotate div 10deg full width

Body:
I have found the following Website.
Special the Section: Social News on the half of the side.

I wonder how to get the rotated divs (i think about 10 deg) over the full width.
Is there any possibility to do that responsive? So i can use the rotated div on a mobile phone?
I`m not as fit to rotate the div. How can i do this using css?

I`ve tried this:

Ans using following css:

.container {
   transform: rotate(10deg);
   width: 100%;
   height: 200px;
   background: red;
}

But the Container is not full width.

Body:
As well as transforming by rotation, you could also scale it up, and set the div parent 's overflow style to hidden - which, if scaled up enough, should cover the full width.

div.parent {
  overflow: hidden;
  height: 100vh;
  background-color: lightblue;
}

div.container {
  margin-top: 42px;
  transform: rotate(10deg) scale(1.2);
  background-color: red;
  height: 100px;
}

<div class="parent">
  <div class="container"></div>
</div>


问:
Using MongoDB locally (electron)?
I need to store some data as part of my electron application. I know how to set up a REST API, and serve my application like so. However, is it also possible to use (e.g.) MongoDB locally, and implement something similar to a REST API locally? I would like to not assume an internet connection for this project.</p>

答: If you need to implement a mongoDB like database locally for the application without internet, you can use lowdb</p>

Title: Using MongoDB locally (electron)?