问:
Javascript - why is this undefined?
The alert at the start shows "undefined", why?

The alerts come in this order:

"success!"

"Data" (what it should be)

"undefined"

I read through multiple threads, the problem was always that ajax was asynchronous, so the data was not defined when it was accessed, but in my case the data is there, the alert in my function shows the data BEFORE the other alert where it is undefined!

Very grateful for any help!

I got this code

```<code>var data = getData("");
alert(data);            <<<<<<< UNDEFINED

function getData(fileName) {

    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            var arrData = processData(data);
            alert("success!");
            alert(arrData);      <<<<< WORKS GREAT
            return arrData;
        },
    });

}

function processData(data) {

    var arrData = CSVToArray(data);

    dimensions = arrData[0];
    var objects = [];

    objects[0] = dimensions;

    for (var i = 1; i < arrData.length; i++){
        objects[i] = new Object();

        for (var j = 0; j < dimensions.length; j++){
            objects[i][dimensions[j]] = arrData[i][j];
        }
    }

    return objects;
}
</code>```

To clarify, I know asynchronous is the way to go for user experience, but this page just has to show data from this call, so its okay for me to wait for it.

答:
Preface: Don't use async: false. But answering the question:

getData doesn't return anything. You're doing a return from the success callback, but that returns something from the success callback, not getData.

To change it so getData returns something, you'd do this:

```<code>function getData(fileName) {
    var arrData;
    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            arrData = processData(data);
        },
    });
    return arrData; // <=== Now `getData` returns something
}
</code>```

But don't do that. Instead, embrace asynchronous programming and remove async: false. For instance, a callback:

```<code>function getData(fileName) {
    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            callback(processData(data));
        },
    });
}
</code>```

...called like this:

```<code>getData(function(data) {
    alert(data);
});
</code>```

...or a promise ($.ajax returns one, of sorts):

```<code>function getData(fileName) {
    return $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            callback(processData(data));
        },
    }).then(data) {
        return processData(data); // <== Becomes the resolution value of `getData`'s promise
    });
}
</code>```

and then

```<code>getData().then(function(data) {
    alert(data);
});
</code>```

Title: Javascript - why is this undefined?

Body:
The alert at the start shows "undefined", why?

The alerts come in this order:

"success!"

"Data" (what it should be)

"undefined"

I read through multiple threads, the problem was always that ajax was asynchronous, so the data was not defined when it was accessed, but in my case the data is there, the alert in my function shows the data BEFORE the other alert where it is undefined!

Very grateful for any help!

I got this code

var data = getData("");
alert(data);            <<<<<<< UNDEFINED

function getData(fileName) {

    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            var arrData = processData(data);
            alert("success!");
            alert(arrData);      <<<<< WORKS GREAT
            return arrData;
        },
    });

}

function processData(data) {

    var arrData = CSVToArray(data);

    dimensions = arrData[0];
    var objects = [];

    objects[0] = dimensions;

    for (var i = 1; i < arrData.length; i++){
        objects[i] = new Object();

        for (var j = 0; j < dimensions.length; j++){
            objects[i][dimensions[j]] = arrData[i][j];
        }
    }

    return objects;
}

To clarify, I know asynchronous is the way to go for user experience, but this page just has to show data from this call, so its okay for me to wait for it.

Body:
Preface: Don't use async: false. But answering the question:

getData doesn't return anything. You're doing a return from the success callback, but that returns something from the success callback, not getData.

To change it so getData returns something, you'd do this:

function getData(fileName) {
    var arrData;
    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            arrData = processData(data);
        },
    });
    return arrData; // <=== Now `getData` returns something
}

But don't do that. Instead, embrace asynchronous programming and remove async: false. For instance, a callback:

function getData(fileName) {
    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            callback(processData(data));
        },
    });
}

...called like this:

getData(function(data) {
    alert(data);
});

...or a promise ($.ajax returns one, of sorts):

function getData(fileName) {
    return $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            callback(processData(data));
        },
    }).then(data) {
        return processData(data); // <== Becomes the resolution value of `getData`'s promise
    });
}

and then

getData().then(function(data) {
    alert(data);
});


来源: stackexchange

问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
as a previous poster mentioned, do check out design patterns.

also, i found uncle bob's stuff useful as a student as well as an instructor, in particular some of the oo design principles: http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod

OwnerDisplayName: GregD

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: GregD

OwnerDisplayName: Ray Tayek


问:
CSS overriding subsequent attributes
Say I have a div for the main body text of a webpage, and a navigation div for links to the rest of the website. Now say I want the links in the body text to be green instead of the usual blue, but I want the links in the navigation div to be yet another color, perhaps red. If I make links green in CSS, then all the links will be green. If I make the text in the navigation div red with CSS, the link attributes seem to override the div's attributes for links in the navigation div. How can I target only certain links when no links have any classes attached to them?

答:
Because of CSS specificity (I love that word) rules, JMC's suggestion works.

Read more about that here:
http://htmldog.com/guides/cssadvanced/specificity/

Basically, the more specific the rule is, the more likely it is to be used.

Title: CSS overriding subsequent attributes


问:
Swift 3 File copy error
I am trying to make a copy of a .plist into the Documents folder.
I have this code but I get "File copy error".</p>

```<code>let srcPath = Bundle.main.path(forResource: "Gameboard", ofType: "plist")
//let path = Bundle.main.resourcePath!
let path = String(describing: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first)
print(srcPath)
print(path)
do {
    //Copy the project plist file to the documents directory.
    try FileManager.default.copyItem(atPath: srcPath!, toPath: path)
} catch {
    print("File copy error!")
}
</code>```

答:
Documentation:

dstPath

  The path at which to place the copy of srcPath. This path must include the name of the file or directory in its new location. This parameter must not be nil.

You need to append the file name "Gameboard.plist" to the destination path:

