答:
Your JSON isn't parseable. There were a few errors with it, such as an extra " after "content": and before "status":. Here is the updated JSON:

```<code>{
    "result": "true",
    "id": "31",
    "content": {
        "project": {
            "title": "New",
            "description": "A new file",
            "template": "cve"
        },
        "elements": [{
            "eleTarget": "page-0",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-0",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-0",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-0",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-0",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-0",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-1",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-1",
            "eleType": "EXPERIENCE"
        }, {
            "eleTarget": "page-2",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-2",
            "eleType": "EDUCATION"
        }, {
            "eleTarget": "page-3",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-3",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-4",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-4",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-5",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-5",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-6",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-6",
            "eleType": "CREDENTIALS"
        }],
        "pages": [{
            "titleName": "page-0-title",
            "titleValue": "About",
            "fields": [{
                "fieName": "page-0-ele-0",
                "fieValue": "Mark"
            }, {
                "fieName": "page-0-ele-1",
                "fieValue": "Hilton"
            }, {
                "fieName": "page-0-ele-2",
                "fieValue": "A creative"
            }, {
                "fieName": "page-0-ele-3",
                "fieValue": "developer"
            }, {
                "fieName": "page-0-ele-4",
                "fieValue": "Grown in the forest educated by robots."
            }, {
                "fieName": "page-0-ele-5",
                "fieValue": "Some Icon links"
            }]
        }, {
            "titleName": "page-1-title",
            "titleValue": "Experience",
            "fields": [{
                "fieName": "page-1-ele-6",
                "fieValue": "Experience"
            }, {
                "fieName": "page-1-ele-0-0",
                "fieValue": "Magic developer"
            }, {
                "fieName": "page-1-ele-0-1",
                "fieValue": "Wizards Ltd."
            }, {
                "fieName": "page-1-ele-0-2",
                "fieValue": "Providence"
            }, {
                "fieName": "page-1-ele-0-3",
                "fieValue": "2011"
            }, {
                "fieName": "page-1-ele-0-4",
                "fieValue": "Create essential magic texts and script code."
            }]
        }, {
            "titleName": "page-2-title",
            "titleValue": "Education",
            "fields": [{
                "fieName": "page-2-ele-7",
                "fieValue": "Education"
            }, {
                "fieName": "page-2-ele-0-0",
                "fieValue": "Junior Wizard"
            }, {
                "fieName": "page-2-ele-0-1",
                "fieValue": "Advanced spell management"
            }, {
                "fieName": "page-2-ele-0-2",
                "fieValue": "Howards"
            }, {
                "fieName": "page-2-ele-0-3",
                "fieValue": "2001"
            }, {
                "fieName": "page-2-ele-0-4",
                "fieValue": "Denver"
            }, {
                "fieName": "page-2-ele-0-5",
                "fieValue": "Texas"
            }]
        }, {
            "titleName": "page-3-title",
            "titleValue": "Skills",
            "fields": [{
                "fieName": "page-3-ele-8",
                "fieValue": "Skills"
            }, {
                "fieName": "page-3-ele-9",
                "fieValue": "Mobile-First  Responsive DesignCross Browser Testing & Debugging Agile Development & Scrum"
            }]
        }, {
            "titleName": "page-4-title",
            "titleValue": "Interests",
            "fields": [{
                "fieName": "page-4-ele-10",
                "fieValue": "Interests"
            }, {
                "fieName": "page-4-ele-11",
                "fieValue": "Apart from being a web developer, I enjoy most of my time being outdoors."
            }]
        }, {
            "titleName": "page-5-title",
            "titleValue": "Awards",
            "fields": [{
                "fieName": "page-5-ele-12",
                "fieValue": "Awards"
            }, {
                "fieName": "page-5-ele-13",
                "fieValue": "No awards yet"
            }]
        }, {
            "titleName": "page-6-title",
            "titleValue": "Personal details",
            "fields": [{
                "fieName": "page-6-ele-14",
                "fieValue": "Personal details"
            }, {
                "fieName": "page-6-ele-0-0",
                "fieValue": "Mark"
            }, {
                "fieName": "page-6-ele-0-1",
                "fieValue": "Hilton"
            }, {
                "fieName": "page-6-ele-0-2",
                "fieValue": "Dakota"
            }, {
                "fieName": "page-6-ele-0-3",
                "fieValue": " 214 987 548 415"
            }, {
                "fieName": "page-6-ele-0-4",
                "fieValue": "hilton43@email.com"
            }, {
                "fieName": "page-6-ele-0-5",
                "fieValue": "04-11-78"
            }, {
                "fieName": "page-6-ele-0-6",
                "fieValue": "Denver TX"
            }, {
                "fieName": "page-6-ele-0-7",
                "fieValue": "USA"
            }, {
                "fieName": "page-6-ele-0-8",
                "fieValue": "32,Elm street, Providence NY"
            }, {
                "fieName": "page-6-ele-0-9",
                "fieValue": "picture"
            }]
        }]
    },
    "status": "0",
    "edited": "2017-12-08 23:02:28",
    "views": "0"
}
</code>```

Or in string JS form:

var data = '{"result":"true","id":"31","content":{"project":{"title":"New","description":"Anewfile","template":"cve"},"elements":[{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-1","eleType":"TEXT"},{"eleTarget":"page-1","eleType":"EXPERIENCE"},{"eleTarget":"page-2","eleType":"TEXT"},{"eleTarget":"page-2","eleType":"EDUCATION"},{"eleTarget":"page-3","eleType":"TEXT"},{"eleTarget":"page-3","eleType":"TEXT"},{"eleTarget":"page-4","eleType":"TEXT"},{"eleTarget":"page-4","eleType":"TEXT"},{"eleTarget":"page-5","eleType":"TEXT"},{"eleTarget":"page-5","eleType":"TEXT"},{"eleTarget":"page-6","eleType":"TEXT"},{"eleTarget":"page-6","eleType":"CREDENTIALS"}],"pages":[{"titleName":"page-0-title","titleValue":"About","fields":[{"fieName":"page-0-ele-0","fieValue":"Mark"},{"fieName":"page-0-ele-1","fieValue":"Hilton"},{"fieName":"page-0-ele-2","fieValue":"Acreative"},{"fieName":"page-0-ele-3","fieValue":"developer"},{"fieName":"page-0-ele-4","fieValue":"Grownintheforesteducatedbyrobots."},{"fieName":"page-0-ele-5","fieValue":"SomeIconlinks"}]},{"titleName":"page-1-title","titleValue":"Experience","fields":[{"fieName":"page-1-ele-6","fieValue":"Experience"},{"fieName":"page-1-ele-0-0","fieValue":"Magicdeveloper"},{"fieName":"page-1-ele-0-1","fieValue":"WizardsLtd."},{"fieName":"page-1-ele-0-2","fieValue":"Providence"},{"fieName":"page-1-ele-0-3","fieValue":"2011"},{"fieName":"page-1-ele-0-4","fieValue":"Createessentialmagictextsandscriptcode."}]},{"titleName":"page-2-title","titleValue":"Education","fields":[{"fieName":"page-2-ele-7","fieValue":"Education"},{"fieName":"page-2-ele-0-0","fieValue":"JuniorWizard"},{"fieName":"page-2-ele-0-1","fieValue":"Advancedspellmanagement"},{"fieName":"page-2-ele-0-2","fieValue":"Howards"},{"fieName":"page-2-ele-0-3","fieValue":"2001"},{"fieName":"page-2-ele-0-4","fieValue":"Denver"},{"fieName":"page-2-ele-0-5","fieValue":"Texas"}]},{"titleName":"page-3-title","titleValue":"Skills","fields":[{"fieName":"page-3-ele-8","fieValue":"Skills"},{"fieName":"page-3-ele-9","fieValue":"Mobile-FirstResponsiveDesignCrossBrowserTesting&DebuggingAgileDevelopment&Scrum"}]},{"titleName":"page-4-title","titleValue":"Interests","fields":[{"fieName":"page-4-ele-10","fieValue":"Interests"},{"fieName":"page-4-ele-11","fieValue":"Apartfrombeingawebdeveloper,Ienjoymostofmytimebeingoutdoors."}]},{"titleName":"page-5-title","titleValue":"Awards","fields":[{"fieName":"page-5-ele-12","fieValue":"Awards"},{"fieName":"page-5-ele-13","fieValue":"Noawardsyet"}]},{"titleName":"page-6-title","titleValue":"Personaldetails","fields":[{"fieName":"page-6-ele-14","fieValue":"Personaldetails"},{"fieName":"page-6-ele-0-0","fieValue":"Mark"},{"fieName":"page-6-ele-0-1","fieValue":"Hilton"},{"fieName":"page-6-ele-0-2","fieValue":"Dakota"},{"fieName":"page-6-ele-0-3","fieValue":"214987548415"},{"fieName":"page-6-ele-0-4","fieValue":"hilton43@email.com"},{"fieName":"page-6-ele-0-5","fieValue":"04-11-78"},{"fieName":"page-6-ele-0-6","fieValue":"DenverTX"},{"fieName":"page-6-ele-0-7","fieValue":"USA"},{"fieName":"page-6-ele-0-8","fieValue":"32,Elmstreet,ProvidenceNY"},{"fieName":"page-6-ele-0-9","fieValue":"picture"}]}]},"status":"0","edited":"2017-12-0823:02:28","views":"0"}';
data = JSON.parse(data);
console.log(data);
console.log(data.result);```

Title: Rare JSON issue: Well parsed but I cant get values. Why?

Body:
Your JSON isn't parseable. There were a few errors with it, such as an extra " after "content": and before "status":. Here is the updated JSON:

{
    "result": "true",
    "id": "31",
    "content": {
        "project": {
            "title": "New",
            "description": "A new file",
            "template": "cve"
        },
        "elements": [{
            "eleTarget": "page-0",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-0",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-0",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-0",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-0",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-0",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-1",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-1",
            "eleType": "EXPERIENCE"
        }, {
            "eleTarget": "page-2",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-2",
            "eleType": "EDUCATION"
        }, {
            "eleTarget": "page-3",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-3",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-4",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-4",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-5",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-5",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-6",
            "eleType": "TEXT"
        }, {
            "eleTarget": "page-6",
            "eleType": "CREDENTIALS"
        }],
        "pages": [{
            "titleName": "page-0-title",
            "titleValue": "About",
            "fields": [{
                "fieName": "page-0-ele-0",
                "fieValue": "Mark"
            }, {
                "fieName": "page-0-ele-1",
                "fieValue": "Hilton"
            }, {
                "fieName": "page-0-ele-2",
                "fieValue": "A creative"
            }, {
                "fieName": "page-0-ele-3",
                "fieValue": "developer"
            }, {
                "fieName": "page-0-ele-4",
                "fieValue": "Grown in the forest educated by robots."
            }, {
                "fieName": "page-0-ele-5",
                "fieValue": "Some Icon links"
            }]
        }, {
            "titleName": "page-1-title",
            "titleValue": "Experience",
            "fields": [{
                "fieName": "page-1-ele-6",
                "fieValue": "Experience"
            }, {
                "fieName": "page-1-ele-0-0",
                "fieValue": "Magic developer"
            }, {
                "fieName": "page-1-ele-0-1",
                "fieValue": "Wizards Ltd."
            }, {
                "fieName": "page-1-ele-0-2",
                "fieValue": "Providence"
            }, {
                "fieName": "page-1-ele-0-3",
                "fieValue": "2011"
            }, {
                "fieName": "page-1-ele-0-4",
                "fieValue": "Create essential magic texts and script code."
            }]
        }, {
            "titleName": "page-2-title",
            "titleValue": "Education",
            "fields": [{
                "fieName": "page-2-ele-7",
                "fieValue": "Education"
            }, {
                "fieName": "page-2-ele-0-0",
                "fieValue": "Junior Wizard"
            }, {
                "fieName": "page-2-ele-0-1",
                "fieValue": "Advanced spell management"
            }, {
                "fieName": "page-2-ele-0-2",
                "fieValue": "Howards"
            }, {
                "fieName": "page-2-ele-0-3",
                "fieValue": "2001"
            }, {
                "fieName": "page-2-ele-0-4",
                "fieValue": "Denver"
            }, {
                "fieName": "page-2-ele-0-5",
                "fieValue": "Texas"
            }]
        }, {
            "titleName": "page-3-title",
            "titleValue": "Skills",
            "fields": [{
                "fieName": "page-3-ele-8",
                "fieValue": "Skills"
            }, {
                "fieName": "page-3-ele-9",
                "fieValue": "Mobile-First  Responsive DesignCross Browser Testing & Debugging Agile Development & Scrum"
            }]
        }, {
            "titleName": "page-4-title",
            "titleValue": "Interests",
            "fields": [{
                "fieName": "page-4-ele-10",
                "fieValue": "Interests"
            }, {
                "fieName": "page-4-ele-11",
                "fieValue": "Apart from being a web developer, I enjoy most of my time being outdoors."
            }]
        }, {
            "titleName": "page-5-title",
            "titleValue": "Awards",
            "fields": [{
                "fieName": "page-5-ele-12",
                "fieValue": "Awards"
            }, {
                "fieName": "page-5-ele-13",
                "fieValue": "No awards yet"
            }]
        }, {
            "titleName": "page-6-title",
            "titleValue": "Personal details",
            "fields": [{
                "fieName": "page-6-ele-14",
                "fieValue": "Personal details"
            }, {
                "fieName": "page-6-ele-0-0",
                "fieValue": "Mark"
            }, {
                "fieName": "page-6-ele-0-1",
                "fieValue": "Hilton"
            }, {
                "fieName": "page-6-ele-0-2",
                "fieValue": "Dakota"
            }, {
                "fieName": "page-6-ele-0-3",
                "fieValue": " 214 987 548 415"
            }, {
                "fieName": "page-6-ele-0-4",
                "fieValue": "hilton43@email.com"
            }, {
                "fieName": "page-6-ele-0-5",
                "fieValue": "04-11-78"
            }, {
                "fieName": "page-6-ele-0-6",
                "fieValue": "Denver TX"
            }, {
                "fieName": "page-6-ele-0-7",
                "fieValue": "USA"
            }, {
                "fieName": "page-6-ele-0-8",
                "fieValue": "32,Elm street, Providence NY"
            }, {
                "fieName": "page-6-ele-0-9",
                "fieValue": "picture"
            }]
        }]
    },
    "status": "0",
    "edited": "2017-12-08 23:02:28",
    "views": "0"
}

Or in string JS form:

var data = '{"result":"true","id":"31","content":{"project":{"title":"New","description":"Anewfile","template":"cve"},"elements":[{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-1","eleType":"TEXT"},{"eleTarget":"page-1","eleType":"EXPERIENCE"},{"eleTarget":"page-2","eleType":"TEXT"},{"eleTarget":"page-2","eleType":"EDUCATION"},{"eleTarget":"page-3","eleType":"TEXT"},{"eleTarget":"page-3","eleType":"TEXT"},{"eleTarget":"page-4","eleType":"TEXT"},{"eleTarget":"page-4","eleType":"TEXT"},{"eleTarget":"page-5","eleType":"TEXT"},{"eleTarget":"page-5","eleType":"TEXT"},{"eleTarget":"page-6","eleType":"TEXT"},{"eleTarget":"page-6","eleType":"CREDENTIALS"}],"pages":[{"titleName":"page-0-title","titleValue":"About","fields":[{"fieName":"page-0-ele-0","fieValue":"Mark"},{"fieName":"page-0-ele-1","fieValue":"Hilton"},{"fieName":"page-0-ele-2","fieValue":"Acreative"},{"fieName":"page-0-ele-3","fieValue":"developer"},{"fieName":"page-0-ele-4","fieValue":"Grownintheforesteducatedbyrobots."},{"fieName":"page-0-ele-5","fieValue":"SomeIconlinks"}]},{"titleName":"page-1-title","titleValue":"Experience","fields":[{"fieName":"page-1-ele-6","fieValue":"Experience"},{"fieName":"page-1-ele-0-0","fieValue":"Magicdeveloper"},{"fieName":"page-1-ele-0-1","fieValue":"WizardsLtd."},{"fieName":"page-1-ele-0-2","fieValue":"Providence"},{"fieName":"page-1-ele-0-3","fieValue":"2011"},{"fieName":"page-1-ele-0-4","fieValue":"Createessentialmagictextsandscriptcode."}]},{"titleName":"page-2-title","titleValue":"Education","fields":[{"fieName":"page-2-ele-7","fieValue":"Education"},{"fieName":"page-2-ele-0-0","fieValue":"JuniorWizard"},{"fieName":"page-2-ele-0-1","fieValue":"Advancedspellmanagement"},{"fieName":"page-2-ele-0-2","fieValue":"Howards"},{"fieName":"page-2-ele-0-3","fieValue":"2001"},{"fieName":"page-2-ele-0-4","fieValue":"Denver"},{"fieName":"page-2-ele-0-5","fieValue":"Texas"}]},{"titleName":"page-3-title","titleValue":"Skills","fields":[{"fieName":"page-3-ele-8","fieValue":"Skills"},{"fieName":"page-3-ele-9","fieValue":"Mobile-FirstResponsiveDesignCrossBrowserTesting&DebuggingAgileDevelopment&Scrum"}]},{"titleName":"page-4-title","titleValue":"Interests","fields":[{"fieName":"page-4-ele-10","fieValue":"Interests"},{"fieName":"page-4-ele-11","fieValue":"Apartfrombeingawebdeveloper,Ienjoymostofmytimebeingoutdoors."}]},{"titleName":"page-5-title","titleValue":"Awards","fields":[{"fieName":"page-5-ele-12","fieValue":"Awards"},{"fieName":"page-5-ele-13","fieValue":"Noawardsyet"}]},{"titleName":"page-6-title","titleValue":"Personaldetails","fields":[{"fieName":"page-6-ele-14","fieValue":"Personaldetails"},{"fieName":"page-6-ele-0-0","fieValue":"Mark"},{"fieName":"page-6-ele-0-1","fieValue":"Hilton"},{"fieName":"page-6-ele-0-2","fieValue":"Dakota"},{"fieName":"page-6-ele-0-3","fieValue":"214987548415"},{"fieName":"page-6-ele-0-4","fieValue":"hilton43@email.com"},{"fieName":"page-6-ele-0-5","fieValue":"04-11-78"},{"fieName":"page-6-ele-0-6","fieValue":"DenverTX"},{"fieName":"page-6-ele-0-7","fieValue":"USA"},{"fieName":"page-6-ele-0-8","fieValue":"32,Elmstreet,ProvidenceNY"},{"fieName":"page-6-ele-0-9","fieValue":"picture"}]}]},"status":"0","edited":"2017-12-0823:02:28","views":"0"}';
data = JSON.parse(data);
console.log(data);
console.log(data.result);


来源: stackexchange

问:
openvms 7.1 install create program.exe utility hangs
When attempting to install a program as a known image, instally hangs, there is no response, control Y fails and the only way out is to stop the process.

```<code>install create logical_path:program.exe/header
</code>```

Program and subroutines are compiled nodebug and it is linked notraceback.
Logical path is in lnm$system. Directory is owned by system, and has protection rwe,rwe,re,re. program.exe has protection rwed,rwed,re,re. I think the problem lies with program.exe, but what ? There must be a simple explanation. BTW, am logged in as system, with cmknl set.
Many thanks in advance.

答:
I can't comment, so asking as an "answer" (site rule - admins delete this if you want) - installing an image requires free global sections. Not sure why it would ever "hang" trying to do that, but that's the only thing I can think of that would prevent the INSTALL from not working.

Suggest checking free global sections and free global pages.

ContentLicense: CC BY-SA 3.0

Body:
When attempting to install a program as a known image, instally hangs, there is no response, control Y fails and the only way out is to stop the process.

install create logical_path:program.exe/header

Program and subroutines are compiled nodebug and it is linked notraceback.
Logical path is in lnm$system. Directory is owned by system, and has protection rwe,rwe,re,re. program.exe has protection rwed,rwed,re,re. I think the problem lies with program.exe, but what ? There must be a simple explanation. BTW, am logged in as system, with cmknl set.
Many thanks in advance.


问:
std::array with unknown length as a type for template function specification
I want to pass std::array class with a known type, but unknown size to the template function specialization:

```<code>class foo {
public:
void bar<class T>(T arg1, int arg2, int arg3) {
    //For any other T
}
void bar<std::array<rs::float3, size>>(T arg1, arg2) {
    //Specific function for type std::array of rs::float3's and unknown length (size is not a type, just variable).
}
</code>```

答:
Try this:

```<code>class foo
{
public:
    template <class T>
    void bar(T arg1, int arg2, int arg3) {
        //For any other T
    }

    template <size_t size>
    void bar(std::array<rs::float3, size> arg1, int arg2) {
        //Specific function for type std::array of rs::float3's of caller-specified length
    }
};
</code>```

Live demo

Body:
I want to pass std::array class with a known type, but unknown size to the template function specialization:

class foo {
public:
void bar<class T>(T arg1, int arg2, int arg3) {
    //For any other T
}
void bar<std::array<rs::float3, size>>(T arg1, arg2) {
    //Specific function for type std::array of rs::float3's and unknown length (size is not a type, just variable).
}

Body:
Try this:

class foo
{
public:
    template <class T>
    void bar(T arg1, int arg2, int arg3) {
        //For any other T
    }

    template <size_t size>
    void bar(std::array<rs::float3, size> arg1, int arg2) {
        //Specific function for type std::array of rs::float3's of caller-specified length
    }
};

Live demo


问:
Unix, find, ls, grep and sort
With this Unix command, I try to search text in a directory

```<code>find . -type f -iname *index*jsp -print | xargs ls -t | xargs grep body
</code>```

./apache-tomcat-6.0.18/a/index.jsp:

./apache-tomcat-6.0.18/b/index.jsp:

But this result is not perfect, I want to get the file creation date and line number of matched string, like

./apache-tomcat-6.0.18/a/index.jsp: 2011-1-2 Line 3

./apache-tomcat-6.0.18/b/index.jsp: 2011-1-1 Line 4

How can I achieve this?

答:
```<code>find . -name index* | xargs ls -t | xargs grep -Z body \
    | tr -s " " \
    | cut -d $'\0' -f 1 | uniq \
    | xargs -n 1 -I {} -exec sh -c \ "
        echo -n {} \" \"; \
        ls -lt {} | tr -s \" \" | cut -d \" \" -f 6; \
        grep -n body {} | cut -d ":" -f 1
    "
</code>```

That's about as close as I can get on it.

Title: Unix, find, ls, grep and sort

Body:
With this Unix command, I try to search text in a directory

find . -type f -iname *index*jsp -print | xargs ls -t | xargs grep body

./apache-tomcat-6.0.18/a/index.jsp:

./apache-tomcat-6.0.18/b/index.jsp:

But this result is not perfect, I want to get the file creation date and line number of matched string, like

./apache-tomcat-6.0.18/a/index.jsp: 2011-1-2 Line 3

./apache-tomcat-6.0.18/b/index.jsp: 2011-1-1 Line 4

How can I achieve this?

Body:
find . -name index* | xargs ls -t | xargs grep -Z body \
    | tr -s " " \
    | cut -d $'\0' -f 1 | uniq \
    | xargs -n 1 -I {} -exec sh -c \ "
        echo -n {} \" \"; \
        ls -lt {} | tr -s \" \" | cut -d \" \" -f 6; \
        grep -n body {} | cut -d ":" -f 1
    "

That's about as close as I can get on it.

ContentLicense: CC BY-SA 2.5


问:
HDFS BLOCK SIZE
What is default block size 128MB or 64MB for hdfs?In hadoop definite guide it is mentioned as "HDFS, too, has the concept of a block, but it is a much larger unit—128 MB by default".Anyone can tell which is the default size?</p>

答:
The best place to refer the default values of hadoop configuration is the apache hadoop website. The default configurations and values are present in the default xml files in apache hadoop website.

The answer to your question is present in the hdfs-default.xml. The latest stable version of hadoop as of now is 2.9.0 and the value of block size (dfs.blocksize) is 128 MB (134217728 bytes).

In hadoop 1.x the default value of block size was 64 MB. Now in the world with high speed network and low cost storage, they made the default value as 128 MB.

Note: The hdfs-default.xml, core-default.xml, yarn-default.xml files present in the apache website can be used as the reference to find the default values of properties in apache hadoop.

Title: HDFS BLOCK SIZE


问:
Query to select and alternate records from 2 different tables
I'm trying to optimize some queries in a duplicate finder application in PHP CodeIgniter. And in order to keep the MVC pattern and stay away from DB calls directly in the views or controllers, I'm looking for a query that will alternate results from 2 different tables:

Table duplicate_leads

```<code>╔════╦══════════════╦═══════════╦════════════════════╦═══════════╗
║ id ║ original_id  ║    name   ║       email        ║   phone   ║
╠════╬══════════════╬═══════════╬════════════════════╬═══════════╣
║  1 ║      345     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║  2 ║      495     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
╚════╩══════════════╩═══════════╩════════════════════╩═══════════╝
</code>```

Table leads

```<code>╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
╚═════╩═══════════╩════════════════════╩═══════════╝
</code>```

The duplicate_leads.original_id is the value that relates the lead to the original lead's leads.id.

Attempt #1

SELECT
    a.id,
    a.name,
    a.email,
    a.phone
FROM
    leads a
        JOIN duplicate_leads b
            ON a.id = b.original_id
```

<p>Which produces:</p>

```╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
║ ... ║    ...    ║         ...        ║    ...    ║
╚═════╩═══════════╩════════════════════╩═══════════╝
```

<p>Seems to be retrieving records from one of the two tables. I don't have advanced experience in SQL so I don't know how exactly use the joins or unions for this particular case because I think that either way, what the query will return is a kind-of concatenation of result like this:</p>

```╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
║     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
╚═════╩═══════════╩════════════════════╩═══════════╝
```

<p><strong>What I'm actually expecting:</strong>
The rows shown first (because they could be multiple) should be records from the <code>leads</code> table. These records should be the ones that match the <code>original_id</code> of the <code>duplicate_leads</code> which should be the next row after the ones matched, like so:</p>

```╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from duplicate_leads
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from leads
║     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from duplicate_leads
║ ... ║    ...    ║         ...        ║    ...    ║
╚═════╩═══════════╩════════════════════╩═══════════╝
```

<p>Multiple matches example:</p>

```╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║ 677 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from duplicate_leads
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from leads
║     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from duplicate_leads
║ ... ║    ...    ║         ...        ║    ...    ║
╚═════╩═══════════╩════════════════════╩═══════════╝
```

How can I achieve that result?

Update

SQL Fiddle: http://sqlfiddle.com/#!9/6d87a9/1

答:
You want to write this I believe:

```<code>SELECT
a.id,
a.name
a.email
FROM leads a
UNION ALL
SELECT
a.id,
a.name
a.email
FROM leads a
INNER JOIN duplicate_leads b
ON a.id = b.original_id
ORDER BY a.id
</code>```

The first query (before the union) will give you one row for every record in your leads table

The second query will give you one row for every lead in your duplicates table (given that it has a match in the lead table - which it should if everything is set-up correctly), but will display the info for the record in the leads table for which the match is found.

The ORDER BY then helps you visualize this so all rows are grouped according to the original lead id

The important thing to remember is that joining two tables creates one table with all the columns from both tables (you then trim down which columns are displayed using SELECT). With a standard join, all of the fields from the original table are maintained, and if a match is found in the second table, these fields will be populated as well. Otherwise, they'll be null.

This is why your original query was only giving you one row per lead. If you SELECT *, you'll get a better idea what's going on behind the scenes

Body:
I'm trying to optimize some queries in a duplicate finder application in PHP CodeIgniter. And in order to keep the MVC pattern and stay away from DB calls directly in the views or controllers, I'm looking for a query that will alternate results from 2 different tables:

Table duplicate_leads

╔════╦══════════════╦═══════════╦════════════════════╦═══════════╗
║ id ║ original_id  ║    name   ║       email        ║   phone   ║
╠════╬══════════════╬═══════════╬════════════════════╬═══════════╣
║  1 ║      345     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║  2 ║      495     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
╚════╩══════════════╩═══════════╩════════════════════╩═══════════╝

Table leads

╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
╚═════╩═══════════╩════════════════════╩═══════════╝

The duplicate_leads.original_id is the value that relates the lead to the original lead's leads.id.

Attempt #1

SELECT
    a.id,
    a.name,
    a.email,
    a.phone
FROM
    leads a
        JOIN duplicate_leads b
            ON a.id = b.original_id

Which produces:

╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
║ ... ║    ...    ║         ...        ║    ...    ║
╚═════╩═══════════╩════════════════════╩═══════════╝

Seems to be retrieving records from one of the two tables. I don't have advanced experience in SQL so I don't know how exactly use the joins or unions for this particular case because I think that either way, what the query will return is a kind-of concatenation of result like this:

╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
║     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
╚═════╩═══════════╩════════════════════╩═══════════╝

What I'm actually expecting:
The rows shown first (because they could be multiple) should be records from the leads table. These records should be the ones that match the original_id of the duplicate_leads which should be the next row after the ones matched, like so:

╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from duplicate_leads
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from leads
║     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from duplicate_leads
║ ... ║    ...    ║         ...        ║    ...    ║
╚═════╩═══════════╩════════════════════╩═══════════╝

Multiple matches example:

╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║ 677 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from duplicate_leads
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from leads
║     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from duplicate_leads
║ ... ║    ...    ║         ...        ║    ...    ║
╚═════╩═══════════╩════════════════════╩═══════════╝

How can I achieve that result?

Update

SQL Fiddle: http://sqlfiddle.com/#!9/6d87a9/1

Body:
You want to write this I believe:

SELECT
a.id,
a.name
a.email
FROM leads a
UNION ALL
SELECT
a.id,
a.name
a.email
FROM leads a
INNER JOIN duplicate_leads b
ON a.id = b.original_id
ORDER BY a.id

The first query (before the union) will give you one row for every record in your leads table

The second query will give you one row for every lead in your duplicates table (given that it has a match in the lead table - which it should if everything is set-up correctly), but will display the info for the record in the leads table for which the match is found.

The ORDER BY then helps you visualize this so all rows are grouped according to the original lead id

The important thing to remember is that joining two tables creates one table with all the columns from both tables (you then trim down which columns are displayed using SELECT). With a standard join, all of the fields from the original table are maintained, and if a match is found in the second table, these fields will be populated as well. Otherwise, they'll be null.

This is why your original query was only giving you one row per lead. If you SELECT *, you'll get a better idea what's going on behind the scenes


问:
Find the position of a specific number that appear first in the list [python]
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

```<code>     s = [1,2,3,4,5,3,9,8]  => s[2] appears first
</code>```

答:
A little bit ambiguous question.

If you just want to find index of first occurrence of specific element, you should use list.index() method:

```<code>index = s.index(3)
</code>```

But if you

want to find a number that appears
  more than once in the list

in general (without element value given), seems you can

either do simple O(N^2) search in array (check all elements of the list for each element, till duplication is found)

or do sort, find duplicated element in sorted list and then find index of duplicated element in the original array with list.index() method - this will take O(N*log(N)) because of sort.

Body:
So I want to find a number that appears more than once in the list. I want the position of the first one.

Example: Say I want 3

     s = [1,2,3,4,5,3,9,8]  => s[2] appears first

Body:
A little bit ambiguous question.

If you just want to find index of first occurrence of specific element, you should use list.index() method:

index = s.index(3)

But if you

want to find a number that appears
  more than once in the list

in general (without element value given), seems you can

either do simple O(N^2) search in array (check all elements of the list for each element, till duplication is found)

or do sort, find duplicated element in sorted list and then find index of duplicated element in the original array with list.index() method - this will take O(N*log(N)) because of sort.


问:
Remove branding and title link from embeded youtube video
Can anyone please suggest a way to remove link back to youtube and branding (watermark or logo) from embedded youtube video.

The below tag remove branding:

```<code><iframe allowfullscreen="" frameborder="0" height="315" src="http://www.youtube.com/embed/8pjJ-Czqpps?modestbranding=1&rel=0" width="420"></iframe>
</code>```

The below tag remove title link:

```<code><iframe allowfullscreen="" frameborder="0" height="315" src="http://www.youtube.com/embed  /8pjJ-Czqpps?showinfo=0" width="420"></iframe>
</code>```

But cant able to make all together happening.

Please help.

答:
Demo: http://bdtune24.com/gtv-live/

You can use this Plugin if your site build in wordpress.[https://wordpress.org/plugins/videojs-html5-video-player-for-wordpress/]

After install That....you can embed any youtube or vimeo video....

Like this: [videojs youtube="https://www.youtube.com/watch?v=0iiCkqA533E"]

Body:
Can anyone please suggest a way to remove link back to youtube and branding (watermark or logo) from embedded youtube video.

The below tag remove branding:

The below tag remove title link:

But cant able to make all together happening.

Please help.


问:
Django Rest Framework: Duplicate key value violates unique constraint
I have a problem with Django Rest Framework. This app I'm building is Avatar. User can update his/her own avatar, then avatar auto save with my path I defined (/users_id/photoset_id/filename.png). So I make function to save like this code:

```<code>def avatar_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s.%s' % (instance.id, ext)
    return "users/%s/avatar/%s_%s" %(instance.user.id, instance.photoset.id, filename)

class Avatar(models.Model):
    user = models.ForeignKey(User, related_name='avatar_set', null=True)
    photoset = models.ForeignKey(PhotoSet, null=True, blank=True)
    primary = models.BooleanField(default=True)
    caption = models.TextField(blank=True, null=True)
    image = models.ImageField(max_length=1024, upload_to=avatar_file_path)
    is_public = models.BooleanField(_('is public'), default=True, help_text=_('Public photographs will be displayed in the default views.'))
    date_uploaded = models.DateTimeField(default=datetime.datetime.now)

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        # Make one primary Avatar
        if self.primary:
            avatars = Avatar.objects.filter(user=self.user, primary=True).exclude(id=self.id)
            avatars.update(primary=False)
        # Set default photoset
        if self.photoset is None:
            if not PhotoSet.objects.filter(user=self.user, photoset_type=3).exists():
                PhotoSet.objects.create(user=self.user, photoset_type=3, title='Profile Pictures')
                self.photoset = PhotoSet.objects.get(user=self.user, photoset_type=3)
            if PhotoSet.objects.filter(user=self.user, photoset_type=3).exists():
                self.photoset = PhotoSet.objects.get(user=self.user, photoset_type=3)
        # Model Save override
        if self.id is None:
            saved_image = self.image
            self.image = None
            super(Avatar, self).save(*args, **kwargs)
            self.image = saved_image
        super(Avatar, self).save(force_insert, force_update, *args, **kwargs)
</code>```

When I create serializers POST with Django Rest Framework:

```<code>class AvatarCreateUpdateSerializer(ModelSerializer):
    class Meta:
        model = Avatar
        fields = [
            'user',
            'image',
            'caption',
            'is_public',
        ]
</code>```

It goes problem:

Error Log Tracking in line:  super(Avatar, self).save(force_insert, force_update, *args, **kwargs)

Why I face with this problem and how can I fix this? Thank you in advance!

答:
The problem is that the save function gets passed "forced_insert=True" by the rest framework. As you are saving twice with the same data, it is trying to force an insert of the same primary key twice.

A solution is that after the first save is to reset that forced_insert by
adding

```<code>kwargs['force_insert'] = False
</code>```

before the second save. That will allow Django to use the update method, hence not try and create the same primary key twice.

Body:
I have a problem with Django Rest Framework. This app I'm building is Avatar. User can update his/her own avatar, then avatar auto save with my path I defined (/users_id/photoset_id/filename.png). So I make function to save like this code:

def avatar_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = '%s.%s' % (instance.id, ext)
    return "users/%s/avatar/%s_%s" %(instance.user.id, instance.photoset.id, filename)

class Avatar(models.Model):
    user = models.ForeignKey(User, related_name='avatar_set', null=True)
    photoset = models.ForeignKey(PhotoSet, null=True, blank=True)
    primary = models.BooleanField(default=True)
    caption = models.TextField(blank=True, null=True)
    image = models.ImageField(max_length=1024, upload_to=avatar_file_path)
    is_public = models.BooleanField(_('is public'), default=True, help_text=_('Public photographs will be displayed in the default views.'))
    date_uploaded = models.DateTimeField(default=datetime.datetime.now)

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
        # Make one primary Avatar
        if self.primary:
            avatars = Avatar.objects.filter(user=self.user, primary=True).exclude(id=self.id)
            avatars.update(primary=False)
        # Set default photoset
        if self.photoset is None:
            if not PhotoSet.objects.filter(user=self.user, photoset_type=3).exists():
                PhotoSet.objects.create(user=self.user, photoset_type=3, title='Profile Pictures')
                self.photoset = PhotoSet.objects.get(user=self.user, photoset_type=3)
            if PhotoSet.objects.filter(user=self.user, photoset_type=3).exists():
                self.photoset = PhotoSet.objects.get(user=self.user, photoset_type=3)
        # Model Save override
        if self.id is None:
            saved_image = self.image
            self.image = None
            super(Avatar, self).save(*args, **kwargs)
            self.image = saved_image
        super(Avatar, self).save(force_insert, force_update, *args, **kwargs)

When I create serializers POST with Django Rest Framework:

class AvatarCreateUpdateSerializer(ModelSerializer):
    class Meta:
        model = Avatar
        fields = [
            'user',
            'image',
            'caption',
            'is_public',
        ]

It goes problem:

Error Log Tracking in line:  super(Avatar, self).save(force_insert, force_update, *args, **kwargs)

Why I face with this problem and how can I fix this? Thank you in advance!

Body:
The problem is that the save function gets passed "forced_insert=True" by the rest framework. As you are saving twice with the same data, it is trying to force an insert of the same primary key twice.

A solution is that after the first save is to reset that forced_insert by
adding

kwargs['force_insert'] = False

before the second save. That will allow Django to use the update method, hence not try and create the same primary key twice.


问:
Generate a random u8 from 0 to 255 inclusively
I am trying to make a program that generates random numbers from 0 to 255 inclusively. It seems so simple! I did this:

```<code>extern crate rand;
use rand::Rng;

fn main() {
    println!("Guess the number!");
    let random_number: u8 = rand::thread_rng().gen_range(0, 255);

    println!("Your random number is {}", random_number);
}
</code>```

This works fine, but the problem with this approach is that the number 255 will not be included:

The gen_range method takes two numbers as arguments and generates a random number between them. It’s inclusive on the lower bound but exclusive on the upper bound.

When I try to do this :

```<code>let random_number: u8 = rand::thread_rng().gen_range(0, 256);
</code>```

Rust will generate a warning because u8 only accepts values from 0 to 255.

warning: literal out of range for u8
 --> src/main.rs:6:61
  |
6 |     let random_number: u8 = rand::thread_rng().gen_range(0, 256);
  |                                                             ^^^
  |
  = note: #[warn(overflowing_literals)] on by default
```

How do I work around this without having to change the type of the random_number variable?

答:
Use the gen method instead. This method will generate a random value from the whole set of possible values for the specified type.

```<code>extern crate rand;

use rand::Rng;

fn main() {
    println!("Guess the number!");
    let random_number: u8 = rand::thread_rng().gen();

    println!("Your random number is {}", random_number);
}
</code>```

Body:
I am trying to make a program that generates random numbers from 0 to 255 inclusively. It seems so simple! I did this:

extern crate rand;
use rand::Rng;

fn main() {
    println!("Guess the number!");
    let random_number: u8 = rand::thread_rng().gen_range(0, 255);

    println!("Your random number is {}", random_number);
}

This works fine, but the problem with this approach is that the number 255 will not be included:

The gen_range method takes two numbers as arguments and generates a random number between them. It’s inclusive on the lower bound but exclusive on the upper bound.

When I try to do this :

let random_number: u8 = rand::thread_rng().gen_range(0, 256);

Rust will generate a warning because u8 only accepts values from 0 to 255.

warning: literal out of range for u8
 --> src/main.rs:6:61
  |
6 |     let random_number: u8 = rand::thread_rng().gen_range(0, 256);
  |                                                             ^^^
  |
  = note: #[warn(overflowing_literals)] on by default

How do I work around this without having to change the type of the random_number variable?

Body:
Use the gen method instead. This method will generate a random value from the whole set of possible values for the specified type.

extern crate rand;

use rand::Rng;

fn main() {
    println!("Guess the number!");
    let random_number: u8 = rand::thread_rng().gen();

    println!("Your random number is {}", random_number);
}


问:
Rare JSON issue: Well parsed but I cant get values. Why?
Here is a JSON string, tested in some lints at https://jsonlint.com/
and they all say it's ok, I guess you will feel this as a redundant question and I understand. But I got stuck and I'm becoming crazy with this issue, unable to fix it by my own.

So I parse the JSON string this way (data var contents on the bottom):

```<code>data = JSON.parse(data);
</code>```

And I have tried to get the data as usual:

```<code>console.log(data.result); or console.log(data['result']);
</code>```

But it always is undefined. Can somebody help me?

Here the contents of var data:

```<code>var data = '{"result":"true","id":"31","content":"{"project":{"title":"New","description":"A new file","template":"cve"},"elements":[{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-1","eleType":"TEXT"},{"eleTarget":"page-1","eleType":"EXPERIENCE"},{"eleTarget":"page-2","eleType":"TEXT"},{"eleTarget":"page-2","eleType":"EDUCATION"},{"eleTarget":"page-3","eleType":"TEXT"},{"eleTarget":"page-3","eleType":"TEXT"},{"eleTarget":"page-4","eleType":"TEXT"},{"eleTarget":"page-4","eleType":"TEXT"},{"eleTarget":"page-5","eleType":"TEXT"},{"eleTarget":"page-5","eleType":"TEXT"},{"eleTarget":"page-6","eleType":"TEXT"},{"eleTarget":"page-6","eleType":"CREDENTIALS"}],"pages":[{"titleName":"page-0-title","titleValue":"About","fields":[{"fieName":"page-0-ele-0","fieValue":"Mark"},{"fieName":"page-0-ele-1","fieValue":"Hilton"},{"fieName":"page-0-ele-2","fieValue":"A creative"},{"fieName":"page-0-ele-3","fieValue":"developer"},{"fieName":"page-0-ele-4","fieValue":"Grown in the forest educated by robots."},{"fieName":"page-0-ele-5","fieValue":"Some Icon links"}]},{"titleName":"page-1-title","titleValue":"Experience","fields":[{"fieName":"page-1-ele-6","fieValue":"Experience"},{"fieName":"page-1-ele-0-0","fieValue":"Magic developer"},{"fieName":"page-1-ele-0-1","fieValue":"Wizards Ltd."},{"fieName":"page-1-ele-0-2","fieValue":"Providence"},{"fieName":"page-1-ele-0-3","fieValue":"2011"},{"fieName":"page-1-ele-0-4","fieValue":"Create essential magic texts and script code."}]},{"titleName":"page-2-title","titleValue":"Education","fields":[{"fieName":"page-2-ele-7","fieValue":"Education"},{"fieName":"page-2-ele-0-0","fieValue":"Junior Wizard"},{"fieName":"page-2-ele-0-1","fieValue":"Advanced spell management"},{"fieName":"page-2-ele-0-2","fieValue":"Howards"},{"fieName":"page-2-ele-0-3","fieValue":"2001"},{"fieName":"page-2-ele-0-4","fieValue":"Denver"},{"fieName":"page-2-ele-0-5","fieValue":"Texas"}]},{"titleName":"page-3-title","titleValue":"Skills","fields":[{"fieName":"page-3-ele-8","fieValue":"Skills"},{"fieName":"page-3-ele-9","fieValue":"Mobile-First  Responsive DesignCross Browser Testing & Debugging Agile Development & Scrum"}]},{"titleName":"page-4-title","titleValue":"Interests","fields":[{"fieName":"page-4-ele-10","fieValue":"Interests"},{"fieName":"page-4-ele-11","fieValue":"Apart from being a web developer, I enjoy most of my time being outdoors."}]},{"titleName":"page-5-title","titleValue":"Awards","fields":[{"fieName":"page-5-ele-12","fieValue":"Awards"},{"fieName":"page-5-ele-13","fieValue":"No awards yet"}]},{"titleName":"page-6-title","titleValue":"Personal details","fields":[{"fieName":"page-6-ele-14","fieValue":"Personal details"},{"fieName":"page-6-ele-0-0","fieValue":"Mark"},{"fieName":"page-6-ele-0-1","fieValue":"Hilton"},{"fieName":"page-6-ele-0-2","fieValue":"Dakota"},{"fieName":"page-6-ele-0-3","fieValue":" 214 987 548 415"},{"fieName":"page-6-ele-0-4","fieValue":"hilton43@email.com"},{"fieName":"page-6-ele-0-5","fieValue":"04-11-78"},{"fieName":"page-6-ele-0-6","fieValue":"Denver TX"},{"fieName":"page-6-ele-0-7","fieValue":"USA"},{"fieName":"page-6-ele-0-8","fieValue":"32,Elm street, Providence NY"},{"fieName":"page-6-ele-0-9","fieValue":"picture"}]}]}","status":"0","edited":"2017-12-08 23:02:28","views":"0"}';
</code>```

答:
Nested JSON objects don't take quotes. Remove the quotes around your content object.

```<code>var data = '{"result":"true","id":"31","content":"{"nested":"object"}","status":"0"}';
JSON.parse(data); // SyntaxError
</code>```

```<code>var data = '{"result":"true","id":"31","content":{"nested":"object"},"status":"0"}';
JSON.parse(data); // success
</code>```

Body:
Here is a JSON string, tested in some lints at https://jsonlint.com/
and they all say it's ok, I guess you will feel this as a redundant question and I understand. But I got stuck and I'm becoming crazy with this issue, unable to fix it by my own.

So I parse the JSON string this way (data var contents on the bottom):

data = JSON.parse(data);

And I have tried to get the data as usual:

console.log(data.result); or console.log(data['result']);

But it always is undefined. Can somebody help me?

Here the contents of var data:

var data = '{"result":"true","id":"31","content":"{"project":{"title":"New","description":"A new file","template":"cve"},"elements":[{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-0","eleType":"TEXT"},{"eleTarget":"page-1","eleType":"TEXT"},{"eleTarget":"page-1","eleType":"EXPERIENCE"},{"eleTarget":"page-2","eleType":"TEXT"},{"eleTarget":"page-2","eleType":"EDUCATION"},{"eleTarget":"page-3","eleType":"TEXT"},{"eleTarget":"page-3","eleType":"TEXT"},{"eleTarget":"page-4","eleType":"TEXT"},{"eleTarget":"page-4","eleType":"TEXT"},{"eleTarget":"page-5","eleType":"TEXT"},{"eleTarget":"page-5","eleType":"TEXT"},{"eleTarget":"page-6","eleType":"TEXT"},{"eleTarget":"page-6","eleType":"CREDENTIALS"}],"pages":[{"titleName":"page-0-title","titleValue":"About","fields":[{"fieName":"page-0-ele-0","fieValue":"Mark"},{"fieName":"page-0-ele-1","fieValue":"Hilton"},{"fieName":"page-0-ele-2","fieValue":"A creative"},{"fieName":"page-0-ele-3","fieValue":"developer"},{"fieName":"page-0-ele-4","fieValue":"Grown in the forest educated by robots."},{"fieName":"page-0-ele-5","fieValue":"Some Icon links"}]},{"titleName":"page-1-title","titleValue":"Experience","fields":[{"fieName":"page-1-ele-6","fieValue":"Experience"},{"fieName":"page-1-ele-0-0","fieValue":"Magic developer"},{"fieName":"page-1-ele-0-1","fieValue":"Wizards Ltd."},{"fieName":"page-1-ele-0-2","fieValue":"Providence"},{"fieName":"page-1-ele-0-3","fieValue":"2011"},{"fieName":"page-1-ele-0-4","fieValue":"Create essential magic texts and script code."}]},{"titleName":"page-2-title","titleValue":"Education","fields":[{"fieName":"page-2-ele-7","fieValue":"Education"},{"fieName":"page-2-ele-0-0","fieValue":"Junior Wizard"},{"fieName":"page-2-ele-0-1","fieValue":"Advanced spell management"},{"fieName":"page-2-ele-0-2","fieValue":"Howards"},{"fieName":"page-2-ele-0-3","fieValue":"2001"},{"fieName":"page-2-ele-0-4","fieValue":"Denver"},{"fieName":"page-2-ele-0-5","fieValue":"Texas"}]},{"titleName":"page-3-title","titleValue":"Skills","fields":[{"fieName":"page-3-ele-8","fieValue":"Skills"},{"fieName":"page-3-ele-9","fieValue":"Mobile-First  Responsive DesignCross Browser Testing & Debugging Agile Development & Scrum"}]},{"titleName":"page-4-title","titleValue":"Interests","fields":[{"fieName":"page-4-ele-10","fieValue":"Interests"},{"fieName":"page-4-ele-11","fieValue":"Apart from being a web developer, I enjoy most of my time being outdoors."}]},{"titleName":"page-5-title","titleValue":"Awards","fields":[{"fieName":"page-5-ele-12","fieValue":"Awards"},{"fieName":"page-5-ele-13","fieValue":"No awards yet"}]},{"titleName":"page-6-title","titleValue":"Personal details","fields":[{"fieName":"page-6-ele-14","fieValue":"Personal details"},{"fieName":"page-6-ele-0-0","fieValue":"Mark"},{"fieName":"page-6-ele-0-1","fieValue":"Hilton"},{"fieName":"page-6-ele-0-2","fieValue":"Dakota"},{"fieName":"page-6-ele-0-3","fieValue":" 214 987 548 415"},{"fieName":"page-6-ele-0-4","fieValue":"hilton43@email.com"},{"fieName":"page-6-ele-0-5","fieValue":"04-11-78"},{"fieName":"page-6-ele-0-6","fieValue":"Denver TX"},{"fieName":"page-6-ele-0-7","fieValue":"USA"},{"fieName":"page-6-ele-0-8","fieValue":"32,Elm street, Providence NY"},{"fieName":"page-6-ele-0-9","fieValue":"picture"}]}]}","status":"0","edited":"2017-12-08 23:02:28","views":"0"}';

Body:
Nested JSON objects don't take quotes. Remove the quotes around your content object.

var data = '{"result":"true","id":"31","content":"{"nested":"object"}","status":"0"}';
JSON.parse(data); // SyntaxError

var data = '{"result":"true","id":"31","content":{"nested":"object"},"status":"0"}';
JSON.parse(data); // success


问:
Best practice for client web hosting?
I've recently started building WordPress sites for other businesses. So far, I've been selling hosting as well, but hosting these other sites under my own shared hosting account.

Is this a bad idea? Should I go through the hassle of setting up an official reseller account with my host? Or does it matter? Is there an established "best practice" for this?

答:
If you're doing this on a small scale, it looks like shared hosting might be workable.  If you're planning on selling hosting though, it looks like your clients will get better performance from a resellers account. You'll also have access to customer service and it may be cheaper in the long run.

Here's an article that (briefly) describes the differences.

You'll probably want to check with your hosting company for more concrete details.

Title: Best practice for client web hosting?


问:
selective `for` loop for an R function: `for` loop Or `Vectorize`
I have a small R function called ab. I'm trying to allow user of the function to provide a vector for either argument m or s (not both).

Question:
I'm wondering how should I set up my for loop so that I can selectively loop either over m or s based on user's choice? [is it better to use Vectorize here?]

Here is my R code with no success:

```<code>ab = function(m, s, lo = -Inf, hi = Inf){

loop = if(length(m) > 1) length(m) else length(s)

for(i in 1:loop){

p = function(x) dnorm(x, m[i], s[i])  # [i] should be either for `m` or `s` but what can I do here to have [i] be selectively chosen?
f = function(x) p(x)/integrate(p, lo, hi)[[1]]
curve(f, -3, 3, add = i!= 1, col = i)
    }
}
# Example of use:
ab(m = c(0, .5), s = 1) # Error in integrate(p, lo, hi) : non-finite function value
</code>```

答:
One thought:

```<code>ab <- function(m, s, lo = -Inf, hi = Inf) {
  if (length(m) > 1) {
    if (length(s) > 1) {
      warning("'m' and 's' are both long, truncating 's'")
    }
    s <- rep(s[1], length(m))
  } else {
    m <- rep(m, length(s))
  }
  # something else here ...
}
</code>```

All this is doing is ensuring both variables are the same length, forcing one to be the unchanging variable. (I think that's what you are trying to do ...)

I don't think you can efficiently vectorize the basic calculations, since (among other things) integrate really needs to deal with one problem at a time. To improve anything, I might suggest doing all of the calculation and returning all values into a single list. From there, it's rather straight-forward to plot the lines individually:

```<code>ab <- function(m, s, lo = -Inf, hi = Inf,
               xrange = c(-3, 3), n = 50) {
  if (length(m) > 1) {
    if (length(s) > 1) {
      warning("'m' and 's' are both long, truncating 's'")
    }
    s <- rep(s[1], length(m))
  } else {
    m <- rep(m, length(s))
  }
  xs <- seq(xrange[1], xrange[2], length = n)
  out <- mapply(function(a,b) {
    p = function(x) dnorm(x, a, b)
    f = function(x) p(x) / integrate(p, lo, hi)[[1]]
    list(x = xs, y = sapply(xs, f))
  }, m, s, SIMPLIFY = FALSE)
  out
}
ret <- ab(m = c(0, .5), s = 1)
str(ret)
# List of 2
#  $ :List of 2
#   ..$ x: num [1:50] -3 -2.88 -2.76 -2.63 -2.51 ...
#   ..$ y: num [1:50] 0.00443 0.00635 0.00897 0.01247 0.01709 ...
#  $ :List of 2
#   ..$ x: num [1:50] -3 -2.88 -2.76 -2.63 -2.51 ...
#   ..$ y: num [1:50] 0.000873 0.00133 0.001996 0.002951 0.004298 ...
</code>```

From here, you should be able to plot trivially all at once:

```<code>yrange <- c(0, max(sapply(ret, `[[`, "y")))
plot(0, type = 'n', xlim = c(-3,3), ylim = yrange,
     ylab = "Density", xlab = "Z")
ign <- mapply(function(d,i) lines(y~x, data=d, col=i),
              ret, seq_along(ret))
</code>```

Separating the calculation portion from the plotting portion typically benefits (IMHO) calculation speed, reproduction of plots without recalculation, and organization of code.

Body:
I have a small R function called ab. I'm trying to allow user of the function to provide a vector for either argument m or s (not both).

Question:
I'm wondering how should I set up my for loop so that I can selectively loop either over m or s based on user's choice? [is it better to use Vectorize here?]

Here is my R code with no success:

ab = function(m, s, lo = -Inf, hi = Inf){

loop = if(length(m) > 1) length(m) else length(s)

for(i in 1:loop){

p = function(x) dnorm(x, m[i], s[i])  # [i] should be either for `m` or `s` but what can I do here to have [i] be selectively chosen?
f = function(x) p(x)/integrate(p, lo, hi)[[1]]
curve(f, -3, 3, add = i!= 1, col = i)
    }
}
# Example of use:
ab(m = c(0, .5), s = 1) # Error in integrate(p, lo, hi) : non-finite function value

Body:
One thought:

ab <- function(m, s, lo = -Inf, hi = Inf) {
  if (length(m) > 1) {
    if (length(s) > 1) {
      warning("'m' and 's' are both long, truncating 's'")
    }
    s <- rep(s[1], length(m))
  } else {
    m <- rep(m, length(s))
  }
  # something else here ...
}

All this is doing is ensuring both variables are the same length, forcing one to be the unchanging variable. (I think that's what you are trying to do ...)

I don't think you can efficiently vectorize the basic calculations, since (among other things) integrate really needs to deal with one problem at a time. To improve anything, I might suggest doing all of the calculation and returning all values into a single list. From there, it's rather straight-forward to plot the lines individually:

ab <- function(m, s, lo = -Inf, hi = Inf,
               xrange = c(-3, 3), n = 50) {
  if (length(m) > 1) {
    if (length(s) > 1) {
      warning("'m' and 's' are both long, truncating 's'")
    }
    s <- rep(s[1], length(m))
  } else {
    m <- rep(m, length(s))
  }
  xs <- seq(xrange[1], xrange[2], length = n)
  out <- mapply(function(a,b) {
    p = function(x) dnorm(x, a, b)
    f = function(x) p(x) / integrate(p, lo, hi)[[1]]
    list(x = xs, y = sapply(xs, f))
  }, m, s, SIMPLIFY = FALSE)
  out
}
ret <- ab(m = c(0, .5), s = 1)
str(ret)
# List of 2
#  $ :List of 2
#   ..$ x: num [1:50] -3 -2.88 -2.76 -2.63 -2.51 ...
#   ..$ y: num [1:50] 0.00443 0.00635 0.00897 0.01247 0.01709 ...
#  $ :List of 2
#   ..$ x: num [1:50] -3 -2.88 -2.76 -2.63 -2.51 ...
#   ..$ y: num [1:50] 0.000873 0.00133 0.001996 0.002951 0.004298 ...

From here, you should be able to plot trivially all at once:

yrange <- c(0, max(sapply(ret, `[[`, "y")))
plot(0, type = 'n', xlim = c(-3,3), ylim = yrange,
     ylab = "Density", xlab = "Z")
ign <- mapply(function(d,i) lines(y~x, data=d, col=i),
              ret, seq_along(ret))

Separating the calculation portion from the plotting portion typically benefits (IMHO) calculation speed, reproduction of plots without recalculation, and organization of code.


问:
c# P/Invoke : Pass Enum value with IntPtr to Function; AccessViolationException
I'm implementing C# wrapper to link C-library and having trouble passing Enum value as parameter to Unmanaged function call which takes pointer as input. that is throwing this exception. The code looks like this :

Function from library :

```<code>int function(infoField Field, void const *value);
</code>```

Marshal in C#:

```<code>[DllImport("CLibrary.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
static extern int function(infoField Field, IntPtr value);
</code>```

infoField structure :

```<code>public enum infoField {section, options, orientation};
</code>```

One Enum type 'Options' has 4 values to choose from :

```<code>public enum Options { var1, var2, var3, var4};
</code>```

I want to pass one of the 4 choices as value for EnumField = Options, something like this:

```<code>IntPtr value = (Intptr)Options.var1;
function (infoField.options,  value);
</code>```

I think I am missing correct cast convention for pointer to point to Enum type. What should be correct format to pass enum value with IntPtr to function?
So far, I have tried few options but get AccessViolationException on function call, Which either means memory allocation failed or did not match what what library is expects the type.

PS : Function marshaling is successful for Other EnumFields. That's also because value passing is string value for them. But Particularly for 'options' it has to be one of 4 Enum options.

答:
Normally, C++ enumerators are defined as follows:

```<code>enum class ENUM_FIELD
{
    VAR1,
    VAR2,
    VAR3,
    VAR4
};
</code>```

By default, enum class types are int sized, which means that you can translate them to C# as follows:

```<code>public enum EnumField
{
    VAR1,
    VAR2,
    VAR3,
    VAR4
}
</code>```

In such case, both enums will be mapped without problem within the interop environment. But if the C++ enum is defined in a different way, or if the unmanaged method requires a different type, you may need to change the underlying type in your C# declaration in order to map the values correctly. For example:

```<code>public enum EnumField : short
{
    VAR1,
    VAR2,
    VAR3,
    VAR4
}
</code>```

Anyway, I think the problem is not caused by the enum, but rather by what you pass as the const void* parameter. Casting an enum value to IntPtr doesn't look right to me:

```<code>UInt32 field = (UInt32)EnumField.VAR1;
GCHandle handle = GCHandle.Alloc(field, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();

// pass the ptr variable to the unmanaged function
// and don't forget to handle.Free() when you are done
</code>```

Body:
I'm implementing C# wrapper to link C-library and having trouble passing Enum value as parameter to Unmanaged function call which takes pointer as input. that is throwing this exception. The code looks like this :

Function from library :

int function(infoField Field, void const *value);

Marshal in C#:

[DllImport("CLibrary.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
static extern int function(infoField Field, IntPtr value);

infoField structure :

public enum infoField {section, options, orientation};

One Enum type 'Options' has 4 values to choose from :

public enum Options { var1, var2, var3, var4};

I want to pass one of the 4 choices as value for EnumField = Options, something like this:

IntPtr value = (Intptr)Options.var1;
function (infoField.options,  value);

I think I am missing correct cast convention for pointer to point to Enum type. What should be correct format to pass enum value with IntPtr to function?
So far, I have tried few options but get AccessViolationException on function call, Which either means memory allocation failed or did not match what what library is expects the type.

PS : Function marshaling is successful for Other EnumFields. That's also because value passing is string value for them. But Particularly for 'options' it has to be one of 4 Enum options.

Body:
Normally, C++ enumerators are defined as follows:

enum class ENUM_FIELD
{
    VAR1,
    VAR2,
    VAR3,
    VAR4
};

By default, enum class types are int sized, which means that you can translate them to C# as follows:

public enum EnumField
{
    VAR1,
    VAR2,
    VAR3,
    VAR4
}

In such case, both enums will be mapped without problem within the interop environment. But if the C++ enum is defined in a different way, or if the unmanaged method requires a different type, you may need to change the underlying type in your C# declaration in order to map the values correctly. For example:

public enum EnumField : short
{
    VAR1,
    VAR2,
    VAR3,
    VAR4
}

Anyway, I think the problem is not caused by the enum, but rather by what you pass as the const void* parameter. Casting an enum value to IntPtr doesn't look right to me:

UInt32 field = (UInt32)EnumField.VAR1;
GCHandle handle = GCHandle.Alloc(field, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();

// pass the ptr variable to the unmanaged function
// and don't forget to handle.Free() when you are done


问:
Inspecting pointers to objects inside a vector C++
I am currently going through some code and I currently have a road class, with a vector of pointers to lanes (a private member), and this road class includes a lane class. This lane class contains a vector of pointers to vehicles, which is another class that contains simple get and set functions to update and obtain a vehicle's position, velocity etc. Now, I have vehicles moving in separate lanes and I allow them to switch lanes, as it is so in traffic flow. However, I would like my vehicles to continuously find a distance from it and the vehicle in front, i.e., look in the vehicles vector and find the closest vehicle. Then I intend to use that to instruct whether a car should decelerate or not. I would also like to make sure that cars which are leading the rest, since once a vehicle leaves the displaywindow height, they should be deleted.

My attempt at this is as follows:

```<code>void Lane::Simulate(double time)
{ // This simulate allows check between other vehicles.

double forwardDistance = 0;
    for (unsigned int iV = 0; iV < fVehicles.size(); iV++)
    {
        for(unsigned int jV = 0; jV < fVehicles.size(); jV++)
        {
            forwardDistance = fVehicles[iV]->getPosition() - fVehicles[jV]->getPosition();
        }
    }

    if(fVehicles.size() < 15)
    {
        addRanVehicle(); // Adds a vehicle, with position zero but random velocities, to each lane.
    }

    for (unsigned int iVehicle = 0; iVehicle < fVehicles.size(); iVehicle++)
    {
        fVehicles[iVehicle]->Simulate(time); // Updates position based on time, velocity and acceleration.
    }
}
</code>```

There may be a much better method than using this forwardDistance parameter. The idea is to loop over each pair of vehicles, avoid the point iV == jV, and find the vehicle which is in front of the iVth vehicle, and record the distance between the two vehicles into a setDistance() function (which is a function of my Vehicle class). I should then be able to use this to check whether a car is too close, check whether it can overtake, or whether it just has to brake.

Currently, I am not sure how to make an efficient looping mechanism for this.

答:
Investigate the cost of performing an ordered insert of Vehicles into the lane. If the Vehicles are ordered according to position on the road, detecting the distance of two Vehicles  is child's play:

Eg

```<code>for (size_t n = 0; n < fVehicles.size() - 1; n++)
{
    distance = fVehicles[n].getPosition() - fVehicles[n+1].getPosition();
}
</code>```

This is O(N) vs O(N^2) (using ^ as exponent, not XOR). The price of this simplification is the requiring ordered insert into fVehicles, and that should be O(N): One std::binary_search to detect the insertion point and whatever shuffling is required by fVehicles to free up space to place the Vehicle.

Maintaining ordering of fVehicles may be beneficial in other places as well. Visualizing the list (graphically or by print statements) will be much easier, debugging is generally easier on the human brain when everything is in a nice predictable order, and CPUs... They LOVE going in a nice, predictable straight line. Sometimes you get a performance boost that you didn't see coming. Great write-up on that here: Why is it faster to process a sorted array than an unsorted array?

Only way to be sure if this is better is to try it and measure it.

Other Suggestions:

Don't use pointers to the vehicles.

Not only are they harder to manage, they can slow you down quite a bit. As mentioned above, modern CPUs are really good at going in straight lines, and pointers can throw a kink in that straight line.

You never really know where in dynamic memory a pointer is going to be relative to the last pointer you looked at. But with a contiguous block of Vehicles , when the CPU loads Vehicle N it can possibly also grab Vehicles N+1 and N+2. If it can't because they are too big, it doesn't matter much because it already knows where they are, and while the CPU is processing, and idle memory channel could be reading ahead and grabbing the data you're going to need soon.

With the pointer you save a bit every time you move a Vehicle from lane to lane (pointers are usually much cheaper than objects to copy), but may suffer on each and every loop iteration in each and every simulation tick and the volume really adds up. Bjarne Stroustrup, God-Emperor of C++, has an excellent write up on this problem using linked lists as an example (Note linked list is often worse than vector of pointer, but the idea is the same).

Take advantage of std::deque.

std::vector Is really good at stack-like behaviour. You can add to and remove from the end lightning fast, but if you add to or remove from the beginning, everything in the vector is moved.

Most of the lane insertions are likely to be at one end and the removals at the other simply because older Vehicles will gravitate toward the end as Vehicles are added to the beginning or vise versa. This is a certainty if suggestion 1 is taken and fVehicles is ordered. New vehicles will be added to the lane at the beginning, a few will change lanes into or out of the middle, and old vehicles will be removed from the end. deque is optimized for inserting and removing at both ends so adding new cars is cheap, removing old cars is cheap and you only pay full price for cars that change lanes.

Documentation on std::deque

Addendum

Take advantage of range-based for where possible. Range-based for takes most of the iteration logic away and hides it from you.

Eg this

```<code>for (unsigned int iV = 0; iV < fVehicles.size(); iV++)
{
    for(unsigned int jV = 0; jV < fVehicles.size(); jV++)
    {
        forwardDistance = fVehicles[iV]->getPosition() - fVehicles[jV]->getPosition();
    }
}
</code>```

becomes

```<code>for (auto v_outer: fVehicles)
{
    for (auto v_inner: fVehicles)
    {
        forwardDistance = v_outer->getPosition() - v_inner->getPosition();
    }
}
</code>```

It doesn't look much better if you are counting lines, but you can't accidentally

```<code>iV <= fVehicles.size()
</code>```

or

```<code>fVehicles[iV]->getPosition() - fVehicles[iV]->getPosition()
</code>```

It removes the possibility for you to make silly, fatal, and hard-to-spot errors.

Let's break one down:

```<code>for (auto v_outer: fVehicles)
     ^    ^        ^
  type    |        |
  variable name    |
           Container to iterate
</code>```

Documentation on Range-based for

In this case I'm also taking advantage of auto. auto allows the compiler to select the type of the data. The compiler knows that fVehicles contains pointers to Vehicles, so it replaces auto with  Vehicle * for you. This takes away some of the headaches if you find yourself refactoring the code later.

Documentation on auto

Unfortunately in this cans it can also trap you. If you follow the suggestions above, fVehicles becomes

```<code>std::dequeue<Vehicle> fVehicles;
</code>```

which means auto is now Vehicle. Which makes v_outer a copy, costing you copying time and meaning if you change v_outer, you change a copy and the original goes unchanged. to avoid that, tend toward

```<code>for (auto &v_outer: fVehicles)
</code>```

The compiler is good at deciding how best to handle that reference or if it even needs it.

Body:
I am currently going through some code and I currently have a road class, with a vector of pointers to lanes (a private member), and this road class includes a lane class. This lane class contains a vector of pointers to vehicles, which is another class that contains simple get and set functions to update and obtain a vehicle's position, velocity etc. Now, I have vehicles moving in separate lanes and I allow them to switch lanes, as it is so in traffic flow. However, I would like my vehicles to continuously find a distance from it and the vehicle in front, i.e., look in the vehicles vector and find the closest vehicle. Then I intend to use that to instruct whether a car should decelerate or not. I would also like to make sure that cars which are leading the rest, since once a vehicle leaves the displaywindow height, they should be deleted.

My attempt at this is as follows:

void Lane::Simulate(double time)
{ // This simulate allows check between other vehicles.

double forwardDistance = 0;
    for (unsigned int iV = 0; iV < fVehicles.size(); iV++)
    {
        for(unsigned int jV = 0; jV < fVehicles.size(); jV++)
        {
            forwardDistance = fVehicles[iV]->getPosition() - fVehicles[jV]->getPosition();
        }
    }

    if(fVehicles.size() < 15)
    {
        addRanVehicle(); // Adds a vehicle, with position zero but random velocities, to each lane.
    }

    for (unsigned int iVehicle = 0; iVehicle < fVehicles.size(); iVehicle++)
    {
        fVehicles[iVehicle]->Simulate(time); // Updates position based on time, velocity and acceleration.
    }
}

There may be a much better method than using this forwardDistance parameter. The idea is to loop over each pair of vehicles, avoid the point iV == jV, and find the vehicle which is in front of the iVth vehicle, and record the distance between the two vehicles into a setDistance() function (which is a function of my Vehicle class). I should then be able to use this to check whether a car is too close, check whether it can overtake, or whether it just has to brake.

Currently, I am not sure how to make an efficient looping mechanism for this.

Body:
Investigate the cost of performing an ordered insert of Vehicles into the lane. If the Vehicles are ordered according to position on the road, detecting the distance of two Vehicles  is child's play:

Eg

for (size_t n = 0; n < fVehicles.size() - 1; n++)
{
    distance = fVehicles[n].getPosition() - fVehicles[n+1].getPosition();
}

This is O(N) vs O(N^2) (using ^ as exponent, not XOR). The price of this simplification is the requiring ordered insert into fVehicles, and that should be O(N): One std::binary_search to detect the insertion point and whatever shuffling is required by fVehicles to free up space to place the Vehicle.

Maintaining ordering of fVehicles may be beneficial in other places as well. Visualizing the list (graphically or by print statements) will be much easier, debugging is generally easier on the human brain when everything is in a nice predictable order, and CPUs... They LOVE going in a nice, predictable straight line. Sometimes you get a performance boost that you didn't see coming. Great write-up on that here: Why is it faster to process a sorted array than an unsorted array?

Only way to be sure if this is better is to try it and measure it.

Other Suggestions:

Don't use pointers to the vehicles.

Not only are they harder to manage, they can slow you down quite a bit. As mentioned above, modern CPUs are really good at going in straight lines, and pointers can throw a kink in that straight line.

You never really know where in dynamic memory a pointer is going to be relative to the last pointer you looked at. But with a contiguous block of Vehicles , when the CPU loads Vehicle N it can possibly also grab Vehicles N+1 and N+2. If it can't because they are too big, it doesn't matter much because it already knows where they are, and while the CPU is processing, and idle memory channel could be reading ahead and grabbing the data you're going to need soon.

With the pointer you save a bit every time you move a Vehicle from lane to lane (pointers are usually much cheaper than objects to copy), but may suffer on each and every loop iteration in each and every simulation tick and the volume really adds up. Bjarne Stroustrup, God-Emperor of C++, has an excellent write up on this problem using linked lists as an example (Note linked list is often worse than vector of pointer, but the idea is the same).

Take advantage of std::deque.

std::vector Is really good at stack-like behaviour. You can add to and remove from the end lightning fast, but if you add to or remove from the beginning, everything in the vector is moved.

Most of the lane insertions are likely to be at one end and the removals at the other simply because older Vehicles will gravitate toward the end as Vehicles are added to the beginning or vise versa. This is a certainty if suggestion 1 is taken and fVehicles is ordered. New vehicles will be added to the lane at the beginning, a few will change lanes into or out of the middle, and old vehicles will be removed from the end. deque is optimized for inserting and removing at both ends so adding new cars is cheap, removing old cars is cheap and you only pay full price for cars that change lanes.

Documentation on std::deque

Addendum

Take advantage of range-based for where possible. Range-based for takes most of the iteration logic away and hides it from you.

Eg this

for (unsigned int iV = 0; iV < fVehicles.size(); iV++)
{
    for(unsigned int jV = 0; jV < fVehicles.size(); jV++)
    {
        forwardDistance = fVehicles[iV]->getPosition() - fVehicles[jV]->getPosition();
    }
}

becomes

for (auto v_outer: fVehicles)
{
    for (auto v_inner: fVehicles)
    {
        forwardDistance = v_outer->getPosition() - v_inner->getPosition();
    }
}

It doesn't look much better if you are counting lines, but you can't accidentally

iV <= fVehicles.size()

or

fVehicles[iV]->getPosition() - fVehicles[iV]->getPosition()

It removes the possibility for you to make silly, fatal, and hard-to-spot errors.

Let's break one down:

for (auto v_outer: fVehicles)
     ^    ^        ^
  type    |        |
  variable name    |
           Container to iterate

Documentation on Range-based for

In this case I'm also taking advantage of auto. auto allows the compiler to select the type of the data. The compiler knows that fVehicles contains pointers to Vehicles, so it replaces auto with  Vehicle * for you. This takes away some of the headaches if you find yourself refactoring the code later.

Documentation on auto

Unfortunately in this cans it can also trap you. If you follow the suggestions above, fVehicles becomes

std::dequeue<Vehicle> fVehicles;

which means auto is now Vehicle. Which makes v_outer a copy, costing you copying time and meaning if you change v_outer, you change a copy and the original goes unchanged. to avoid that, tend toward

for (auto &v_outer: fVehicles)

The compiler is good at deciding how best to handle that reference or if it even needs it.


问:
Overwriting variables in coffee script classes and sub classes
I'm a Ruby programmer trying to create a small JavaScript library.

As I'm no big JavaScript expert I'm helping myself with CoffeeScript, fighting my way through a rather unknown territory.

The idea:

I want to create several small JavaScript widgets, all of which share some small pieces of functionality.

The shared functionality and config is in the Base class. Every widget has its own class that inherits from Base and can set its own config (and even overwrite configs of Base).

Finally, when a widget is instantiated, it can be passed an option hash, itself overwriting the default options of the widget.

It looks like this so far:

```<code>@Adg = {}

class Adg.Base
  config =
    debugMessage:   false
    hiddenCssClass: 'visually-hidden'

  # Constructor. Should not be overridden; use @init() instead.
  #
  # - Arg1: The DOM element on which the script should be applied (will be saved as @$el)
  # - Arg2: An optional hash of options which will be merged into the global default config
  constructor: (el, options = {}) ->
    @config = config

    @$el = $(el)

    for key, val of options
      @config[key] = val

    @init()

  # Dummy, must be overridden in inheriting classes.
  init: ->
    throw 'Classes extending App must implement method init()!'

class Adg.Autocomplete extends Adg.Base
  config =
    suggestionsContainer: 'fieldset'
    suggestionsContainerLabel: 'legend'
    alertsContainerId: 'alerts'

  init: ->
    # Merge config into existing one
    for key, val of config
      @config[key] = val
</code>```

This works, but feels clumsy to me:

I don't like that I have to create default constructor that must not be overridden by inheriting classes (I add an init() method as a substitute)

In each inheriting class I have to manually merge the configs

答:
I believe the following will do what you are looking for:

```<code>@Adg = {}

class Adg.Base

  @config =
    debugMessage:   false
    hiddenCssClass: 'visually-hidden'

  constructor: (el, options = {}) ->
    @config = Object.assign {}, Adg.Base.config, options
    @$el = $(el)

class Adg.Autocomplete extends Adg.Base

  @config =
    suggestionsContainer: 'fieldset'
    suggestionsContainerLabel: 'legend'
    alertsContainerId: 'alerts'

  constructor: (el, options={}) ->
    super(el, Object.assign({}, options, Adg.Autocomplete.config))
</code>```

There are a couple changes I made:

Using class properties rather than local variables/closure. @config on Adg.Base is read using Adg.Base.config.

Using super to call the parent constructor from the child's.

Using Object.assign to merge hashes.

Note that if you're using Coffeescript 2 (uninstall coffee-script and install coffeescript@next package), you can use the spread operator instead of Object.assign:

```<code>@config = {Adg.Base.config..., config...}`
</code>```

Body:
I'm a Ruby programmer trying to create a small JavaScript library.

As I'm no big JavaScript expert I'm helping myself with CoffeeScript, fighting my way through a rather unknown territory.

The idea:

I want to create several small JavaScript widgets, all of which share some small pieces of functionality.

The shared functionality and config is in the Base class. Every widget has its own class that inherits from Base and can set its own config (and even overwrite configs of Base).

Finally, when a widget is instantiated, it can be passed an option hash, itself overwriting the default options of the widget.

It looks like this so far:

@Adg = {}

class Adg.Base
  config =
    debugMessage:   false
    hiddenCssClass: 'visually-hidden'

  # Constructor. Should not be overridden; use @init() instead.
  #
  # - Arg1: The DOM element on which the script should be applied (will be saved as @$el)
  # - Arg2: An optional hash of options which will be merged into the global default config
  constructor: (el, options = {}) ->
    @config = config

    @$el = $(el)

    for key, val of options
      @config[key] = val

    @init()

  # Dummy, must be overridden in inheriting classes.
  init: ->
    throw 'Classes extending App must implement method init()!'

class Adg.Autocomplete extends Adg.Base
  config =
    suggestionsContainer: 'fieldset'
    suggestionsContainerLabel: 'legend'
    alertsContainerId: 'alerts'

  init: ->
    # Merge config into existing one
    for key, val of config
      @config[key] = val

This works, but feels clumsy to me:

I don't like that I have to create default constructor that must not be overridden by inheriting classes (I add an init() method as a substitute)

In each inheriting class I have to manually merge the configs

Body:
I believe the following will do what you are looking for:

@Adg = {}

class Adg.Base

  @config =
    debugMessage:   false
    hiddenCssClass: 'visually-hidden'

  constructor: (el, options = {}) ->
    @config = Object.assign {}, Adg.Base.config, options
    @$el = $(el)

class Adg.Autocomplete extends Adg.Base

  @config =
    suggestionsContainer: 'fieldset'
    suggestionsContainerLabel: 'legend'
    alertsContainerId: 'alerts'

  constructor: (el, options={}) ->
    super(el, Object.assign({}, options, Adg.Autocomplete.config))

There are a couple changes I made:

Using class properties rather than local variables/closure. @config on Adg.Base is read using Adg.Base.config.

Using super to call the parent constructor from the child's.

Using Object.assign to merge hashes.

Note that if you're using Coffeescript 2 (uninstall coffee-script and install coffeescript@next package), you can use the spread operator instead of Object.assign:

@config = {Adg.Base.config..., config...}`


问:
About CGRectMake
This will sound extremely silly and stupid, but I have touched a couple languages and they kind of messed up my sense of.... orientation or something:

In Objective-C, you can use CGRectMake(x,y,w,h) to make a rect. Cool.

So x,y set the... top left corner of the rect, or.... the center of the rect?

答: In UIKit, (x,y) is the upper-left corner.</p>

Title: About CGRectMake


问:
CAShapeLayer cutout in UIView
My goal is to create a pretty opaque background with a clear rounded rect inset

```<code>    let shape = CGRect(x: 0, y: 0, width: 200, height: 200)

    let maskLayer = CAShapeLayer()
    maskLayer.path = UIBezierPath(roundedRect: shape, cornerRadius: 16).cgPath
    maskLayer.fillColor = UIColor.clear.cgColor
    maskLayer.fillRule = kCAFillRuleEvenOdd

    let background = UIView()
    background.backgroundColor = UIColor.black.withAlphaComponent(0.8)
    view.addSubview(background)
    constrain(background) {
        $0.edges == $0.superview!.edges
    }

    background.layer.addSublayer(maskLayer)
//        background.layer.mask = maskLayer
</code>```

When I uncomment background.layer.mask = maskLayer, the view is totally clear. When I have it commented out, I see the semi-opaque background color but no mask cutout

Any idea what I'm doing wrong here? Thanks!

答:
Your mask Layer has no size.
Add this line maskLayer.frame = shape

and you don't need background.layer.addSublayer(maskLayer)

Title: CAShapeLayer cutout in UIView

Body:
My goal is to create a pretty opaque background with a clear rounded rect inset

    let shape = CGRect(x: 0, y: 0, width: 200, height: 200)

    let maskLayer = CAShapeLayer()
    maskLayer.path = UIBezierPath(roundedRect: shape, cornerRadius: 16).cgPath
    maskLayer.fillColor = UIColor.clear.cgColor
    maskLayer.fillRule = kCAFillRuleEvenOdd

    let background = UIView()
    background.backgroundColor = UIColor.black.withAlphaComponent(0.8)
    view.addSubview(background)
    constrain(background) {
        $0.edges == $0.superview!.edges
    }

    background.layer.addSublayer(maskLayer)
//        background.layer.mask = maskLayer

When I uncomment background.layer.mask = maskLayer, the view is totally clear. When I have it commented out, I see the semi-opaque background color but no mask cutout

Any idea what I'm doing wrong here? Thanks!