```<code>let srcUrl = Bundle.main.url(forResource: "Gameboard", ofType: "plist")
let documentsUrl = FileManager.default.urls(
    for: .documentDirectory,
    in: .userDomainMask
).first!
let destinationUrl = documentsUrl.appendingPathComponent(
   "Gameboard.plist",   // or srcUrl.lastPathComponent
    isDirectory: false
)

do {
   try FileManager.default.copyItem(at: srcUrl, to: destinationUrl)
} catch {
   ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Swift 3 File copy error

Body:
I am trying to make a copy of a .plist into the Documents folder.
I have this code but I get "File copy error".

let srcPath = Bundle.main.path(forResource: "Gameboard", ofType: "plist")
//let path = Bundle.main.resourcePath!
let path = String(describing: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first)
print(srcPath)
print(path)
do {
    //Copy the project plist file to the documents directory.
    try FileManager.default.copyItem(atPath: srcPath!, toPath: path)
} catch {
    print("File copy error!")
}

Body:
Documentation:

dstPath

  The path at which to place the copy of srcPath. This path must include the name of the file or directory in its new location. This parameter must not be nil.

You need to append the file name "Gameboard.plist" to the destination path:

let srcUrl = Bundle.main.url(forResource: "Gameboard", ofType: "plist")
let documentsUrl = FileManager.default.urls(
    for: .documentDirectory,
    in: .userDomainMask
).first!
let destinationUrl = documentsUrl.appendingPathComponent(
   "Gameboard.plist",   // or srcUrl.lastPathComponent
    isDirectory: false
)

do {
   try FileManager.default.copyItem(at: srcUrl, to: destinationUrl)
} catch {
   ...
}


问:
Regex find string after key inside qoutes
Input:

blalasdl8ujd "key":"value", blblabla asdw
  "alo":"ebobo",blabla"www":"zzzz"

or

blalasdl8ujd key [any_chars_here] "value", blabla asdw
  "alo":"ebobo", bla"www":"zzzz"

I'm tring to extract value having only key and knowing that value is covered with "

Following regex key.*"(.*?)" returns the last match covered with " ("zzzz").
I need to fix it to return first.

https://regex101.com/r/CDfhBT/1

答:
Code

See regex in use here

```<code>"key"\s*:\s*"([^"]*)"
</code>```

To match the possibility of escaped double quotes you can use the following regex:

See regex in use here

```<code>"key"\s*:\s*"((?:(?<!\\)\\(?:\\{2})*"|[^"])*)"
</code>```

This method ensures that an odd number of backslashes \ precedes the double quotation character " such that \", \\\", \\\\\", etc. are valid, but \\", \\\\", \\\\\\" are not valid (this would simply output a backslash character, thus the double quotation character " preceded by an even number of backslashes would simply result in a string termination).

Matching both strings

If you're looking to match your second string as well, you can use either of the following regexes:

```<code>\bkey\b(?:"\s*:\s*|.*?)"([^"]*)"
\bkey\b(?:"\s*:\s*|.*?)"((?:(?<!\\)\\(?:\\{2})*"|[^"])*)"
</code>```

Usage

See code in use here

```<code>import re

s = 'blahblah "key":"value","TargetCRS": "Target","TargetCRScode": "vertical Code","zzz": "aaaa" sadzxc "sss"'
r = re.compile(r'''"key"\s*:\s*"([^"]*)"''')

match = r.search(s)
if match:
    print match.group(1)
</code>```

Results

Input

```<code>blahblah "key":"value","TargetCRS": "Target","TargetCRScode": "vertical Code","zzz": "aaaa" sadzxc "sss"
blalasdl8ujd key [any_chars_here] "value", blabla asdw "alo":"ebobo", bla"www":"zzzz"
</code>```

Output

String 1

Match: "key":"value"

Capture group 1: value

String 2 (when using one of the methods under Matching both strings)

Match: key [any_chars_here] "value"

Capture group 1: value

Explanation

"key" Match this literally

\s* Match any number of whitespace characters

: Match the colon character literally

\s* Match any number of whitespace characters

" Match the double quotation character literally

([^"]*) Capture any character not present in the set (any character except the double quotation character ") any number of times into capture group 1

" Match the double quotation character literally

Matching both strings

\b Assert position as a word boundary

key Match this literally

\b Assert position as a word boundary

(?:"\s*:\s*|.*?) Match either of the following

"\s*:\s*

" Match this literally

\s* Match any number of whitespace characters

: Match this literally

\s* Match any number of whitespace characters

.*? Match any character any number of times, but as few as possible

" Match this literally

([^"]*) Capture any number of any character except " into capture group 1

" Match this literally

Body:
Code

See regex in use here

"key"\s*:\s*"([^"]*)"

To match the possibility of escaped double quotes you can use the following regex:

See regex in use here

"key"\s*:\s*"((?:(?<!\\)\\(?:\\{2})*"|[^"])*)"

This method ensures that an odd number of backslashes \ precedes the double quotation character " such that \", \\\", \\\\\", etc. are valid, but \\", \\\\", \\\\\\" are not valid (this would simply output a backslash character, thus the double quotation character " preceded by an even number of backslashes would simply result in a string termination).

Matching both strings

If you're looking to match your second string as well, you can use either of the following regexes:

\bkey\b(?:"\s*:\s*|.*?)"([^"]*)"
\bkey\b(?:"\s*:\s*|.*?)"((?:(?<!\\)\\(?:\\{2})*"|[^"])*)"

Usage

See code in use here

import re

s = 'blahblah "key":"value","TargetCRS": "Target","TargetCRScode": "vertical Code","zzz": "aaaa" sadzxc "sss"'
r = re.compile(r'''"key"\s*:\s*"([^"]*)"''')

match = r.search(s)
if match:
    print match.group(1)

Results

Input

blahblah "key":"value","TargetCRS": "Target","TargetCRScode": "vertical Code","zzz": "aaaa" sadzxc "sss"
blalasdl8ujd key [any_chars_here] "value", blabla asdw "alo":"ebobo", bla"www":"zzzz"

Output

String 1

Match: "key":"value"

Capture group 1: value

String 2 (when using one of the methods under Matching both strings)

Match: key [any_chars_here] "value"

Capture group 1: value

Explanation

"key" Match this literally

\s* Match any number of whitespace characters

: Match the colon character literally

\s* Match any number of whitespace characters

" Match the double quotation character literally

([^"]*) Capture any character not present in the set (any character except the double quotation character ") any number of times into capture group 1

" Match the double quotation character literally

Matching both strings

\b Assert position as a word boundary

key Match this literally

\b Assert position as a word boundary

(?:"\s*:\s*|.*?) Match either of the following

"\s*:\s*

" Match this literally

\s* Match any number of whitespace characters

: Match this literally

\s* Match any number of whitespace characters

.*? Match any character any number of times, but as few as possible

" Match this literally

([^"]*) Capture any number of any character except " into capture group 1

" Match this literally


问:
ExtractXML Oracle Query Returns Null
I have the below data in a column called "attributes" of a table "data" on Oracle 12c database:

```<code><Attributes>
  <Map>
    <entry key="accountFlags">
      <value>
        <List>
          <String>Normal User Account</String>
        </List>
      </value>
    </entry>
    <entry key="cn" value="paul.john"/>
    <entry key="department" value="IT"/>
    <entry key="description" value="New account. Automatically created"/>
    <entry key="displayName" value="John, Paul"/>
    <entry key="distinguishedName" value="CN=paul.john,OU=Users,DC=test,DC=com"/>
    <entry key="givenName" value="Paul"/>
    <entry key="homeMDB" value="CN=Test,CN=Databases,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=test,DC=com"/>
    <entry key="l" value="London"/>
    <entry key="mail" value="paul.john@test.com"/>
    <entry key="mailNickname" value="PaulJ"/>
    <entry key="manager" value="CN=brock.lesnar,OU=Users,DC=test,DC=com"/>
    <entry key="memberOf">
      <value>
        <List>
          <String>CN=Test1,OU=Rights,OU=Groups,DC=test,DC=com</String>
          <String>CN=Test2,OU=Rights,OU=Groups,DC=test,DC=com</String>
          <String>CN=Test3,OU=Rights,OU=Groups,DC=test,DC=com</String>
          <String>CN=Test4,OU=Rights,OU=Groups,DC=test,DC=com</String>
        </List>
      </value>
    </entry>
  </Map>
</Attributes>
</code>```

I wish to extract the value of "memberOf" from this column like this:

```<code>MEMBER_OF
---------
CN=Test1,OU=Rights,OU=Groups,DC=test,DC=com
CN=Test2,OU=Rights,OU=Groups,DC=test,DC=com
CN=Test3,OU=Rights,OU=Groups,DC=test,DC=com
CN=Test4,OU=Rights,OU=Groups,DC=test,DC=com
</code>```

I have tried this with the below query which is returning null:

```<code>SELECT EXTRACTVALUE(xmltype(attributes), '/Attributes/Map/entry[@key="memberOf"]/value/List/@String')
FROM DATA;
</code>```

I have also tried the below query which also returns null

```<code>SELECT EXTRACTVALUE(xmltype(attributes), '/Attributes/Map/entry[@key="memberOf"]/value[1]/List/@String')
FROM DATA;
</code>```

Not sure if there is something else that needs to be passed in the query?

答:
Your path ends with .../@String, which is looking for an attribute called String, not a node. But if you fix that you'd get:

```<code>ORA-19025: EXTRACTVALUE returns value of only one node
</code>```

ExtractValue() is long-deprecated anyway. You could use XMLQuery() instead, but that gives you a single XML fragment rather than separate strings:

```<code>select xmlquery('/Attributes/Map/entry[@key="memberOf"]/value/List/String'
  passing xmltype(attributes)
  returning content) as member_of
from data;

MEMBER_OF
--------------------------------------------------------------------------------
<String>CN=Test1,OU=Rights,OU=Groups,DC=test,DC=com</String><String>CN=Test2,OU=
Rights,OU=Groups,DC=test,DC=com</String><String>CN=Test3,OU=Rights,OU=Groups,DC=
test,DC=com</String><String>CN=Test4,OU=Rights,OU=Groups,DC=test,DC=com</String>
</code>```

Instead, use XMLTable() to get the individual values, as Bikash suggested - but it can be done more simply, without two XMLTable calls:

```<code>select x.member_of
from data
cross join XMLTable('/Attributes/Map/entry[@key="memberOf"]/value/List/String'
  passing XMLType(attributes)
  columns member_of varchar2(60) path '.'
) x;

MEMBER_OF
------------------------------------------------------------
CN=Test1,OU=Rights,OU=Groups,DC=test,DC=com
CN=Test2,OU=Rights,OU=Groups,DC=test,DC=com
CN=Test3,OU=Rights,OU=Groups,DC=test,DC=com
CN=Test4,OU=Rights,OU=Groups,DC=test,DC=com
</code>```

Read more.

If you want to get other data in the same query, you can add those as more columns clauses, referring back up the tree - since the rest are single nodes, unless you have and need to show multiple account flags.

```<code>select x.*
from data
cross join XMLTable('/Attributes/Map/entry[@key="memberOf"]/value/List/String'
  passing XMLType(attributes)
  columns cn varchar2(20) path './../../../../entry[@key="cn"]/@value',
    department varchar2(10) path './../../../../entry[@key="department"]/@value',
    member_of varchar2(60) path '.'
) x;

CN                   DEPARTMENT MEMBER_OF
-------------------- ---------- ------------------------------------------------------------
paul.john            IT         CN=Test1,OU=Rights,OU=Groups,DC=test,DC=com
paul.john            IT         CN=Test2,OU=Rights,OU=Groups,DC=test,DC=com
paul.john            IT         CN=Test3,OU=Rights,OU=Groups,DC=test,DC=com
paul.john            IT         CN=Test4,OU=Rights,OU=Groups,DC=test,DC=com
</code>```

although once you do that it might be easier to read and maintain if you do use multiple XMLTable calls:

```<code>select x1.cn, x1.department, x2.member_of
from data
cross join XMLTable('/Attributes/Map'
  passing XMLType(attributes)
  columns cn varchar2(20) path 'entry[@key="cn"]/@value',
    department varchar2(10) path 'entry[@key="department"]/@value',
    member_of_xml XMLType path 'entry[@key="memberOf"]'
) x1
cross join XMLTable('/entry/value/List/String'
  passing member_of_xml
  columns member_of varchar2(60) path '.'
) x2;
</code>```

It's then simple to add a third XMLTable call to handle multiple account flags.

You could also do all this manipulation in a single XMLTable with a more complicated XPath with loops etc., but I think this is clearer and simpler, and unless you're dealing with large XML documents (and a lot of them) there may not be a significant performance difference.

Title: ExtractXML Oracle Query Returns Null

Body:
I have the below data in a column called "attributes" of a table "data" on Oracle 12c database:

<Attributes>
  <Map>
    <entry key="accountFlags">
      <value>
        <List>
          <String>Normal User Account</String>
        </List>
      </value>
    </entry>
    <entry key="cn" value="paul.john"/>
    <entry key="department" value="IT"/>
    <entry key="description" value="New account. Automatically created"/>
    <entry key="displayName" value="John, Paul"/>
    <entry key="distinguishedName" value="CN=paul.john,OU=Users,DC=test,DC=com"/>
    <entry key="givenName" value="Paul"/>
    <entry key="homeMDB" value="CN=Test,CN=Databases,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=test,DC=com"/>
    <entry key="l" value="London"/>
    <entry key="mail" value="paul.john@test.com"/>
    <entry key="mailNickname" value="PaulJ"/>
    <entry key="manager" value="CN=brock.lesnar,OU=Users,DC=test,DC=com"/>
    <entry key="memberOf">
      <value>
        <List>
          <String>CN=Test1,OU=Rights,OU=Groups,DC=test,DC=com</String>
          <String>CN=Test2,OU=Rights,OU=Groups,DC=test,DC=com</String>
          <String>CN=Test3,OU=Rights,OU=Groups,DC=test,DC=com</String>
          <String>CN=Test4,OU=Rights,OU=Groups,DC=test,DC=com</String>
        </List>
      </value>
    </entry>
  </Map>
</Attributes>

I wish to extract the value of "memberOf" from this column like this:

MEMBER_OF
---------
CN=Test1,OU=Rights,OU=Groups,DC=test,DC=com
CN=Test2,OU=Rights,OU=Groups,DC=test,DC=com
CN=Test3,OU=Rights,OU=Groups,DC=test,DC=com
CN=Test4,OU=Rights,OU=Groups,DC=test,DC=com

I have tried this with the below query which is returning null:

SELECT EXTRACTVALUE(xmltype(attributes), '/Attributes/Map/entry[@key="memberOf"]/value/List/@String')
FROM DATA;

I have also tried the below query which also returns null

SELECT EXTRACTVALUE(xmltype(attributes), '/Attributes/Map/entry[@key="memberOf"]/value[1]/List/@String')
FROM DATA;

Not sure if there is something else that needs to be passed in the query?

Body:
Your path ends with .../@String, which is looking for an attribute called String, not a node. But if you fix that you'd get:

ORA-19025: EXTRACTVALUE returns value of only one node

ExtractValue() is long-deprecated anyway. You could use XMLQuery() instead, but that gives you a single XML fragment rather than separate strings:

select xmlquery('/Attributes/Map/entry[@key="memberOf"]/value/List/String'
  passing xmltype(attributes)
  returning content) as member_of
from data;

MEMBER_OF
--------------------------------------------------------------------------------
<String>CN=Test1,OU=Rights,OU=Groups,DC=test,DC=com</String><String>CN=Test2,OU=
Rights,OU=Groups,DC=test,DC=com</String><String>CN=Test3,OU=Rights,OU=Groups,DC=
test,DC=com</String><String>CN=Test4,OU=Rights,OU=Groups,DC=test,DC=com</String>

Instead, use XMLTable() to get the individual values, as Bikash suggested - but it can be done more simply, without two XMLTable calls:

select x.member_of
from data
cross join XMLTable('/Attributes/Map/entry[@key="memberOf"]/value/List/String'
  passing XMLType(attributes)
  columns member_of varchar2(60) path '.'
) x;

MEMBER_OF
------------------------------------------------------------
CN=Test1,OU=Rights,OU=Groups,DC=test,DC=com
CN=Test2,OU=Rights,OU=Groups,DC=test,DC=com
CN=Test3,OU=Rights,OU=Groups,DC=test,DC=com
CN=Test4,OU=Rights,OU=Groups,DC=test,DC=com

Read more.

If you want to get other data in the same query, you can add those as more columns clauses, referring back up the tree - since the rest are single nodes, unless you have and need to show multiple account flags.

select x.*
from data
cross join XMLTable('/Attributes/Map/entry[@key="memberOf"]/value/List/String'
  passing XMLType(attributes)
  columns cn varchar2(20) path './../../../../entry[@key="cn"]/@value',
    department varchar2(10) path './../../../../entry[@key="department"]/@value',
    member_of varchar2(60) path '.'
) x;

CN                   DEPARTMENT MEMBER_OF
-------------------- ---------- ------------------------------------------------------------
paul.john            IT         CN=Test1,OU=Rights,OU=Groups,DC=test,DC=com
paul.john            IT         CN=Test2,OU=Rights,OU=Groups,DC=test,DC=com
paul.john            IT         CN=Test3,OU=Rights,OU=Groups,DC=test,DC=com
paul.john            IT         CN=Test4,OU=Rights,OU=Groups,DC=test,DC=com

although once you do that it might be easier to read and maintain if you do use multiple XMLTable calls:

select x1.cn, x1.department, x2.member_of
from data
cross join XMLTable('/Attributes/Map'
  passing XMLType(attributes)
  columns cn varchar2(20) path 'entry[@key="cn"]/@value',
    department varchar2(10) path 'entry[@key="department"]/@value',
    member_of_xml XMLType path 'entry[@key="memberOf"]'
) x1
cross join XMLTable('/entry/value/List/String'
  passing member_of_xml
  columns member_of varchar2(60) path '.'
) x2;

It's then simple to add a third XMLTable call to handle multiple account flags.

You could also do all this manipulation in a single XMLTable with a more complicated XPath with loops etc., but I think this is clearer and simpler, and unless you're dealing with large XML documents (and a lot of them) there may not be a significant performance difference.


问:
mysqli conversion PDO
How can I turn this to PDO? I tried, but I don't know how.
It was MySQLi at first and I tried to turn it to PDO and so, that was the result:

```<code><?php
    $username = $_POST['username'];
    $password = $_POST['password'];

    $stmt = $conn-> prepare("SELECT * FROM resident WHERE '$username' = ? AND '$password' = ?");
    //mysqli_stmt_bind_param($sql, "ss", $username, $password);
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $password);
    $stmt ->execute();
    mysqli_stmt_store_result($sql);
    $stmt-> BindParam($sql, $name, $username, $password);
    $response=array();
    $response["succes"] = false;
    while (mysqli_stmt_fetch($sql)) {
        $response["success"] = true;
        $response["name"]= $name;
    }
    echo json_encode ($response);
?>
</code>```

答:
You're confusing variables with column names. It's extremely important to note the difference. In a query '$username' is a string with a value in it, and probably a SQL injection bug. username without quotes is probably a column name.

You're also using named placeholders but you haven't named them. ? is an unnamed one. If you want a placeholder named :x then :x must appear in the query.

Your fixed code should look like:

```<code>$stmt = $conn-> prepare("SELECT * FROM resident WHERE username=:username AND password=:password");
//mysqli_stmt_bind_param($sql, "ss", $username, $password);

$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt ->execute();
</code>```

That is technically functional but VERY, VERY WRONG. Passwords must be properly hashed using, at the absolute least, password_hash. If you do that you can no longer fetch based on username and password, you need to fetch based on username and use password_verify to check if it's correct or not.

Disclaimer: Don't Write Your Own Login System

Unless this is strictly for academic purposes, all of this code is pretty much a waste of time. Any development framework has a solution for this. One example is Laravel where out of the box you get a full-featured authentication system.

Title: mysqli conversion PDO

Body:
How can I turn this to PDO? I tried, but I don't know how.
It was MySQLi at first and I tried to turn it to PDO and so, that was the result:

<?php
    $username = $_POST['username'];
    $password = $_POST['password'];

    $stmt = $conn-> prepare("SELECT * FROM resident WHERE '$username' = ? AND '$password' = ?");
    //mysqli_stmt_bind_param($sql, "ss", $username, $password);
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':password', $password);
    $stmt ->execute();
    mysqli_stmt_store_result($sql);
    $stmt-> BindParam($sql, $name, $username, $password);
    $response=array();
    $response["succes"] = false;
    while (mysqli_stmt_fetch($sql)) {
        $response["success"] = true;
        $response["name"]= $name;
    }
    echo json_encode ($response);
?>

Body:
You're confusing variables with column names. It's extremely important to note the difference. In a query '$username' is a string with a value in it, and probably a SQL injection bug. username without quotes is probably a column name.

You're also using named placeholders but you haven't named them. ? is an unnamed one. If you want a placeholder named :x then :x must appear in the query.

Your fixed code should look like:

$stmt = $conn-> prepare("SELECT * FROM resident WHERE username=:username AND password=:password");
//mysqli_stmt_bind_param($sql, "ss", $username, $password);

$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt ->execute();

That is technically functional but VERY, VERY WRONG. Passwords must be properly hashed using, at the absolute least, password_hash. If you do that you can no longer fetch based on username and password, you need to fetch based on username and use password_verify to check if it's correct or not.

Disclaimer: Don't Write Your Own Login System

Unless this is strictly for academic purposes, all of this code is pretty much a waste of time. Any development framework has a solution for this. One example is Laravel where out of the box you get a full-featured authentication system.


问:
How do I generate a custom designed QR Code including app icon?

Colorful QR Code

With App Icon in the center.

Almost like Snapchat.

For every new device a new Unique Qr Code

This QR Code cannot be scanned by anyother QR Scanner

and QR Code Scanner to scan only this QR Code

I have already searched online for this, but found nothing for android only got results for website based apps.

答:
Take a look at this
Library.
All your conditions are can fulfilled but Point 5 and 6 are not possible as all QR codes use the same format.

Happy Coding :)


问:
How to create a listview inside a listview?
I'm learning programming in android studio, I want to make clickable list view and when one of the item is clicked other list is shown underneath that clicked list item and everything else is pushed down, I already have some ideas how to make that but I don't know is there any layout item for that purpose or I have to make it by myself? Thank you.</p>

答:
You need to make Expandable ListView and here how it works:

Your activity_main.xml:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ExpandableListView
    android:id="@+id/myExpandableListView"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorLeft"
    android:divider="@android:color/white"
    android:dividerHeight="1dp" />
</code>```

then the List Group or the header of each expandable list:

```<code>list_header_group.xml

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

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/listTitle"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
            android:textColor="@android:color/blue"
            android:paddingTop="10dp"
            android:paddingBottom="8dp" />
    </LinearLayout>
</code>```

then the child items underneath each group header:

```<code>list_item_child.xml

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

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/expandedListItem"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
            android:paddingTop="10dp"
            android:paddingBottom="10dp" />
    </LinearLayout>
</code>```

your data init should be like weather you put it in a different java class or make it as a method:

```<code>import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ExpandableListDataInit {
    public static HashMap<String, List<String>> getData() {
        HashMap<String, List<String>> expandableList = new HashMap<String, List<String>>();

        List<String> Books = new ArrayList<String>();
        books.add("Programming");
        books.add("Stories");
        books.add("Kids");
        books.add("Fiction");

        List<String> movies= new ArrayList<String>();
        movies.add("Action");
        movies.add("Cartoon");
        movies.add("Others");

        List<String> toys = new ArrayList<String>();
        toys.add("Brand 1");
        toys.add("brand 2");

        expandableList.put("books", books);
        expandableList.put("mvies", movies);
        expandableList.put("toys", toys);
        return expandableList;
    }
}
</code>```

your adapter should look like this:

CustomExpAdapter.java

```<code>import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

public class CustomExpAdapter extends BaseExpandableListAdapter {

    private Context context;
    private List<String> expandableListTitle;
    private HashMap<String, List<String>> expandableListDetail;

    public CustomExpAdapter(Context context, List<String> expandableListTitle,
                                       HashMap<String, List<String>> expandableListDetail) {
        this.context = context;
        this.expandableListTitle = expandableListTitle;
        this.expandableListDetail = expandableListDetail;
    }

    @Override
    public Object getChild(int listPosition, int expandedListPosition) {
        return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
                .get(expandedListPosition);
    }

    @Override
    public long getChildId(int listPosition, int expandedListPosition) {
        return expandedListPosition;
    }

    @Override
    public View getChildView(int listPosition, final int expandedListPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {
        final String expandedListText = (String) getChild(listPosition, expandedListPosition);
        if (convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) this.context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.list_item, null);
        }
        TextView expandedListTextView = (TextView) convertView
                .findViewById(R.id.expandedListItem);
        expandedListTextView.setText(expandedListText);
        return convertView;
    }

    @Override
    public int getChildrenCount(int listPosition) {
        return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
                .size();
    }

    @Override
    public Object getGroup(int listPosition) {
        return this.expandableListTitle.get(listPosition);
    }

    @Override
    public int getGroupCount() {
        return this.expandableListTitle.size();
    }

    @Override
    public long getGroupId(int listPosition) {
        return listPosition;
    }

    @Override
    public View getGroupView(int listPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        String listTitle = (String) getGroup(listPosition);
        if (convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) this.context.
                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.list_group, null);
        }
        TextView listTitleTextView = (TextView) convertView
                .findViewById(R.id.listTitle);
        listTitleTextView.setTypeface(null, Typeface.BOLD);
        listTitleTextView.setText(listTitle);
        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int listPosition, int expandedListPosition) {
        return true;
    }
}
</code>```

the MainActivity.java should look pretty much like this:

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    ExpandableListView expandableListView;
    ExpandableListAdapter expandableListAdapter;
    List<String> expandableListTitle;
    HashMap<String, List<String>> expandableListDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        expandableListView = (ExpandableListView) findViewById(R.id.myExpandableListView);
        expandableListDetail = ExpandableListDataPump.getData();
        expandableListTitle = new ArrayList<String>(expandableListDetail.keySet());
        expandableListAdapter = new CustomExpandableListAdapter(this, expandableListTitle, expandableListDetail);
        expandableListView.setAdapter(expandableListAdapter);
        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        expandableListTitle.get(groupPosition) + " List Expanded.",
                        Toast.LENGTH_SHORT).show();
            }
        });

        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        expandableListTitle.get(groupPosition) + " List Collapsed.",
                        Toast.LENGTH_SHORT).show();

            }
        });

        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                Toast.makeText(
                        getApplicationContext(),
                        expandableListTitle.get(groupPosition)
                                + " -> "
                                + expandableListDetail.get(
                                expandableListTitle.get(groupPosition)).get(
                                childPosition), Toast.LENGTH_SHORT
                ).show();
                return false;
            }
        });
    }

}
</code>```

Body:
You need to make Expandable ListView and here how it works:

Your activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ExpandableListView
    android:id="@+id/myExpandableListView"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorLeft"
    android:divider="@android:color/white"
    android:dividerHeight="1dp" />

then the List Group or the header of each expandable list:

list_header_group.xml

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

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/listTitle"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
            android:textColor="@android:color/blue"
            android:paddingTop="10dp"
            android:paddingBottom="8dp" />
    </LinearLayout>

then the child items underneath each group header:

list_item_child.xml

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

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/expandedListItem"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
            android:paddingTop="10dp"
            android:paddingBottom="10dp" />
    </LinearLayout>

your data init should be like weather you put it in a different java class or make it as a method:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ExpandableListDataInit {
    public static HashMap<String, List<String>> getData() {
        HashMap<String, List<String>> expandableList = new HashMap<String, List<String>>();

        List<String> Books = new ArrayList<String>();
        books.add("Programming");
        books.add("Stories");
        books.add("Kids");
        books.add("Fiction");

        List<String> movies= new ArrayList<String>();
        movies.add("Action");
        movies.add("Cartoon");
        movies.add("Others");

        List<String> toys = new ArrayList<String>();
        toys.add("Brand 1");
        toys.add("brand 2");

        expandableList.put("books", books);
        expandableList.put("mvies", movies);
        expandableList.put("toys", toys);
        return expandableList;
    }
}

your adapter should look like this:

CustomExpAdapter.java

import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

public class CustomExpAdapter extends BaseExpandableListAdapter {

    private Context context;
    private List<String> expandableListTitle;
    private HashMap<String, List<String>> expandableListDetail;

    public CustomExpAdapter(Context context, List<String> expandableListTitle,
                                       HashMap<String, List<String>> expandableListDetail) {
        this.context = context;
        this.expandableListTitle = expandableListTitle;
        this.expandableListDetail = expandableListDetail;
    }

    @Override
    public Object getChild(int listPosition, int expandedListPosition) {
        return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
                .get(expandedListPosition);
    }

    @Override
    public long getChildId(int listPosition, int expandedListPosition) {
        return expandedListPosition;
    }

    @Override
    public View getChildView(int listPosition, final int expandedListPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {
        final String expandedListText = (String) getChild(listPosition, expandedListPosition);
        if (convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) this.context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.list_item, null);
        }
        TextView expandedListTextView = (TextView) convertView
                .findViewById(R.id.expandedListItem);
        expandedListTextView.setText(expandedListText);
        return convertView;
    }

    @Override
    public int getChildrenCount(int listPosition) {
        return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
                .size();
    }

    @Override
    public Object getGroup(int listPosition) {
        return this.expandableListTitle.get(listPosition);
    }

    @Override
    public int getGroupCount() {
        return this.expandableListTitle.size();
    }

    @Override
    public long getGroupId(int listPosition) {
        return listPosition;
    }

    @Override
    public View getGroupView(int listPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        String listTitle = (String) getGroup(listPosition);
        if (convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) this.context.
                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.list_group, null);
        }
        TextView listTitleTextView = (TextView) convertView
                .findViewById(R.id.listTitle);
        listTitleTextView.setTypeface(null, Typeface.BOLD);
        listTitleTextView.setText(listTitle);
        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int listPosition, int expandedListPosition) {
        return true;
    }
}

the MainActivity.java should look pretty much like this:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    ExpandableListView expandableListView;
    ExpandableListAdapter expandableListAdapter;
    List<String> expandableListTitle;
    HashMap<String, List<String>> expandableListDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        expandableListView = (ExpandableListView) findViewById(R.id.myExpandableListView);
        expandableListDetail = ExpandableListDataPump.getData();
        expandableListTitle = new ArrayList<String>(expandableListDetail.keySet());
        expandableListAdapter = new CustomExpandableListAdapter(this, expandableListTitle, expandableListDetail);
        expandableListView.setAdapter(expandableListAdapter);
        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        expandableListTitle.get(groupPosition) + " List Expanded.",
                        Toast.LENGTH_SHORT).show();
            }
        });

        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                Toast.makeText(getApplicationContext(),
                        expandableListTitle.get(groupPosition) + " List Collapsed.",
                        Toast.LENGTH_SHORT).show();

            }
        });

        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                Toast.makeText(
                        getApplicationContext(),
                        expandableListTitle.get(groupPosition)
                                + " -> "
                                + expandableListDetail.get(
                                expandableListTitle.get(groupPosition)).get(
                                childPosition), Toast.LENGTH_SHORT
                ).show();
                return false;
            }
        });
    }

}


问:
How access a context value from a variable in django template
I have a Question model that I am passing as a context to the template

```<code>class Question(models.Model):
    possible_answer1 = models.TextField(
        'Possible Answer 1',
        max_length=1000,
        default='none'
    )
    possible_answer2 = models.TextField(
        'Possible Answer 2',
        max_length=1000,
        default='none',
        blank=True
    )
    possible_answer3 = models.TextField(
        'Possible Answer 3',
        max_length=1000,
        default='none',
        blank=True
    )
    possible_answer4 = models.TextField(
        'Possible Answer 4',
        max_length=1000,
        default='none',
        blank=True
    )
    possible_answer5 = models.TextField(
        'Possible Answer 5',
        max_length=1000,
        default='none',
        blank=True
    )
    possible_answer6 = models.TextField(
        'Possible Answer 6',
        max_length=1000,
        default='none',
        blank=True
    )
</code>```

I can access all the answer object no problem if I use

```<code>{{ context.this_question.question.possible_answer1 }}
{{ context.this_question.question.possible_answer2 }}
.
.
{{ context.this_question.question.possible_answer6 }}
</code>```

The problem is that I don't need all 6 answers to be displayed all the time so I was trying to build for loop that would only dispay what I need at a certain time based on the following thread using the with tag How to concatenate strings in django templates?1 . In the example below mylist contain four elements so I tried this

```<code>{% for x in mylist %}
    {% with possible_answer='context.this_question.question.possible_answer'|add:forloop.counter %}
      {{ possible_answer }}
    {% endwith %}
{% endfor %}
</code>```

In the hope that it would generate

```<code>{{ context.this_question.question.possible_answer1 }}
{{ context.this_question.question.possible_answer2 }}
{{ context.this_question.question.possible_answer3 }}
{{ context.this_question.question.possible_answer4 }}
</code>```

and consequently display the corresponding item from the context object as if I was typing it myself but it doesn't work. Nothing is displaying

If replace forloop.counter with any string it would then display the concatened string  without trying fetch the value in the context.

Anyone has an idea on how to achieve this?

答:
That kind of logic is better generated at the view. You may as well, will need to rethink your database architecture. When I am presented that kind of problems I preferably create two diferent models.

For instance a Question model and an Answer model. The Answer model would have a Foreign Key to the Question model and then with a simple filter get all the answers related to that question. It is a simple programming paradigm of SQL databases.

models.py

```<code>class Question(models.Model):
  Body = models.TextField(max_length=1000,default='none',blank=True)

class Answer(models.Model):
  Question = models.ForeignKey(Question)
  Body = models.TextField(max_length=1000,default='none',blank=True)
</code>```

views.py:

```<code>Q = Question.objects.get(pk='id')
A = Answer.objects.filter(Question=Q)
</code>```

I hope it helps!

Body:
I have a Question model that I am passing as a context to the template

class Question(models.Model):
    possible_answer1 = models.TextField(
        'Possible Answer 1',
        max_length=1000,
        default='none'
    )
    possible_answer2 = models.TextField(
        'Possible Answer 2',
        max_length=1000,
        default='none',
        blank=True
    )
    possible_answer3 = models.TextField(
        'Possible Answer 3',
        max_length=1000,
        default='none',
        blank=True
    )
    possible_answer4 = models.TextField(
        'Possible Answer 4',
        max_length=1000,
        default='none',
        blank=True
    )
    possible_answer5 = models.TextField(
        'Possible Answer 5',
        max_length=1000,
        default='none',
        blank=True
    )
    possible_answer6 = models.TextField(
        'Possible Answer 6',
        max_length=1000,
        default='none',
        blank=True
    )

I can access all the answer object no problem if I use

{{ context.this_question.question.possible_answer1 }}
{{ context.this_question.question.possible_answer2 }}
.
.
{{ context.this_question.question.possible_answer6 }}

The problem is that I don't need all 6 answers to be displayed all the time so I was trying to build for loop that would only dispay what I need at a certain time based on the following thread using the with tag How to concatenate strings in django templates?1 . In the example below mylist contain four elements so I tried this

{% for x in mylist %}
    {% with possible_answer='context.this_question.question.possible_answer'|add:forloop.counter %}
      {{ possible_answer }}
    {% endwith %}
{% endfor %}

In the hope that it would generate

{{ context.this_question.question.possible_answer1 }}
{{ context.this_question.question.possible_answer2 }}
{{ context.this_question.question.possible_answer3 }}
{{ context.this_question.question.possible_answer4 }}

and consequently display the corresponding item from the context object as if I was typing it myself but it doesn't work. Nothing is displaying

If replace forloop.counter with any string it would then display the concatened string  without trying fetch the value in the context.

Anyone has an idea on how to achieve this?

Body:
That kind of logic is better generated at the view. You may as well, will need to rethink your database architecture. When I am presented that kind of problems I preferably create two diferent models.

For instance a Question model and an Answer model. The Answer model would have a Foreign Key to the Question model and then with a simple filter get all the answers related to that question. It is a simple programming paradigm of SQL databases.

models.py

class Question(models.Model):
  Body = models.TextField(max_length=1000,default='none',blank=True)

class Answer(models.Model):
  Question = models.ForeignKey(Question)
  Body = models.TextField(max_length=1000,default='none',blank=True)

views.py:

Q = Question.objects.get(pk='id')
A = Answer.objects.filter(Question=Q)

I hope it helps!


问:
Understanding quantifier traversing in Z3
I'm trying to understand traversing quantified formula in z3 (i'm using z3py). Have no idea how to pickup the quantified variables. For example in code shown below i'm trying to print the same formula and getting error.

```<code>from z3 import *

def traverse(e):
  if is_quantifier(e):
    var_list = []
    if e.is_forall():
        for i in range(e.num_vars()):
            var_list.append(e.var_name(i))
        return ForAll (var_list, traverse(e.body()))

x, y = Bools('x y')
fml =  ForAll(x, ForAll (y, And(x,y)))
same_formula = traverse( fml )
print same_formula
</code>```

With little search i got to know that z3 uses De Bruijn index and i have to get something like Var(1, BoolSort()). I can think of using var_sort() but how to get the formula to return the variable correctly. Stuck here for some time.

答:
var_list is a list of strings, but ForAll expects a list of constants. Also, traverse should return e when it's not a quantifier. Here's a modified example:

```<code>from z3 import *

def traverse(e):
  if is_quantifier(e):
    var_list = []
    if e.is_forall():
        for i in range(e.num_vars()):
            c = Const(e.var_name(i) + "-traversed", e.var_sort(i))
            var_list.append(c)
        return ForAll (var_list, traverse(e.body()))
  else:
    return e

x, y = Bools('x y')
fml =  ForAll(x, ForAll (y, And(x,y)))
same_formula = traverse( fml )
print(same_formula)
</code>```

Body:
I'm trying to understand traversing quantified formula in z3 (i'm using z3py). Have no idea how to pickup the quantified variables. For example in code shown below i'm trying to print the same formula and getting error.

from z3 import *

def traverse(e):
  if is_quantifier(e):
    var_list = []
    if e.is_forall():
        for i in range(e.num_vars()):
            var_list.append(e.var_name(i))
        return ForAll (var_list, traverse(e.body()))

x, y = Bools('x y')
fml =  ForAll(x, ForAll (y, And(x,y)))
same_formula = traverse( fml )
print same_formula

With little search i got to know that z3 uses De Bruijn index and i have to get something like Var(1, BoolSort()). I can think of using var_sort() but how to get the formula to return the variable correctly. Stuck here for some time.

Body:
var_list is a list of strings, but ForAll expects a list of constants. Also, traverse should return e when it's not a quantifier. Here's a modified example:

from z3 import *

def traverse(e):
  if is_quantifier(e):
    var_list = []
    if e.is_forall():
        for i in range(e.num_vars()):
            c = Const(e.var_name(i) + "-traversed", e.var_sort(i))
            var_list.append(c)
        return ForAll (var_list, traverse(e.body()))
  else:
    return e

x, y = Bools('x y')
fml =  ForAll(x, ForAll (y, And(x,y)))
same_formula = traverse( fml )
print(same_formula)


问:
show custom dialog only once with onclick Button
i'm trying to show my custom dialog only once ; firstly i have a custom dialog contains one button OK when i click ok button and re open app i want to hide the custom dialog for that i tried to use SharedPreference

```<code>   SharedPreferences.Editor editor;
    SharedPreferences pref;
    @SuppressLint("CommitPrefEdits")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pref = getApplicationContext().getSharedPreferences("MyPref", 0);
        editor = pref.edit();
        editor.putBoolean("key_name", false);

/**/

 if (pref.getBoolean("key_name", true)) {
                users();
  }

private void users() {
        final Dialog myDialog = new Dialog(MainActivity.this);
        myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        assert myDialog.getWindow() != null;
        myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        myDialog.setCancelable(false);
        myDialog.setContentView(R.layout.users_artwork_dialog);
        Button okbtn = myDialog.findViewById(R.id.okbtn);

        okbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
                @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = pref.edit();
                editor.putBoolean("key_name", false);
                myDialog.dismiss();
            }
        });
        myDialog.show();
    }
</code>```

答:
You should either commit() or apply() SharedPreference editor.

void commit() :

  Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.

void apply ()
  Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.

Check your modified code as well

```<code>    SharedPreferences.Editor editor;
    SharedPreferences pref;

    @SuppressLint("CommitPrefEdits")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pref = getApplicationContext().getSharedPreferences("MyPref", 0);
        editor = pref.edit();
        editor.putBoolean("key_name", true);
        //Add commit()
        editor.commit();

/**/

        if (pref.getBoolean("key_name", false)) {
            users();
        }
    }
    private void users() {
        final Dialog myDialog = new Dialog(MainActivity.this);
        myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        assert myDialog.getWindow() != null;
        myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        myDialog.setCancelable(false);
        myDialog.setContentView(R.layout.users_artwork_dialog);
        Button okbtn = myDialog.findViewById(R.id.okbtn);

        okbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
                @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = pref.edit();
                editor.putBoolean("key_name", false);
                //Add commit()
                editor.commit();
                myDialog.dismiss();
            }
        });
        myDialog.show();
    }
</code>```

Body:
i'm trying to show my custom dialog only once ; firstly i have a custom dialog contains one button OK when i click ok button and re open app i want to hide the custom dialog for that i tried to use SharedPreference

   SharedPreferences.Editor editor;
    SharedPreferences pref;
    @SuppressLint("CommitPrefEdits")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pref = getApplicationContext().getSharedPreferences("MyPref", 0);
        editor = pref.edit();
        editor.putBoolean("key_name", false);

/**/

 if (pref.getBoolean("key_name", true)) {
                users();
  }

private void users() {
        final Dialog myDialog = new Dialog(MainActivity.this);
        myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        assert myDialog.getWindow() != null;
        myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        myDialog.setCancelable(false);
        myDialog.setContentView(R.layout.users_artwork_dialog);
        Button okbtn = myDialog.findViewById(R.id.okbtn);

        okbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
                @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = pref.edit();
                editor.putBoolean("key_name", false);
                myDialog.dismiss();
            }
        });
        myDialog.show();
    }

Body:
You should either commit() or apply() SharedPreference editor.

void commit() :

  Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.

void apply ()
  Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.

Check your modified code as well

    SharedPreferences.Editor editor;
    SharedPreferences pref;

    @SuppressLint("CommitPrefEdits")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pref = getApplicationContext().getSharedPreferences("MyPref", 0);
        editor = pref.edit();
        editor.putBoolean("key_name", true);
        //Add commit()
        editor.commit();

/**/

        if (pref.getBoolean("key_name", false)) {
            users();
        }
    }
    private void users() {
        final Dialog myDialog = new Dialog(MainActivity.this);
        myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        assert myDialog.getWindow() != null;
        myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        myDialog.setCancelable(false);
        myDialog.setContentView(R.layout.users_artwork_dialog);
        Button okbtn = myDialog.findViewById(R.id.okbtn);

        okbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
                @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = pref.edit();
                editor.putBoolean("key_name", false);
                //Add commit()
                editor.commit();
                myDialog.dismiss();
            }
        });
        myDialog.show();
    }


问:
scp or sftp copy multiple files with single command
I'd like to copy files from/to remote server in different directories.
For example, I want to run these 4 commands at once.

```<code>scp remote:A/1.txt local:A/1.txt
scp remote:A/2.txt local:A/2.txt
scp remote:B/1.txt local:B/1.txt
scp remote:C/1.txt local:C/1.txt
</code>```

What is the easiest way to do that?

答:
The answers with {file1,file2,file3} works only with bash (on remote or locally)

The real way is :

```<code>scp user@remote:'/path1/file1 /path2/file2 /path3/file3' /localPath
</code>```

Body:
I'd like to copy files from/to remote server in different directories.
For example, I want to run these 4 commands at once.

scp remote:A/1.txt local:A/1.txt
scp remote:A/2.txt local:A/2.txt
scp remote:B/1.txt local:B/1.txt
scp remote:C/1.txt local:C/1.txt

What is the easiest way to do that?

Body:
The answers with {file1,file2,file3} works only with bash (on remote or locally)

The real way is :

scp user@remote:'/path1/file1 /path2/file2 /path3/file3' /localPath


问:
Deshuffle text with C
I wanted to get an opinion here. Would it be possible to write a C program that deshuffles a text file? What do I mean by that? Say I have the following data in a textfile:

```<code>1  X
4  T
3  Z
2  L
</code>```

And I wanted to deshuffle it and output another file as so:

```<code>1  X
2  L
3  Z
4  T
</code>```

Such that all of the data following the number is preserved with the actual index number. Do know that I have 40,500 shuffled entities, so that should probably be taken into account since that could take a long time if the program needs to loop through all of the entities for each entity...And I only used letters for representation. The actual data files don't have letters, but rather have floats. Sorry if this causes any confusion

So, bottom line, would this be possible with C? And if so, could I get a hint at where to start? I could obviously input all of the textfile data into an array dat[][], but how should I deshuffle it then?

Thanks!
Amit

答: If you know the largest index in the file and there are no holes (i.e. all indices are present), you can create an array of that size, then as you read each line of the file, put the data into the correct location in the array. When you're done reading the file, your array will have all the elements in the correct order.</p>

Title: Deshuffle text with C

Body:
I wanted to get an opinion here. Would it be possible to write a C program that deshuffles a text file? What do I mean by that? Say I have the following data in a textfile:

1  X
4  T
3  Z
2  L

And I wanted to deshuffle it and output another file as so:

1  X
2  L
3  Z
4  T

Such that all of the data following the number is preserved with the actual index number. Do know that I have 40,500 shuffled entities, so that should probably be taken into account since that could take a long time if the program needs to loop through all of the entities for each entity...And I only used letters for representation. The actual data files don't have letters, but rather have floats. Sorry if this causes any confusion

So, bottom line, would this be possible with C? And if so, could I get a hint at where to start? I could obviously input all of the textfile data into an array dat[][], but how should I deshuffle it then?

Thanks!
Amit


问:
read docx file error
```<code>import docx2txt

my_text=docx2txt.process("file1.docx")
print(my_text)
</code>```

when I want to read the docx file from this code it shows the following error:

```<code>  File "/usr/lib/python3.5/zipfile.py", line 1093, in _RealGetContents
    raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file
</code>```

答:
As @cowbert mentioned in the comment section, your file likely has been corrupted or it's in a zip format. Your provided code is correct. You can also use textract which supports .docx files:

```<code>import textract
text = textract.process("path/to/file.extension")
</code>```

This package is built on top of several python packages and other source libraries. Once you install it, several packages (including docx2txt) are all installed by default with this package.

Title: read docx file error

Body:
import docx2txt

my_text=docx2txt.process("file1.docx")
print(my_text)

when I want to read the docx file from this code it shows the following error:

  File "/usr/lib/python3.5/zipfile.py", line 1093, in _RealGetContents
    raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file

Body:
As @cowbert mentioned in the comment section, your file likely has been corrupted or it's in a zip format. Your provided code is correct. You can also use textract which supports .docx files:

import textract
text = textract.process("path/to/file.extension")

This package is built on top of several python packages and other source libraries. Once you install it, several packages (including docx2txt) are all installed by default with this package.

ContentLicense: CC BY-SA 4.0


问:
Multiple file upload using s3
I'd like to upload files to my s3 bucket via the aws golang sdk. I have a web server listening to POST requests and I'm expecting to receive multiple files of any type.

Using the sdk, the s3 struct PutObjectInput expects Body to be of type io.ReadSeeker and I'm not sure how to extract the content from the files uploaded and in turn satisfy the io.ReadSeeker interface.

```<code>images := r.MultipartForm.File

for _, files := range images {
    for _, f := range files {

        # In my handler, I can loop over the files
        # and see the content
        fmt.Println(f.Header)

        _, err = svc.PutObjectWithContext(ctx, &s3.PutObjectInput{
                Bucket: aws.String("bucket"),
                Key:    aws.String("key"),
                Body:   FILE_CONTENT_HERE,
            })
    }
}
</code>```

答:
Use the FileHeader.Open method to get an io.ReadSeeker.

```<code>    f, err := f.Open()
    if err != nil {
       // handle error
    }

    _, err = svc.PutObjectWithContext(ctx, &s3.PutObjectInput{
            Bucket: aws.String("bucket"),
            Key:    aws.String("key"),
            Body:   f,
        })
</code>```

Open returns a File. This type satisfies the io.ReadSeeker interface.

Title: Multiple file upload using s3

Body:
I'd like to upload files to my s3 bucket via the aws golang sdk. I have a web server listening to POST requests and I'm expecting to receive multiple files of any type.

Using the sdk, the s3 struct PutObjectInput expects Body to be of type io.ReadSeeker and I'm not sure how to extract the content from the files uploaded and in turn satisfy the io.ReadSeeker interface.

images := r.MultipartForm.File

for _, files := range images {
    for _, f := range files {

        # In my handler, I can loop over the files
        # and see the content
        fmt.Println(f.Header)

        _, err = svc.PutObjectWithContext(ctx, &s3.PutObjectInput{
                Bucket: aws.String("bucket"),
                Key:    aws.String("key"),
                Body:   FILE_CONTENT_HERE,
            })
    }
}

Body:
Use the FileHeader.Open method to get an io.ReadSeeker.

    f, err := f.Open()
    if err != nil {
       // handle error
    }

    _, err = svc.PutObjectWithContext(ctx, &s3.PutObjectInput{
            Bucket: aws.String("bucket"),
            Key:    aws.String("key"),
            Body:   f,
        })

Open returns a File. This type satisfies the io.ReadSeeker interface.


问:
Is there an API to force Facebook to scrape a page again?
I'm aware you can force update a page's cache by entering the URL on Facebook's debugger tool while been logged in as admin for that app/page:
https://developers.facebook.com/tools/debug

But what I need is a way to automatically call an API endpoint or something from our internal app whenever somebody from our Sales department updates the main image of one of our pages. It is not an option to ask thousands of sales people to login as an admin and manually update a page's cache whenever they update one of our item's description or image.

We can't afford to wait 24 hours for Facebook to update its cache because we're getting daily complaints from our clients whenever they don't see a change showing up as soon as we change it on our side.

答:
Here's my Ruby solution using Koala gem and Facebook API v2.9

```<code>    api = Koala::Facebook::API.new(access_token)
    response = api.put_object(nil, nil, {scrape: true, id: "url-of-page-to-scrape"})
</code>```

response should be a hash of attributes retrieved from the og: meta tags on the page which was scraped.

Body:
Here's my Ruby solution using Koala gem and Facebook API v2.9

    api = Koala::Facebook::API.new(access_token)
    response = api.put_object(nil, nil, {scrape: true, id: "url-of-page-to-scrape"})

response should be a hash of attributes retrieved from the og: meta tags on the page which was scraped.


问:
Imagick not working, returns no errors
So I am trying to resize an image from a form which is a .png, like so:

```<code>$logo = new Imagick($_FILES['icon']['tmp_name']);
$logo->resizeImage(256, 256, 0, 1);
</code>```

When I die the $_FILES['icon']['tmp_name'] it returns the .tmp file like so:

```<code>C:\wamp64\tmp\php7895.tmp
</code>```

But when running the above code, it throws no errors, but just breaks the script, if I add a die after the code, it doesn't reach that part.

I have checked my error logs, which is empty, and my Imagick is enabled:

Is there anything else I could try or how to fix it?

答:
I think you are using wrong filtering. Try this:

```<code>$logo->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
</code>```

Documentation here

Title: Imagick not working, returns no errors

Body:
So I am trying to resize an image from a form which is a .png, like so:

$logo = new Imagick($_FILES['icon']['tmp_name']);
$logo->resizeImage(256, 256, 0, 1);

When I die the $_FILES['icon']['tmp_name'] it returns the .tmp file like so:

C:\wamp64\tmp\php7895.tmp

But when running the above code, it throws no errors, but just breaks the script, if I add a die after the code, it doesn't reach that part.

I have checked my error logs, which is empty, and my Imagick is enabled:

Is there anything else I could try or how to fix it?

Body:
I think you are using wrong filtering. Try this:

$logo->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);

Documentation here


问:
Filter reactive data with button clicked on leaflet map popup
I have a shiny app that displays information to users. Each line represents a place, so you can use two selectInputs to filter data using specific city names and areas. I'm using reactive() to filter the data. The resulting data is displayed below with info boxes and a map showing the location of each place.

The info boxes have an action button that, once clicked, displays only the marker corresponding to the box. I'm updating my map with leafletProxy.

Also, in my map, I have makers with popups containing an action button, so I want to click in that button and show only the info box corresponding to the place on the map, and not displaying the others. I thought I could do that filtering again the data wih eventReactive when the user click on the button on the map, but I can't seem to do that. The ID of the buttons are dinamically generated with lapply, so I don't know how to declare that in an observeEvent or eventReactive. Any suggestions?

Code example below:

```<code>name<-sample(c('a','b','c'),replace=T,5)
area1<-sample(c(0,1),replace=T,5)
area2<-sample(c(0,1),replace=T,5)
area3<-sample(c(0,1),replace=T,5)
LAT<-runif(5,min=-26, max=-22)
LONG<-runif(5,min=-54, max=-48)
data<-data.frame(name,area1,area2,area3,LAT,LONG)

ui <- shinyUI(fluidPage(
selectInput('muni',label='Select city',
             choices=c('Show all',sort(levels(data$name)),selected=NULL)),
selectInput('area',label='Select area',
            choices=c('Show all','area1','area2','area3',selected=NULL)),
HTML('<table border="0"><tr><td style="padding: 8px">
      <a id="reset" href="#" style="text-indent: 0px;"
      class="action-button shiny-bound-input">
      Reset</a></td></tr></table>'),
htmlOutput('box'),
leafletOutput('map')
))

server <- function (input, output, session) {

data1<-reactive({
  if (input$muni!='Show all') {
    data<-data[which(data$name==input$muni),]
    }
  if (input$area!='Show all') {
    data<-data[data[input$area]!=0,]
  }
  return(data)
})

observeEvent(input$reset, {
   updateSelectInput(session,'muni',selected='Show all')
   updateSelectInput(session,'area',selected='Show all')
})

output$box <- renderUI({

  data<-data1()
  num<-as.integer(nrow(data))
  func_areas <- function(areas) sub(",\\s+([^,]+)$", " and \\1",
  toString(areas))

  lapply(1:num, function(i) {
      bt <- paste0('go_btn',i)
      fluidRow(
        HTML(paste0('<div style="border: 1px solid #00000026;
                      border-radius: 10px; padding: 10px;">
                     <span style="font-size:14px font-weight:bold;">',
                      data$name[i],' - areas: ',
                     func_areas(colnames(data[i,names(data)[2:4]])
                     [which(data[i,names(data)[2:4]]!=0)]),'</span></br>',
        actionButton(bt,'See map',icon=icon('map-marker',lib='font-awesome')),
        HTML('</div></br>')
                    )))
  })
})

output$map<-renderLeaflet({

  data<-data1()
  rownames(data)<-seq(1:nrow(data))
  pop<-paste0('<strong>',data$name,'</strong></br>',
              '<a id="info',rownames(data),'" href="#" style="text-indent: 0px;"
               class="action-button shiny-bound-input"
              onclick="{Shiny.onInputChange(\'info',rownames(data),'\',
             (Math.random() * 1000) + 1);}">
              <i class="fa fa-info-circle"></i>Show info</a>')

  leaflet(data) %>%
    addProviderTiles("Esri.WorldTopoMap") %>%
    setView(-51.5,-24.8,zoom=7) %>%
    addMarkers(lng=~data$LONG,lat=~data$LAT,popup=pop)

})

lapply(1:nrow(data), function(i) {
  bt <- paste0('go_btn',i)
  observeEvent(input[[bt]], {
    data<-data1()
    rownames(data)<-seq(1:nrow(data))

    pop<-paste0('<strong>',data$name[i],'</strong></br>',
                '<a id="info',rownames(data),'" href="#" style="text-indent: 0px;"
                class="action-button shiny-bound-input"
                onclick="{Shiny.onInputChange(\'info',rownames(data),'\',
               (Math.random() * 1000) + 1);}">
                <i class="fa fa-info-circle"></i>Show info</a>')

    leafletProxy('map',data=data,session=session) %>%
      clearMarkers() %>%
      setView(data$LONG[i],data$LAT[i],zoom=15) %>%
      addMarkers(lng=data$LONG[i],lat=data$LAT[i],popup=pop)
  })
})
}

shinyApp(ui, server)
</code>```

Thank you for any help and sorry if I wrote something wrong, first time using stackoverflow.

答:
Okay, I am not 100% sure this is the desired behavior, but I think this gives you enough to work with so you can achieve what you want.

I added an id to the div's you created, and then used lapply to create a separate observeEvent for each button. This observeEvent then triggers show or hide from the shinyjs package on the appropriate divs.

I added #added by Florian or modified by Florian above the lines I added or modifed, since the code is quite long. I hope this helps! Let me know if any other questions arise.

```<code># Added by Florian
library(shinyjs)

name<-sample(c('a','b','c'),replace=T,5)
area1<-sample(c(0,1),replace=T,5)
area2<-sample(c(0,1),replace=T,5)
area3<-sample(c(0,1),replace=T,5)
LAT<-runif(5,min=-26, max=-22)
LONG<-runif(5,min=-54, max=-48)
data<-data.frame(name,area1,area2,area3,LAT,LONG)

ui <- shinyUI(fluidPage(
  # Added by Florian
  useShinyjs(),
  selectInput('muni',label='Select city',
              choices=c('Show all',sort(levels(data$name)),selected=NULL)),
  selectInput('area',label='Select area',
              choices=c('Show all','area1','area2','area3',selected=NULL)),
  HTML('<table border="0"><tr><td style="padding: 8px">
       <a id="reset" href="#" style="text-indent: 0px;"
       class="action-button shiny-bound-input">
       Reset</a></td></tr></table>'),
  htmlOutput('box'),
  leafletOutput('map')
  ))

server <- function (input, output, session) {

  data1<-reactive({
    if (input$muni!='Show all') {
      data<-data[which(data$name==input$muni),]
    }
    if (input$area!='Show all') {
      data<-data[data[input$area]!=0,]
    }
    return(data)
  })

  observeEvent(input$reset, {
    updateSelectInput(session,'muni',selected='Show all')
    updateSelectInput(session,'area',selected='Show all')

    # Added by Florian
    for (i in 1:as.integer(nrow(data)))
    {
        shinyjs::show(paste0('mydiv_',i))
    }

  })

  output$box <- renderUI({

    data<-data1()
    num<-as.integer(nrow(data))
    func_areas <- function(areas) sub(",\\s+([^,]+)$", " and \\1",
                                      toString(areas))
    #modified by Florian: added div id
    lapply(1:num, function(i) {
      bt <- paste0('go_btn',i)
      fluidRow(
        HTML(paste0('<div id="mydiv_',i,'"; style="border: 1px solid #00000026;
                    border-radius: 10px; padding: 10px;">
                    <span style="font-size:14px font-weight:bold;">',
                    data$name[i],' - areas: ',
                    func_areas(colnames(data[i,names(data)[2:4]])
                               [which(data[i,names(data)[2:4]]!=0)]),'</span></br>',
                    actionButton(bt,'See map',icon=icon('map-marker',lib='font-awesome')),
                    HTML('</div></br>')
        )))
    })
  })

  # Added by Florian
  lapply(1:as.integer(nrow(data)),function(x)
  {
    observeEvent(input[[paste0('go_btn',x)]], {
      logjs('Click!')
      shinyjs::show(paste0('mydiv_',x))
      for (i in 1:as.integer(nrow(data)))
      {
        if(i!=x)
        {
          shinyjs::hide(paste0('mydiv_',i))
        }
      }

    } )

  })

  output$map<-renderLeaflet({

    data<-data1()
    pop<-paste0('<strong>',data$name,'</strong></br>',
                '<a id="info" href="#" style="text-indent: 0px;"
                class="action-button shiny-bound-input"
                onclick="{Shiny.onInputChange(\'info\', (Math.random() * 1000) + 1);}">
                <i class="fa fa-info-circle"></i>Show info</a>')

    leaflet(data) %>%
      addProviderTiles("Esri.WorldTopoMap") %>%
      setView(-51.5,-24.8,zoom=7) %>%
      addMarkers(lng=~data$LONG,lat=~data$LAT,popup=pop)

  })

  lapply(1:nrow(data), function(i) {
    bt <- paste0('go_btn',i)
    observeEvent(input[[bt]], {
      data<-data1()

      pop<-paste0('<strong>',data$name[i],'</strong></br>',
                  '<a id="info" href="#" style="text-indent: 0px;"
                  class="action-button shiny-bound-input"
                  onclick="{Shiny.onInputChange(\'info\', (Math.random() * 1000) + 1);}">
                  <i class="fa fa-info-circle"></i>Show info</a>')

      leafletProxy('map',data=data,session=session) %>%
        clearMarkers() %>%
        setView(data$LONG[i],data$LAT[i],zoom=15) %>%
        addMarkers(lng=data$LONG[i],lat=data$LAT[i],popup=pop)
    })
  })
}

shinyApp(ui, server)
</code>```

Body:
I have a shiny app that displays information to users. Each line represents a place, so you can use two selectInputs to filter data using specific city names and areas. I'm using reactive() to filter the data. The resulting data is displayed below with info boxes and a map showing the location of each place.

The info boxes have an action button that, once clicked, displays only the marker corresponding to the box. I'm updating my map with leafletProxy.

Also, in my map, I have makers with popups containing an action button, so I want to click in that button and show only the info box corresponding to the place on the map, and not displaying the others. I thought I could do that filtering again the data wih eventReactive when the user click on the button on the map, but I can't seem to do that. The ID of the buttons are dinamically generated with lapply, so I don't know how to declare that in an observeEvent or eventReactive. Any suggestions?

Code example below:

name<-sample(c('a','b','c'),replace=T,5)
area1<-sample(c(0,1),replace=T,5)
area2<-sample(c(0,1),replace=T,5)
area3<-sample(c(0,1),replace=T,5)
LAT<-runif(5,min=-26, max=-22)
LONG<-runif(5,min=-54, max=-48)
data<-data.frame(name,area1,area2,area3,LAT,LONG)

ui <- shinyUI(fluidPage(
selectInput('muni',label='Select city',
             choices=c('Show all',sort(levels(data$name)),selected=NULL)),
selectInput('area',label='Select area',
            choices=c('Show all','area1','area2','area3',selected=NULL)),
HTML('

      Reset

'),
htmlOutput('box'),
leafletOutput('map')
))

server <- function (input, output, session) {

data1<-reactive({
  if (input$muni!='Show all') {
    data<-data[which(data$name==input$muni),]
    }
  if (input$area!='Show all') {
    data<-data[data[input$area]!=0,]
  }
  return(data)
})

observeEvent(input$reset, {
   updateSelectInput(session,'muni',selected='Show all')
   updateSelectInput(session,'area',selected='Show all')
})

output$box <- renderUI({

  data<-data1()
  num<-as.integer(nrow(data))
  func_areas <- function(areas) sub(",\\s+([^,]+)$", " and \\1",
  toString(areas))

  lapply(1:num, function(i) {
      bt <- paste0('go_btn',i)
      fluidRow(
        HTML(paste0('

                     ',
                      data$name[i],' - areas: ',
                     func_areas(colnames(data[i,names(data)[2:4]])
                     [which(data[i,names(data)[2:4]]!=0)]),'
',
        actionButton(bt,'See map',icon=icon('map-marker',lib='font-awesome')),
        HTML('

')
                    )))
  })
})

output$map<-renderLeaflet({

  data<-data1()
  rownames(data)<-seq(1:nrow(data))
  pop<-paste0('',data$name,'
',
              '
              Show info')

  leaflet(data) %>%
    addProviderTiles("Esri.WorldTopoMap") %>%
    setView(-51.5,-24.8,zoom=7) %>%
    addMarkers(lng=~data$LONG,lat=~data$LAT,popup=pop)

})

lapply(1:nrow(data), function(i) {
  bt <- paste0('go_btn',i)
  observeEvent(input[[bt]], {
    data<-data1()
    rownames(data)<-seq(1:nrow(data))

    pop<-paste0('',data$name[i],'
',
                '
                Show info')

    leafletProxy('map',data=data,session=session) %>%
      clearMarkers() %>%
      setView(data$LONG[i],data$LAT[i],zoom=15) %>%
      addMarkers(lng=data$LONG[i],lat=data$LAT[i],popup=pop)
  })
})
}

shinyApp(ui, server)

Thank you for any help and sorry if I wrote something wrong, first time using stackoverflow.

Body:
Okay, I am not 100% sure this is the desired behavior, but I think this gives you enough to work with so you can achieve what you want.

I added an id to the div's you created, and then used lapply to create a separate observeEvent for each button. This observeEvent then triggers show or hide from the shinyjs package on the appropriate divs.

I added #added by Florian or modified by Florian above the lines I added or modifed, since the code is quite long. I hope this helps! Let me know if any other questions arise.

# Added by Florian
library(shinyjs)

name<-sample(c('a','b','c'),replace=T,5)
area1<-sample(c(0,1),replace=T,5)
area2<-sample(c(0,1),replace=T,5)
area3<-sample(c(0,1),replace=T,5)
LAT<-runif(5,min=-26, max=-22)
LONG<-runif(5,min=-54, max=-48)
data<-data.frame(name,area1,area2,area3,LAT,LONG)

ui <- shinyUI(fluidPage(
  # Added by Florian
  useShinyjs(),
  selectInput('muni',label='Select city',
              choices=c('Show all',sort(levels(data$name)),selected=NULL)),
  selectInput('area',label='Select area',
              choices=c('Show all','area1','area2','area3',selected=NULL)),
  HTML('<table border="0"><tr><td style="padding: 8px">
       <a id="reset" href="#" style="text-indent: 0px;"
       class="action-button shiny-bound-input">
       Reset</a></td></tr></table>'),
  htmlOutput('box'),
  leafletOutput('map')
  ))

server <- function (input, output, session) {

  data1<-reactive({
    if (input$muni!='Show all') {
      data<-data[which(data$name==input$muni),]
    }
    if (input$area!='Show all') {
      data<-data[data[input$area]!=0,]
    }
    return(data)
  })

  observeEvent(input$reset, {
    updateSelectInput(session,'muni',selected='Show all')
    updateSelectInput(session,'area',selected='Show all')

    # Added by Florian
    for (i in 1:as.integer(nrow(data)))
    {
        shinyjs::show(paste0('mydiv_',i))
    }

  })

  output$box <- renderUI({

    data<-data1()
    num<-as.integer(nrow(data))
    func_areas <- function(areas) sub(",\\s+([^,]+)$", " and \\1",
                                      toString(areas))
    #modified by Florian: added div id
    lapply(1:num, function(i) {
      bt <- paste0('go_btn',i)
      fluidRow(
        HTML(paste0('<div id="mydiv_',i,'"; style="border: 1px solid #00000026;
                    border-radius: 10px; padding: 10px;">
                    <span style="font-size:14px font-weight:bold;">',
                    data$name[i],' - areas: ',
                    func_areas(colnames(data[i,names(data)[2:4]])
                               [which(data[i,names(data)[2:4]]!=0)]),'</span></br>',
                    actionButton(bt,'See map',icon=icon('map-marker',lib='font-awesome')),
                    HTML('</div></br>')
        )))
    })
  })

  # Added by Florian
  lapply(1:as.integer(nrow(data)),function(x)
  {
    observeEvent(input[[paste0('go_btn',x)]], {
      logjs('Click!')
      shinyjs::show(paste0('mydiv_',x))
      for (i in 1:as.integer(nrow(data)))
      {
        if(i!=x)
        {
          shinyjs::hide(paste0('mydiv_',i))
        }
      }

    } )

  })

  output$map<-renderLeaflet({

    data<-data1()
    pop<-paste0('<strong>',data$name,'</strong></br>',
                '<a id="info" href="#" style="text-indent: 0px;"
                class="action-button shiny-bound-input"
                onclick="{Shiny.onInputChange(\'info\', (Math.random() * 1000) + 1);}">
                <i class="fa fa-info-circle"></i>Show info</a>')

    leaflet(data) %>%
      addProviderTiles("Esri.WorldTopoMap") %>%
      setView(-51.5,-24.8,zoom=7) %>%
      addMarkers(lng=~data$LONG,lat=~data$LAT,popup=pop)

  })

  lapply(1:nrow(data), function(i) {
    bt <- paste0('go_btn',i)
    observeEvent(input[[bt]], {
      data<-data1()

      pop<-paste0('<strong>',data$name[i],'</strong></br>',
                  '<a id="info" href="#" style="text-indent: 0px;"
                  class="action-button shiny-bound-input"
                  onclick="{Shiny.onInputChange(\'info\', (Math.random() * 1000) + 1);}">
                  <i class="fa fa-info-circle"></i>Show info</a>')

      leafletProxy('map',data=data,session=session) %>%
        clearMarkers() %>%
        setView(data$LONG[i],data$LAT[i],zoom=15) %>%
        addMarkers(lng=data$LONG[i],lat=data$LAT[i],popup=pop)
    })
  })
}

shinyApp(ui, server)


问:
Wordpress post table
some of my blog posts contain tables. I know I can just insert html directly into the blog and it applies the tags correctly to form a table, however my friend also wants to post such tables and he is scared of the html. Is there a way to insert tables into blogs easily without using html?</p>

答: Use this plugin to add buttons to the rich text editor. It includes tabling functions. http://wordpress.org/extend/plugins/tinymce-advanced/</p>

Title: Wordpress post table


问:
Is there way to use interpolation inside *ngFor
```<code><div *ngFor="let t of {{randomName}}"></div>
</code>```

I want to pass the array name dynamically, i tried above code but i got error.

Thanks for answers but i have to update the question with my scenario

```<code><div formArrayName="{{obj.key}}">
 <div *ngFor="let t of formGrp.controls.{{obj.key}}.controls"></div>
</div>
</code>```

I am creating form array dynamically and it can have any name depending on schema. I   am able to bind that dynamic name to formArrayName as it supports interpolation but i need same behaviour on loop also

Body:
I want to pass the array name dynamically, i tried above code but i got error.

Thanks for answers but i have to update the question with my scenario

I am creating form array dynamically and it can have any name depending on schema. I   am able to bind that dynamic name to formArrayName as it supports interpolation but i need same behaviour on loop also

Body:
<div *ngFor="let t of getTheData()"></div>

getTheData is a method in your component that returns the data

Check the example here https://plnkr.co/edit/Ma66tJhpldYY4GuuM3uU?p=preview in the .component.ts