问:
Center-Align Items In MaterializeCSS Row
I am trying to align containers within a row created with the MaterializeCSS library.
The documentation does not seem to mention anything regarding centering objects that are already within the row so I figured I would ask here.

Current code:

```<code><div class="container" style="width: 88%;height: 100%;max-width: 100%;margin: auto;">

<div class="row" style="width: 100%;height: 100%;">

    <div class="col s6 center-align" id="extra-pic-container">
        <img id="extra-pic" width="100%" src="img1.png">
    </div>

    <div class="col s6 center-align" id="extra-pic-container">
        <img id="extra-pic" width="100%" src="img2.png">
    </div>

    <div class="col s6 center-align" id="extra-pic-container">
        <img id="extra-pic" width="100%" src="img3.png">
    </div>

</div>
</code>```

This is what it looks like currently:

What I would like (rough sketch):

Is there any CSS magic that can be performed so that this can be accomplished?

Much appreciated.

答:
On the col.div you need to set:</p>

```<code>float: none;
margin: 0 aut;
</code>```

Body:
I am trying to align containers within a row created with the MaterializeCSS library.
The documentation does not seem to mention anything regarding centering objects that are already within the row so I figured I would ask here.

Current code:

This is what it looks like currently:

What I would like (rough sketch):

Is there any CSS magic that can be performed so that this can be accomplished?

Much appreciated.

Body:
On the col.div you need to set:

float: none;
margin: 0 aut;


来源: stackexchange

问:
RegEx for replacing capture group content using sed
Have inputs.conf files in multiple directories that needs to match and parse each stanza and modify the index= to index=secure.
This are files type in inputs.conf and also do run the script to locate the inputs file in this dir (_GWAS_pr_linux_t1/local/inputs.conf) to modify the index</p>

```<code>[monitor:///var/log/messages]
index=BDBD_np
sourcetype=syslog

[monitor:///var/log/cron]
index=NDNW_np
sourcetype=syslog

[monitor:///var/log/maillog]
index=BSKX_np
sourcetype=syslog

[monitor:///var/log/secure]
index=NDNDK_np
sourcetype=syslog

[monitor:///var/log/spooler]
index=DNWN_np
sourcetype=syslog

[monitor:///var/log/audit/audit.log]
index=XBJB_np
sourcetype=syslog

    sed -i -e 's/.*(?s)((\[monitor\:\/\/\/var\/log\/messages|secure\]).*?)(?:(?:\r*\n){2})' /index=secure *linux*/local/inputs.conf

############################
match each stanza and modify index name to index=windows
inputs file in this dir (_GWAS_pr_window_t1/local/inputs.conf)

    [WinEventLog://Application]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://Security]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://System]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://ForwardedEvents]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://Setup]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    sed -i -e 's/.*(?s)((\[WinEventLog:\/\/Application|Security|System|ForwardedEvents|Setup\]).*?)(?:(?:\r\n){2}) /index=window *window*/local/inputs.conf
</code>```

答:
This might work for you (GNU sed):

```<code>sed -E '/^\[/{h;b};G;s/^(index=)power\n.*(messages|secure)\]$/\1secure/;P;d' file
</code>```

This appends the first line of each stanza to every other line and using pattern matching, replaces power by secure.

ContentLicense: CC BY-SA 4.0

Body:
Have inputs.conf files in multiple directories that needs to match and parse each stanza and modify the index= to index=secure.
This are files type in inputs.conf and also do run the script to locate the inputs file in this dir (_GWAS_pr_linux_t1/local/inputs.conf) to modify the index

[monitor:///var/log/messages]
index=BDBD_np
sourcetype=syslog

[monitor:///var/log/cron]
index=NDNW_np
sourcetype=syslog

[monitor:///var/log/maillog]
index=BSKX_np
sourcetype=syslog

[monitor:///var/log/secure]
index=NDNDK_np
sourcetype=syslog

[monitor:///var/log/spooler]
index=DNWN_np
sourcetype=syslog

[monitor:///var/log/audit/audit.log]
index=XBJB_np
sourcetype=syslog

    sed -i -e 's/.*(?s)((\[monitor\:\/\/\/var\/log\/messages|secure\]).*?)(?:(?:\r*\n){2})' /index=secure *linux*/local/inputs.conf

############################
match each stanza and modify index name to index=windows
inputs file in this dir (_GWAS_pr_window_t1/local/inputs.conf)

    [WinEventLog://Application]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://Security]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://System]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://ForwardedEvents]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    [WinEventLog://Setup]
    checkpointInterval = 5
    current_only = 0
    disabled =0
    start_from = oldest
    index =

    sed -i -e 's/.*(?s)((\[WinEventLog:\/\/Application|Security|System|ForwardedEvents|Setup\]).*?)(?:(?:\r\n){2}) /index=window *window*/local/inputs.conf

Body:
This might work for you (GNU sed):

sed -E '/^\[/{h;b};G;s/^(index=)power\n.*(messages|secure)\]$/\1secure/;P;d' file

This appends the first line of each stanza to every other line and using pattern matching, replaces power by secure.


问:
How to set up different navigation modes for different screens?
I am very new to react-native, but I will try to phrase this the best I can. I have a react-native app that has a navigation bar on the bottom. If the user taps one of the options, they are navigated to the corresponding screen.

The mode for each screen is the default 'card'. This makes it so the screen slides in from the right like a deck  of cards.

```<code>const RootStack = createStackNavigator(
  {
    Main: {
      screen: MainStack,
    },
    MyModal: {
      screen: ModalScreen,
    },
  },
  {
    mode: 'card',
    headerMode: 'none',
  }
);
</code>```

The thing is, I have a 'More' screen that I want to behave differently. It needs to slide up from the bottom of the screen. As I understand, the 'modal' mode will do this.

```<code>mode:'modal',
</code>```

So my question is, can I set all the screens to be mode:'card' and just one screen mode:'modal'? Does anyone know if and how I can do this?

答:
To directly answer your question, React-Navigation docs say that mode can only be set at the navigator level, not for individual screens: The mode configuration for stack navigator can be either card (default) or modal.

However, they do provide direction for achieving a modal:

React-Navigation docs say to create a root navigator with mode: 'modal', and nest your existing navigator within it. When you navigate in the app you should be able to just specify the screen id and it will determine the proper navigator automatically.

Read more:
https://reactnavigation.org/docs/en/modal.html

Body:
I am very new to react-native, but I will try to phrase this the best I can. I have a react-native app that has a navigation bar on the bottom. If the user taps one of the options, they are navigated to the corresponding screen.

The mode for each screen is the default 'card'. This makes it so the screen slides in from the right like a deck  of cards.

const RootStack = createStackNavigator(
  {
    Main: {
      screen: MainStack,
    },
    MyModal: {
      screen: ModalScreen,
    },
  },
  {
    mode: 'card',
    headerMode: 'none',
  }
);

The thing is, I have a 'More' screen that I want to behave differently. It needs to slide up from the bottom of the screen. As I understand, the 'modal' mode will do this.

mode:'modal',

So my question is, can I set all the screens to be mode:'card' and just one screen mode:'modal'? Does anyone know if and how I can do this?


问:
Flutter + Firebase Cloud Functions - How to get data from HttpsCallableResult
I have written a simple cloud function that returns an id that is saved within my Cloud Firestore database.

The cloud function looks like this:

```<code>
exports.getWinkert = functions.https.onCall((data, context) => {

    return admin.firestore().collection('users').doc('hash').get()
    .then(snapshot => {
        const winkertId = snapshot.wwinkert
        return { id: winkertId };
    })
})

</code>```

This function is called from my flutter app with this code:

```<code>
Future _getValues() async {
    final HttpsCallable callable = CloudFunctions.instance.getHttpsCallable(
      functionName: "getWinkert",
    );
    dynamic resp = await callable.call(<String, dynamic>{
      "name": "wwinkert",
    });
    print(resp.toString());
  }

</code>```

Upon calling the function, I get this result:

```<code>I/flutter ( 8253): Instance of 'HttpsCallableResult'
</code>```

Question: How do I get my data from the HttpsCallableResult instance in Dart?

Thank you for your help in advance!

Greets,
Raul

答:
A quick look through this documentation:

https://github.com/flutter/plugins/tree/master/packages/cloud_functions

reveals that one can get data by adding .data to the HttpsCallableResult object.

.
.
.

My apologies :D

Body:
I have written a simple cloud function that returns an id that is saved within my Cloud Firestore database.

The cloud function looks like this:

exports.getWinkert = functions.https.onCall((data, context) => {

    return admin.firestore().collection('users').doc('hash').get()
    .then(snapshot => {
        const winkertId = snapshot.wwinkert
        return { id: winkertId };
    })
})

This function is called from my flutter app with this code:

Future _getValues() async {
    final HttpsCallable callable = CloudFunctions.instance.getHttpsCallable(
      functionName: "getWinkert",
    );
    dynamic resp = await callable.call(<String, dynamic>{
      "name": "wwinkert",
    });
    print(resp.toString());
  }

Upon calling the function, I get this result:

I/flutter ( 8253): Instance of 'HttpsCallableResult'

Question: How do I get my data from the HttpsCallableResult instance in Dart?

Thank you for your help in advance!

Greets,
Raul


问:
Does this script follow common standard? (Javascript/Html)
I just made a simple Javascript Quiz script here:

```<code>/* Dade Lamkins.  2011. */

var Questions = [
    { Question: "What is 5+2?", Values: ["7", "9", "10", "6"], Answer: 1 },
    { Question: "What is the square root of 16?", Values: ["7", "5", "4", "1"], Answer: 3 },
    { Question: "What is the answer to life?", Values: ["7", "42", "4", "47"], Answer: 2 }
];

var currentSession={ Questions: [], TotalPoints: 0 }

var Letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

function createQuestions(id) {
    var tReturn="<form style=\"text-align: left;width: 33.33333%;background-color: lightblue;border=1px solid #000000;padding: 10px\">";
    tReturn=tReturn+"<b>Questions "+(id+1)+":</b><br />    <i>"+Questions[id].Question+"</i><br /><br />";
    for (var i=0;i<(Questions[id].Values).length;i++) {
        tReturn=tReturn+"<input onClick=\"checkAnswer("+id+","+i+",this)\" type=\"button\" value=\""+Letters[i]+"\" style=\"width:50px\" />. "+Questions[id].Values[i]+"<br />";
    }
    tReturn=tReturn+"</form>";
    return tReturn;
}

function updateScore() {
    var currentPoints=0;
    for (var i=0;i<currentSession.Questions.length;i++) {
        currentPoints+=currentSession.Questions[i].Score;
    }
    document.getElementById('quiz_score').innerHTML='%'+Math.round((currentPoints/currentSession.TotalPoints)*100);
}

function initializeQuiz() {
    for (var i=0;i<Questions.length;i++) {
        var elem=document.getElementById('quiz_section');
        currentSession.TotalPoints+=parseInt(elem.getAttribute('chances'));
        elem.innerHTML=elem.innerHTML+createQuestions(i)+"<br />";
        currentSession.Questions[i]={ Chances: elem.getAttribute('chances'), Answered: false, Score: parseInt(elem.getAttribute('chances')) };
    }
    updateScore();
}

function finalizeAnswer(bttn,c,questionId) {
    if (c) {
        bttn.parentNode.style.backgroundColor="lightgreen";
        bttn.parentNode.innerHTML="<b>QUESTION "+(questionId+1)+":</b> Correct!";
    } else {
        bttn.parentNode.style.backgroundColor="pink";
        bttn.parentNode.innerHTML="<b>QUESTION "+(questionId+1)+":</b> Wrong!";
    }
    updateScore();
}

function checkAnswer(questionId,answerId,bttn) {
    if (Questions[questionId].Answer==(answerId+1)) {
        finalizeAnswer(bttn,true,questionId);
        return 0;
    } else {
        bttn.setAttribute('value','x');
        bttn.setAttribute('disabled','true');
    }
    currentSession.Questions[questionId].Chances--;
    currentSession.Questions[questionId].Score--;
    if (currentSession.Questions[questionId].Chances<=0) {
        finalizeAnswer(bttn,false,questionId);
    } else {
        updateScore();
    }
}
</code>```

You then put this is another html page:

```<code><html>
    <head>
        <title>HTML QUIZ</title>
        <script language="javascript" src="Quiz.js"></script>
    </head>
    <body onload='javascript:initializeQuiz()' bgcolor="#CCFFFF">
        <b>Your Score Is Currently:  </b><span id="quiz_score"></span>
        <br />
        <br />
        <center><span style="width:100%" id="quiz_section" chances="1" quizid="1"></span></center>
    </body>
</html>
</code>```

My question is, are all the methods I've used here generally accepted?

答: Your use of innerHTML might earn you a visit from the JavaScript style police, other than that it looks fine. The most secure and robust way of building HTML on the client is to make DOM elements using document.createElement https://developer.mozilla.org/en/DOM/document.createElement and Node.appendChild https://developer.mozilla.org/En/DOM/Node.appendChild .

ContentLicense: CC BY-SA 3.0

Body:
I just made a simple Javascript Quiz script here:

/* Dade Lamkins.  2011. */

var Questions = [
    { Question: "What is 5+2?", Values: ["7", "9", "10", "6"], Answer: 1 },
    { Question: "What is the square root of 16?", Values: ["7", "5", "4", "1"], Answer: 3 },
    { Question: "What is the answer to life?", Values: ["7", "42", "4", "47"], Answer: 2 }
];

var currentSession={ Questions: [], TotalPoints: 0 }

var Letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

function createQuestions(id) {
    var tReturn="<form style=\"text-align: left;width: 33.33333%;background-color: lightblue;border=1px solid #000000;padding: 10px\">";
    tReturn=tReturn+"Questions "+(id+1)+":
    "+Questions[id].Question+"

";
    for (var i=0;i<(Questions[id].Values).length;i++) {
        tReturn=tReturn+"<input onClick=\"checkAnswer("+id+","+i+",this)\" type=\"button\" value=\""+Letters[i]+"\" style=\"width:50px\" />. "+Questions[id].Values[i]+"
";
    }
    tReturn=tReturn+"</form>";
    return tReturn;
}

function updateScore() {
    var currentPoints=0;
    for (var i=0;i<currentSession.Questions.length;i++) {
        currentPoints+=currentSession.Questions[i].Score;
    }
    document.getElementById('quiz_score').innerHTML='%'+Math.round((currentPoints/currentSession.TotalPoints)*100);
}

function initializeQuiz() {
    for (var i=0;i<Questions.length;i++) {
        var elem=document.getElementById('quiz_section');
        currentSession.TotalPoints+=parseInt(elem.getAttribute('chances'));
        elem.innerHTML=elem.innerHTML+createQuestions(i)+"
";
        currentSession.Questions[i]={ Chances: elem.getAttribute('chances'), Answered: false, Score: parseInt(elem.getAttribute('chances')) };
    }
    updateScore();
}

function finalizeAnswer(bttn,c,questionId) {
    if (c) {
        bttn.parentNode.style.backgroundColor="lightgreen";
        bttn.parentNode.innerHTML="QUESTION "+(questionId+1)+": Correct!";
    } else {
        bttn.parentNode.style.backgroundColor="pink";
        bttn.parentNode.innerHTML="QUESTION "+(questionId+1)+": Wrong!";
    }
    updateScore();
}

function checkAnswer(questionId,answerId,bttn) {
    if (Questions[questionId].Answer==(answerId+1)) {
        finalizeAnswer(bttn,true,questionId);
        return 0;
    } else {
        bttn.setAttribute('value','x');
        bttn.setAttribute('disabled','true');
    }
    currentSession.Questions[questionId].Chances--;
    currentSession.Questions[questionId].Score--;
    if (currentSession.Questions[questionId].Chances<=0) {
        finalizeAnswer(bttn,false,questionId);
    } else {
        updateScore();
    }
}

You then put this is another html page:

        <title>HTML QUIZ</title>

        Your Score Is Currently:

My question is, are all the methods I've used here generally accepted?


问:
Javascript Async Await function requirements
I have a project (html + JavaScript) created by other person. There is an image and a button on that html page. When I click the button, it calls a function and processes the image.

My task is to process multiple images using that function. The images must be processed consecutive (not parallel), this is important.

I use Async Await way to call the function, but the 'for loop' does not wait till the function finished processing the first image, it goes to the next images.

I tried to do this different ways (using promises etc.), but it does not work as expected. How can I force the 'for loop' to wait?

```<code>async function processImages(fileList) {
    for (let file of fileList) {
        await processOneImage(file);
    }
}

async function processOneImage(filename) {
    // load an image
    document.getElementById('ImageToBeProcessed').src = filename;
    // call the function created by other person
    await document.querySelector('#start_process').click();
}
</code>```

Is there some requirement for the .click() function to work with 'await' in a correct way? For example, .click() does not return anything now. Should I add

```<code>return someVar
</code>```

to the end of the .click() function?

Or maybe the .click() function should also have 'async' word before 'function'?

I looked at many async/await samples, but it did not help.

Thanks.

P.S. More info:

That html+script use Google Polymer (perhaps it is important). I shortened the .click() function code to show you. Now it looks like:

```<code>this.startProcessButton.addEventListener('click', function () {
    _this.prepareData()
        .then(function () {
        // removed unneeded code here ...
        _this.doProcessing()
        // removed unneeded code here ...
    })
        .catch(function (error) {
        console.log(error);
    });
});
</code>```

As I understand, it is a promise.

Unfortunately I can not contact that person. He/she does not answer any questions from Autumn.

答:
To be able to await an operation, it needs to be async (or returning a promise). Furthermore, when you emit a click on the button, you only execute (and wait for completion) of the click, not the event handler.

You should create a function for processing one image (at the moment your processOneImage function doesn't process an image (!), it emits a click on a DOM button):

```<code>function processOneImage(image) {
    return _this.prepareData()
        .then(function () {
        // removed unneeded code here ...
        _this.doProcessing()
        // removed unneeded code here ...
    })
        .catch(function (error) {
        console.log(error);
    });
}
</code>```

please note that I've returned the promise!

Then you can have it added to the event listener:

```<code>this.startProcessButton.addEventListener('click', (e) => processOneImage(getFileNameFromClickEvent(e));
</code>```

separate your UI related concerns from your processing - getFileNameFromClickEvent can help figuring out how to get your file name or other input from the ui

If you have this, you can reuse the processOneImage function (awaitable) w/o need of messing with DOM actions and emitting clicks.

```<code>async function processImages(fileList) {
    for (const file of fileList) {
        await processOneImage(file);
    }
}
</code>```

Note: this is a quick fix, you should consider following best practices (e.g. not mixing vanilla promises with async/await) and using a modern client framework/lib like React.js.

Body:
I have a project (html + JavaScript) created by other person. There is an image and a button on that html page. When I click the button, it calls a function and processes the image.

My task is to process multiple images using that function. The images must be processed consecutive (not parallel), this is important.

I use Async Await way to call the function, but the 'for loop' does not wait till the function finished processing the first image, it goes to the next images.

I tried to do this different ways (using promises etc.), but it does not work as expected. How can I force the 'for loop' to wait?

async function processImages(fileList) {
    for (let file of fileList) {
        await processOneImage(file);
    }
}

async function processOneImage(filename) {
    // load an image
    document.getElementById('ImageToBeProcessed').src = filename;
    // call the function created by other person
    await document.querySelector('#start_process').click();
}

Is there some requirement for the .click() function to work with 'await' in a correct way? For example, .click() does not return anything now. Should I add

return someVar

to the end of the .click() function?

Or maybe the .click() function should also have 'async' word before 'function'?

I looked at many async/await samples, but it did not help.

Thanks.

P.S. More info:

That html+script use Google Polymer (perhaps it is important). I shortened the .click() function code to show you. Now it looks like:

this.startProcessButton.addEventListener('click', function () {
    _this.prepareData()
        .then(function () {
        // removed unneeded code here ...
        _this.doProcessing()
        // removed unneeded code here ...
    })
        .catch(function (error) {
        console.log(error);
    });
});

As I understand, it is a promise.

Unfortunately I can not contact that person. He/she does not answer any questions from Autumn.

Body:
To be able to await an operation, it needs to be async (or returning a promise). Furthermore, when you emit a click on the button, you only execute (and wait for completion) of the click, not the event handler.

You should create a function for processing one image (at the moment your processOneImage function doesn't process an image (!), it emits a click on a DOM button):

function processOneImage(image) {
    return _this.prepareData()
        .then(function () {
        // removed unneeded code here ...
        _this.doProcessing()
        // removed unneeded code here ...
    })
        .catch(function (error) {
        console.log(error);
    });
}

please note that I've returned the promise!

Then you can have it added to the event listener:

this.startProcessButton.addEventListener('click', (e) => processOneImage(getFileNameFromClickEvent(e));

separate your UI related concerns from your processing - getFileNameFromClickEvent can help figuring out how to get your file name or other input from the ui

If you have this, you can reuse the processOneImage function (awaitable) w/o need of messing with DOM actions and emitting clicks.

async function processImages(fileList) {
    for (const file of fileList) {
        await processOneImage(file);
    }
}

Note: this is a quick fix, you should consider following best practices (e.g. not mixing vanilla promises with async/await) and using a modern client framework/lib like React.js.


问:
How to get the newest address for each person
I have created a simple Access database an example of table structure and a query.  Two tables, person(contains 3 records) & address(contains 5 records), provide the ability to capture multiple addresses for each person.  I am good with normal conditional statements, but this one is throwing me for a loop...
I am looking for a query that will return only the newest address for a given person.
Table Relationship

Current sql for the query:

```SELECT Person.PersonID_PK, Address.Address, Address.StatusDate
FROM Person INNER JOIN Address ON Person.[PersonID_PK] = Address.PersonID_FK;```

My current returns:

```EmployeeID_PK  Address                         StatusDate
1               12 Elm St, MN  23569            11/13/2017
1               15 Apple Ln, NY 12345           7/15/2018
2               30 Mulberry, TN 38456           6/11/2018
2               10 Lonesome Pine, KY 15487      12/4/2018
3               100 Plaze Place, LA 14563       6/17/2018  ```

I need to return each person along with the greatest(newest) StatusDate
My expected return should be:

```EmployeeID_PK  Address                             StatusDate
1               15 Apple Ln, NY 12345                7/15/2018
2               10 Lonesome Pine, KY 15487           12/4/2018
3               100 Plaze Place, LA 14563            6/17/2018```

答:
Thanks for the help.  I modified Gordon's code to support my query, the following provided the answer.</p>

```<code>SELECT Person.PersonID_PK, Address.Address, Address.StatusDate
FROM Person
INNER JOIN Address
ON Person.[PersonID_PK] = Address.PersonID_FK
WHERE (((Address.StatusDate)=(SELECT MAX(Address.StatusDate)
FROM Address
WHERE Person.PersonID_PK = Address.PersonID_FK)));
</code>```

Body:
I have created a simple Access database an example of table structure and a query.  Two tables, person(contains 3 records) & address(contains 5 records), provide the ability to capture multiple addresses for each person.  I am good with normal conditional statements, but this one is throwing me for a loop...
I am looking for a query that will return only the newest address for a given person.
Table Relationship

Current sql for the query:

SELECT Person.PersonID_PK, Address.Address, Address.StatusDate
FROM Person INNER JOIN Address ON Person.[PersonID_PK] = Address.PersonID_FK;

My current returns:

EmployeeID_PK  Address                         StatusDate
1               12 Elm St, MN  23569            11/13/2017
1               15 Apple Ln, NY 12345           7/15/2018
2               30 Mulberry, TN 38456           6/11/2018
2               10 Lonesome Pine, KY 15487      12/4/2018
3               100 Plaze Place, LA 14563       6/17/2018

I need to return each person along with the greatest(newest) StatusDate
My expected return should be:

EmployeeID_PK  Address                             StatusDate
1               15 Apple Ln, NY 12345                7/15/2018
2               10 Lonesome Pine, KY 15487           12/4/2018
3               100 Plaze Place, LA 14563            6/17/2018

Body:
Thanks for the help.  I modified Gordon's code to support my query, the following provided the answer.

SELECT Person.PersonID_PK, Address.Address, Address.StatusDate
FROM Person
INNER JOIN Address
ON Person.[PersonID_PK] = Address.PersonID_FK
WHERE (((Address.StatusDate)=(SELECT MAX(Address.StatusDate)
FROM Address
WHERE Person.PersonID_PK = Address.PersonID_FK)));


问:
nvprof is crashing as it writes a very large file to /tmp/ and runs out of disk space
How do I work-around an nvprof crash that occurs when running on a disk with a relatively small amount of space available?

Specifically, when profiling my cuda kernel, I use the following two commands:

```<code># Generate the timeline
nvprof -f -o ~/myproj/profiling/timeline-`date -I`.out ~/myproj/build/myexe
# Generate profiling data
nvprof -f --kernels ::mykernel:1 --analysis-metrics -o ~/myproj/profiling/analysis-metrics-`date -I`.out ~/myproj/build/myexe
</code>```

The first nvprof command works fine.  The second nvprof needs to write a 12GB temporary file to /tmp before it can proceed.  Since my 38GB cloud disk only has 6 GB available, nvprof crashes.  Assuming I can't free up more disk space, how do I work around this problem?

Side note:
It's mostly irrelevant to diagnosing the problem, but nvprof is reporting an Error: Application received signal 7, which is a "Bus error (bad memory access)" (see http://man7.org/linux/man-pages/man7/signal.7.html for more info).

答:
One can direct nvprof to use a different temporary directory by setting the TMPDIR environment variable.  This is helpful, because since Linux kernel 2.6, there's a decent chance that you have a RAM disk available at /dev/shm (see https://superuser.com/a/45509/363816 for more info).  Thus, adding the following at the beginning of one's [bash] script will likely work-around your issue.

```<code>export TMPDIR=/dev/shm
</code>```

Body:
How do I work-around an nvprof crash that occurs when running on a disk with a relatively small amount of space available?

Specifically, when profiling my cuda kernel, I use the following two commands:

# Generate the timeline
nvprof -f -o ~/myproj/profiling/timeline-`date -I`.out ~/myproj/build/myexe
# Generate profiling data
nvprof -f --kernels ::mykernel:1 --analysis-metrics -o ~/myproj/profiling/analysis-metrics-`date -I`.out ~/myproj/build/myexe

The first nvprof command works fine.  The second nvprof needs to write a 12GB temporary file to /tmp before it can proceed.  Since my 38GB cloud disk only has 6 GB available, nvprof crashes.  Assuming I can't free up more disk space, how do I work around this problem?

Side note:
It's mostly irrelevant to diagnosing the problem, but nvprof is reporting an Error: Application received signal 7, which is a "Bus error (bad memory access)" (see http://man7.org/linux/man-pages/man7/signal.7.html for more info).

Body:
One can direct nvprof to use a different temporary directory by setting the TMPDIR environment variable.  This is helpful, because since Linux kernel 2.6, there's a decent chance that you have a RAM disk available at /dev/shm (see https://superuser.com/a/45509/363816 for more info).  Thus, adding the following at the beginning of one's [bash] script will likely work-around your issue.

export TMPDIR=/dev/shm


问:
copying files from subfolders and renaming
i need help with a task

I need to copy an exported file from sub-directories into a new folder location and have them renamed. The issue is that all the exported files have the same name and it goes up to 500

```<code>--Old Folder
 ---Export1
    ---Scan.TIF
 ---Export2
    ---Scan.TIF
 ---Export3
    ---Scan.TIF
</code>```

I have tried the following link which worked fine but the data would be all over the place. For example, the copied and renamed file in the new folder location called eg SCAN13.TIF would actualy be the document from sub-directory Export24

https://sumtips.com/snippets/powershell/copy-files-rename-duplicates-subfolder/

I need help with a script that could copy the file from all the sub-directories to a new location, renamed and have the data matched

Is that doable via scripting or would there be a tool for that?

Thanks for your time

答:
You could try this first

Puts the name of the folder at the beginning of the file name

```<code>Get-ChildItem <Directory of File> -Filter *.ext -Recurse | Rename-Item -NewName {$_.Directory.Name+'_'+$_.Name}
</code>```

Its not the whole answer you are looking for but hopefully a piece of what you need.

Body:
i need help with a task

I need to copy an exported file from sub-directories into a new folder location and have them renamed. The issue is that all the exported files have the same name and it goes up to 500

--Old Folder
 ---Export1
    ---Scan.TIF
 ---Export2
    ---Scan.TIF
 ---Export3
    ---Scan.TIF

I have tried the following link which worked fine but the data would be all over the place. For example, the copied and renamed file in the new folder location called eg SCAN13.TIF would actualy be the document from sub-directory Export24

https://sumtips.com/snippets/powershell/copy-files-rename-duplicates-subfolder/

I need help with a script that could copy the file from all the sub-directories to a new location, renamed and have the data matched

Is that doable via scripting or would there be a tool for that?

Thanks for your time

Body:
You could try this first

Puts the name of the folder at the beginning of the file name

Get-ChildItem <Directory of File> -Filter *.ext -Recurse | Rename-Item -NewName {$_.Directory.Name+'_'+$_.Name}

Its not the whole answer you are looking for but hopefully a piece of what you need.


问:
How to loop through the alphabet via underscoreJS
I'm using Underscore's template() method in BackboneJS views. I'd like to show a list of alphabet letters in my view in order to sort a collection by letter.

As a result, I have a list of 26 links (one link = one letter) in my view. Instead of copy-pasting each link (which is very bad for code maintainability), I was wondering if it was possible to loop through the alphabet via underscoreJS.

Result to display :

```<code><li ><a href="#">a</a></li>
<li ><a href="#">b</a></li>
<li ><a href="#">c</a></li>
...
<li ><a href="#">z</a></li>
</code>```

答:
Another approach with underscore (or loadash):</p>

```<code>_.map(_.range(26), function(i) { return String.fromCharCode(97 + i) });

// returns ['a', 'b', ..., 'z']
</code>```

Body:
I'm using Underscore's template() method in BackboneJS views. I'd like to show a list of alphabet letters in my view in order to sort a collection by letter.

As a result, I have a list of 26 links (one link = one letter) in my view. Instead of copy-pasting each link (which is very bad for code maintainability), I was wondering if it was possible to loop through the alphabet via underscoreJS.

Result to display :

a

b

c

...

z

Body:
Another approach with underscore (or loadash):

_.map(_.range(26), function(i) { return String.fromCharCode(97 + i) });

// returns ['a', 'b', ..., 'z']


问:
Entity Framework Code-First - Defining relationships with MembershipUser
I'm trying to understand the best way to define my POCO classes to be able to use Entity Framework code-first feature.

I want to define some foreign key relations in my classes, between the user and also between the classes themselves. For example consider the following 3 classes:

```<code>Public class Job
{
    public int JobID {get; set;}
    public string JobTitle {get; set;}
    public virtual ICollection<Resume> Resumes {get; set;} // Is this correct at all? How to access all resumes for a certain job? (many-to-many relationship between Job and Employee)
}

Public class Resume
{
    public int EmployeeID {get; set;} // or should it be: public virtual Employee EmployeePerson?
    public int JobID {get; set;} // or should it be: public virtual Job UserJob?
    public DateTime EmploymentDate {get; set;}
}

public class Employee
{
    public int EmployeeID {get; set;}
    public int UserID{ger; set;} // or should it be: public virtual MembershipUser User?
    public ICollection<Resume> Resumes {get; set;} // Is this correct at all?
}
</code>```

The user is a Membership user which is in System.Web.Security which is being authenticated by FormsAuthentication or ActiveDirectoryAuthentication.  The questions are mentioned in the code (as comments). But for clarification:

Should I define the objects in relations and use .Include every time I need them or is it better to store the ID of the objects and try to get the data from that ID every time I need to? Should I use a different approach when dealing with MembershipUser class instead of my defined classes?

What's other uses of virtual apart from enabling lazy loading? Where should I avoid it and where should I use it?

Thank you.

UPDATE: I have just tested to define Employee with the ublic virtual MembershipUser User definition. The result was 4 added columns in my table:

User_Email,

User_Comment,

User_IsApproved,

User_LastLoginDate,

User_LastActivityDate

Nothing unique to the user (User_Email is defined as nullable). So If you want to have user in you classes, write a wrapper for MembershipUser or just store UserID.

Thank you Ladislav and Sergi.

答:
In case of code first I would probably use this:

```<code>public class Job
{
    public virtual int JobId {get; set;}
    public virtual string JobTitle {get; set;}
    public virtual ICollection<Resume> Resumes {get; set;}
}

public class Resume
{
    [Key, Column(Order = 0)]
    public virtual int EmployeeId {get; set;}
    [Key, Column(Order = 1)]
    public virtual int JobId {get; set;}

    public virtual DateTime EmploymentDate {get; set;}
    public virtual Employee Employee {get; set;}
    public virtual Job Job {get; set;}
}

public class Employee
{
    public virtual int EmployeeId {get; set;}
    public virtual int UserId {ger; set;}
    public virtual User User {get;set;}
    public virtual ICollection<Resume> Resumes {get; set;}
}
</code>```

Foreign keys in entity are bad but they make things much easier in EF. If you don't use foreign key property EF will define different type of relationship. Virtual keyword on navigation property is for lazy loading and virtual keyword on other mapped properties is for change tracking.

Body:
I'm trying to understand the best way to define my POCO classes to be able to use Entity Framework code-first feature.

I want to define some foreign key relations in my classes, between the user and also between the classes themselves. For example consider the following 3 classes:

Public class Job
{
    public int JobID {get; set;}
    public string JobTitle {get; set;}
    public virtual ICollection<Resume> Resumes {get; set;} // Is this correct at all? How to access all resumes for a certain job? (many-to-many relationship between Job and Employee)
}

Public class Resume
{
    public int EmployeeID {get; set;} // or should it be: public virtual Employee EmployeePerson?
    public int JobID {get; set;} // or should it be: public virtual Job UserJob?
    public DateTime EmploymentDate {get; set;}
}

public class Employee
{
    public int EmployeeID {get; set;}
    public int UserID{ger; set;} // or should it be: public virtual MembershipUser User?
    public ICollection<Resume> Resumes {get; set;} // Is this correct at all?
}

The user is a Membership user which is in System.Web.Security which is being authenticated by FormsAuthentication or ActiveDirectoryAuthentication.  The questions are mentioned in the code (as comments). But for clarification:

Should I define the objects in relations and use .Include every time I need them or is it better to store the ID of the objects and try to get the data from that ID every time I need to? Should I use a different approach when dealing with MembershipUser class instead of my defined classes?

What's other uses of virtual apart from enabling lazy loading? Where should I avoid it and where should I use it?

Thank you.

UPDATE: I have just tested to define Employee with the ublic virtual MembershipUser User definition. The result was 4 added columns in my table:

User_Email,

User_Comment,

User_IsApproved,

User_LastLoginDate,

User_LastActivityDate

Nothing unique to the user (User_Email is defined as nullable). So If you want to have user in you classes, write a wrapper for MembershipUser or just store UserID.

Thank you Ladislav and Sergi.

Body:
In case of code first I would probably use this:

public class Job
{
    public virtual int JobId {get; set;}
    public virtual string JobTitle {get; set;}
    public virtual ICollection<Resume> Resumes {get; set;}
}

public class Resume
{
    [Key, Column(Order = 0)]
    public virtual int EmployeeId {get; set;}
    [Key, Column(Order = 1)]
    public virtual int JobId {get; set;}

    public virtual DateTime EmploymentDate {get; set;}
    public virtual Employee Employee {get; set;}
    public virtual Job Job {get; set;}
}

public class Employee
{
    public virtual int EmployeeId {get; set;}
    public virtual int UserId {ger; set;}
    public virtual User User {get;set;}
    public virtual ICollection<Resume> Resumes {get; set;}
}

Foreign keys in entity are bad but they make things much easier in EF. If you don't use foreign key property EF will define different type of relationship. Virtual keyword on navigation property is for lazy loading and virtual keyword on other mapped properties is for change tracking.


问:
FB.logout() called without an access token
I'm trying to log out of a website i've created with Facebook integrated.
Logging in works fine, but when I want to log out Firebug consistently gives me this error:

FB.logout() called without an access token.

I'm using the Facebook JavaScript SDK, and the code I've got to logout looks like this:

```<code>$(document).ready($(function () {
    $("#fblogout").click(facebooklogout);
}));

function facebooklogout() {
    FB.logout(function (response) {
    }
)};
</code>```

This is the logout code specified at the Facebook Developers Documentation just with a button being assigned the method on document.ready

Before this code I have the FB.init() method, that all runs fine.

If anyone's got a solution as to why FB.logout doesn't have an access token, it'd be appreciated.

答:
Figured it out after so many tries.

Generally response.authResponse.accessToken contains token. So, its error about the accessToken not being there.

Think logically, where does that response come from in your code? Out of nowhere.

So, we need to get that response object from a function and get this working.
I don't know how it worked for others, but this worked for me.

Just replace the code with this

```<code>function logout(){
  FB.getLoginStatus(function(response) {
    FB.logout(function(response){
      console.log("Logged Out!");
      window.location = "/";
    });
  });
}
</code>```

What we do here is, get the login status if the user is logged in and get the corresponding response in return, which contains all the necessary tokens and data. Once this is fetched, the token is used to log out the user.

Body:
I'm trying to log out of a website i've created with Facebook integrated.
Logging in works fine, but when I want to log out Firebug consistently gives me this error:

FB.logout() called without an access token.

I'm using the Facebook JavaScript SDK, and the code I've got to logout looks like this:

$(document).ready($(function () {
    $("#fblogout").click(facebooklogout);
}));

function facebooklogout() {
    FB.logout(function (response) {
    }
)};

This is the logout code specified at the Facebook Developers Documentation just with a button being assigned the method on document.ready

Before this code I have the FB.init() method, that all runs fine.

If anyone's got a solution as to why FB.logout doesn't have an access token, it'd be appreciated.

Body:
Figured it out after so many tries.

Generally response.authResponse.accessToken contains token. So, its error about the accessToken not being there.

Think logically, where does that response come from in your code? Out of nowhere.

So, we need to get that response object from a function and get this working.
I don't know how it worked for others, but this worked for me.

Just replace the code with this

function logout(){
  FB.getLoginStatus(function(response) {
    FB.logout(function(response){
      console.log("Logged Out!");
      window.location = "/";
    });
  });
}

What we do here is, get the login status if the user is logged in and get the corresponding response in return, which contains all the necessary tokens and data. Once this is fetched, the token is used to log out the user.


问:
Retrieving a row when specific text strings occur in SQL
I'm trying to retrieve rows that contain only a specific text string(s). The issue is that sometimes the text string can me mixed in with other text strings, and when this occurs, I do NOT want to retrieve this row. Here's an idea of the data that I'm working with:

```<code>    MED_TABLE
______________________________________
med_code    |   med_name
______________________________________
1            calcium potassium iodine fluoride
2            potassium calcium
3            hydrochloride; calcium
4            iodine, calcium, fluoride
5            iodine calcium phosphate
6            calcium phosphate
7            IODINE
8            calcium PHOSPHATE iodine
</code>```

If I want to return rows that ONLY contain the strings 'calcium phosphate' and/or 'iodine', either independently or in pair, what's an efficient way of going about this? In this case, I would only want to return rows 5, 6, 7, 8.

I was trying to do this by using a query like this:

```<code>SELECT med_code, med_name
FROM med_table
WHERE lower(med_name) LIKE '%calcium phosphate%'
OR WHERE lower(med_name) LIKE '%iodine%'
</code>```

But this returns rows that contain text strings that I do not want.

答:
You must replace both terms and commas with empty strings, then trim the result and check if the length is 0:

```<code>SELECT med_code, med_name
FROM med_table
WHERE
  length(trim(
    regexp_replace(regexp_replace(regexp_replace(lower(med_name), 'calcium phosphate', ''), 'iodine', ''), ',', '')
  )) = 0
</code>```

See the demo (for MySql the difference is the use of replace instead of Hive's regexp_replace).

Results:

```<code>| med_code | med_name                 |
| -------- | ------------------------ |
| 5        | iodine calcium phosphate |
| 6        | calcium phosphate        |
| 7        | IODINE                   |
| 8        | calcium PHOSPHATE iodine |
</code>```

Body:
I'm trying to retrieve rows that contain only a specific text string(s). The issue is that sometimes the text string can me mixed in with other text strings, and when this occurs, I do NOT want to retrieve this row. Here's an idea of the data that I'm working with:

    MED_TABLE
______________________________________
med_code    |   med_name
______________________________________
1            calcium potassium iodine fluoride
2            potassium calcium
3            hydrochloride; calcium
4            iodine, calcium, fluoride
5            iodine calcium phosphate
6            calcium phosphate
7            IODINE
8            calcium PHOSPHATE iodine

If I want to return rows that ONLY contain the strings 'calcium phosphate' and/or 'iodine', either independently or in pair, what's an efficient way of going about this? In this case, I would only want to return rows 5, 6, 7, 8.

I was trying to do this by using a query like this:

SELECT med_code, med_name
FROM med_table
WHERE lower(med_name) LIKE '%calcium phosphate%'
OR WHERE lower(med_name) LIKE '%iodine%'

But this returns rows that contain text strings that I do not want.

Body:
You must replace both terms and commas with empty strings, then trim the result and check if the length is 0:

SELECT med_code, med_name
FROM med_table
WHERE
  length(trim(
    regexp_replace(regexp_replace(regexp_replace(lower(med_name), 'calcium phosphate', ''), 'iodine', ''), ',', '')
  )) = 0

See the demo (for MySql the difference is the use of replace instead of Hive's regexp_replace).

Results:

| med_code | med_name                 |
| -------- | ------------------------ |
| 5        | iodine calcium phosphate |
| 6        | calcium phosphate        |
| 7        | IODINE                   |
| 8        | calcium PHOSPHATE iodine |


问:
How to create mac application, which will be always running in the background and collects Location?
I need to know how to create an application which will always be running in the background and collects location info once every 10 minutes. I don't know much about launch agents and daemons.

I have read a few examples where I found Launch agents is just a plist file. Should we launch the app through launch agents every 10 minutes? How to do that?

答:
There's no simple answer to this; you really need to read—or at least familiarize yourself with—the Daemons and Services Programming Guide, particularly the "Creating Login Items" section.

If you plan on creating a sandboxed (App Store) application, that limits your options somewhat, but not dramatically (for this kind of application).

You need to decide if your background process needs a UI or not. I suspect not, so I'd direct you to the either the XPC Service or user agent route. These will be registered with launchd and launchd has about a billion different options for how and when your process gets launched, and one of those is periodically. For more info on those, see man launchd.plist, particularly StartInterval and StartCalendarInterval.

With this knowledge, I'd then suggest to do some internet and open source searches looking for examples. I'm sure you'll find plenty.


问:
LiteDB: Invalid BSON data type 'Null' on field '_id'
Using LiteDB, and it is amazing. It works well for loading and storing data, however, not on subsequent loads after the database has been created.

On initial load, everything is perfect. It creates the database and stores the new record flawlessly, and query returns empty since nothing exists in that collection yet.

On subsequent load, after querying the data (works and gets the result), there is a problem in the .Update() which is causing this issue. According to their documentation, when an 'Id' is not specified it is supposed to create one. When the object is returned from the collection, it does not contain this '_Id' field, and thus fails to update the record in the database.

```<code>public class AuctionCache
{
    public double lastModified { get; set; }
    public string server { get; set; }
    public AuctionCache() { }
}

private static bool IsCached(AuctionCache auction)
{
    string filename = string.Format("{0}-{1}.json", auction.server, auction.lastModified);
    bool cached = false;
    try
    {
        using (LiteDatabase db = new LiteDatabase("cache.db"))
        {
            // Get customer collection
            var auctions = db.GetCollection<AuctionCache>("auctions");

            // Use Linq to query documents
            try
            {
                var results = auctions.Find(x => x.server == auction.server).DefaultIfEmpty(null).Single();
                if (results == null)
                {
                    // Insert new cached server
                    auctions.Insert(auction);
                    auctions.EnsureIndex(x => x.server);
                }
                else
                {
                    if (results.lastModified < auction.lastModified)
                    {
                        // Update existing cached server data
                        results.lastModified = auction.lastModified;
                        auctions.Update(results);
                        auctions.EnsureIndex(x => x.server);
                    }
                    else
                    {
                        cached = File.Exists(filename);
                    }
                }
            }
            catch (LiteException le1) {
                Log.Output(le1.Message);
                // Get stack trace for the exception with source file information
                var st = new StackTrace(le1, true);
                // Get the top stack frame
                var frame = st.GetFrame(0);
                // Get the line number from the stack frame
                var line = frame.GetFileLineNumber();
                var module = frame.GetMethod();
                var file = frame.GetFileName();
            }
            catch (Exception e)
            {
                Log.Output(e.Message);
                // Get stack trace for the exception with source file information
                var st = new StackTrace(e, true);
                // Get the top stack frame
                var frame = st.GetFrame(0);
                // Get the line number from the stack frame
                var line = frame.GetFileLineNumber();
            }
        }
    } catch (Exception ee) {
        Log.Output(ee.Message);
        // Get stack trace for the exception with source file information
        var st = new StackTrace(ee, true);
        // Get the top stack frame
        var frame = st.GetFrame(0);
        // Get the line number from the stack frame
        var line = frame.GetFileLineNumber();
    }
    return cached;
}
</code>```

If you wish to use the above code quickly, you can use the following for demonstration purposes (initial load) :

```<code>   AuctionCache ac = new AuctionCache();
   ac.lastModified = (double)12345679;
   ac.server = "Foo";

   // should return true on subsequent loads.
   Console.WriteLine( IsCached( ac ) );
</code>```

Make sure when testing to stop the program after initial creation, and then start the program 'fresh' for a clean test of loading / updating the database using the following code :

```<code>   AuctionCache ac = new AuctionCache();
   ac.lastModified = (double)22345679;
   ac.server = "Foo";

   // should return true on subsequent loads.
   Console.WriteLine( IsCached( ac ) );
</code>```

This should ensure that it will try to update the record and flag the problem in your IDE as lastModified is newer than the one stored in cache.db which will trigger the .Update method inside my IsCached method.

答:
I agree with @mbdavid's answer. However, when it's for a type you don't own, like something you're using from a 3rd-party assembly, you'll like need to use the BsonMapper:

```<code>BsonMapper.Global.Entity<IdentityServer4.Models.IdentityResources.OpenId>()
    .Id(oid => oid.Name);
</code>```

Put this somewhere in your startup code.

Body:
Using LiteDB, and it is amazing. It works well for loading and storing data, however, not on subsequent loads after the database has been created.

On initial load, everything is perfect. It creates the database and stores the new record flawlessly, and query returns empty since nothing exists in that collection yet.

On subsequent load, after querying the data (works and gets the result), there is a problem in the .Update() which is causing this issue. According to their documentation, when an 'Id' is not specified it is supposed to create one. When the object is returned from the collection, it does not contain this '_Id' field, and thus fails to update the record in the database.

public class AuctionCache
{
    public double lastModified { get; set; }
    public string server { get; set; }
    public AuctionCache() { }
}

private static bool IsCached(AuctionCache auction)
{
    string filename = string.Format("{0}-{1}.json", auction.server, auction.lastModified);
    bool cached = false;
    try
    {
        using (LiteDatabase db = new LiteDatabase("cache.db"))
        {
            // Get customer collection
            var auctions = db.GetCollection<AuctionCache>("auctions");

            // Use Linq to query documents
            try
            {
                var results = auctions.Find(x => x.server == auction.server).DefaultIfEmpty(null).Single();
                if (results == null)
                {
                    // Insert new cached server
                    auctions.Insert(auction);
                    auctions.EnsureIndex(x => x.server);
                }
                else
                {
                    if (results.lastModified < auction.lastModified)
                    {
                        // Update existing cached server data
                        results.lastModified = auction.lastModified;
                        auctions.Update(results);
                        auctions.EnsureIndex(x => x.server);
                    }
                    else
                    {
                        cached = File.Exists(filename);
                    }
                }
            }
            catch (LiteException le1) {
                Log.Output(le1.Message);
                // Get stack trace for the exception with source file information
                var st = new StackTrace(le1, true);
                // Get the top stack frame
                var frame = st.GetFrame(0);
                // Get the line number from the stack frame
                var line = frame.GetFileLineNumber();
                var module = frame.GetMethod();
                var file = frame.GetFileName();
            }
            catch (Exception e)
            {
                Log.Output(e.Message);
                // Get stack trace for the exception with source file information
                var st = new StackTrace(e, true);
                // Get the top stack frame
                var frame = st.GetFrame(0);
                // Get the line number from the stack frame
                var line = frame.GetFileLineNumber();
            }
        }
    } catch (Exception ee) {
        Log.Output(ee.Message);
        // Get stack trace for the exception with source file information
        var st = new StackTrace(ee, true);
        // Get the top stack frame
        var frame = st.GetFrame(0);
        // Get the line number from the stack frame
        var line = frame.GetFileLineNumber();
    }
    return cached;
}

If you wish to use the above code quickly, you can use the following for demonstration purposes (initial load) :

   AuctionCache ac = new AuctionCache();
   ac.lastModified = (double)12345679;
   ac.server = "Foo";

   // should return true on subsequent loads.
   Console.WriteLine( IsCached( ac ) );

Make sure when testing to stop the program after initial creation, and then start the program 'fresh' for a clean test of loading / updating the database using the following code :

   AuctionCache ac = new AuctionCache();
   ac.lastModified = (double)22345679;
   ac.server = "Foo";

   // should return true on subsequent loads.
   Console.WriteLine( IsCached( ac ) );

This should ensure that it will try to update the record and flag the problem in your IDE as lastModified is newer than the one stored in cache.db which will trigger the .Update method inside my IsCached method.

Body:
I agree with @mbdavid's answer. However, when it's for a type you don't own, like something you're using from a 3rd-party assembly, you'll like need to use the BsonMapper:

BsonMapper.Global.Entity<IdentityServer4.Models.IdentityResources.OpenId>()
    .Id(oid => oid.Name);

Put this somewhere in your startup code.


问:
Connecting Instagram with facebook gives error_type OauthException
I tried to connect my instagram profile via my facebook page in the settings area. When I try to log in to my account in the popup window this is what it says:

{"error_type": "OAuthException", "code": 400, "error_message": "Session invalid"}

Also when I try to connect my facebook in the Instagram app on my phone it won't connect just for 1 - 5 seconds.

答: I was having the same problem. I solved it by disabling my AdBlock and Pop Up blocker in both</p>


问:
Setting Up Rows in Tables
I'm trying to set up custom notifications for order confirmations and am struggling to find in the documentation how to make sure that each line in a data table row is related to that row.  It that what the order line data fields are versus the just regular sales order data fields?

I'm using MJML to create the more stylized customer facing notifications.

I've looked far and wide through the documentation, googles and blog posts.

```<code><mjml>

  <mj-head>

    <mj-style>
        @media all and (max-width: 599px) {
      .container600 {
        width: 100% !important;
      }

      .smarttable {
        border: 0;
      }
      .smarttable thead {
        display:none;
        border: none;
        clip: rect(0 0 0 0);
        height: 0px;
        margin: 0px;
        overflow: hidden;
        padding: 0;
        max-width:0px;
        max-height:0px;
      }
      .smarttable tr {
        display: block;
        width:90%;
        margin:20px auto;
      }
      .smarttable td {
        border-bottom: 1px solid #000;
        display: block;
        font-size: 14px;
        text-align: right;
      }
      .smarttable td:before {
        content: attr(data-label);
        float: left;
        font-weight: bold;
        text-transform: uppercase;
      }
    }
    </mj-style>
       <mj-attributes>
               <mj-text align="left" font-family="sans-serif" color="#000" font-size="14px" line-height="23px" />

      <mj-section background-color="#fff" padding="0px" />
    </mj-attributes>

  </mj-head>

  <mj-body background-color="#ededed">

    <mj-section>
   <mj-column>
        <mj-image width="300px" align="center" src="http://go.pardot.com/l/45492/2019-04-05/72zfh7/45492/214936/splitheader_01.jpg" />
      </mj-column>

         <mj-column>
        <mj-image width="300px" align="center" src="http://go.pardot.com/l/45492/2019-04-05/72zfh9/45492/214938/splitheader_02.jpg" />
      </mj-column>
  </mj-section>
        <mj-section>
      <mj-column>

          <mj-text>
        John Smith,<br></br>
            Your order <a href="google.com" target="_blank" style="color:#429df1">#((Document.OrderNbr))</a> contains one or more backordered items. Most backorders are filled and shipped out within five business days. We apologize for the inconvenience.
        </mj-text>
               </mj-column>
              </mj-section>

                <mj-section> <mj-column>
        <mj-button font-family="Helvetica" background-color="#f45e43" color="white" align="left" padding="0px 25px" href="">
          VIEW ORDER DETAILS
         </mj-button>
                  </mj-column>
          </mj-section>

           <mj-section><mj-column>
           <mj-spacer height="15px" />
           </mj-column>
           </mj-section>

<mj-section> <mj-column>
  <mj-text><h1 style="color:#fff;font-size:18px;background-color:#033047; padding:5px">BACKORDER NOTIFICATION</h1></mj-text>
  </mj-column></mj-section>

          <!-- First column -->
          <mj-section> <mj-column>
              <mj-text><h2 style="color:#033047;font-size:16px;">ORDER DETAILS</h2></mj-text>
           <mj-text>Customer #:  ((Document.CustomerOrderNbr))<br>
             Order #:  <a href="google.com" target="_blank" style="color:#429df1">((Document.OrderNbr))</a><br>
             Purchase Order #:  ((Document.InvoiceNbr))<br>
             Order Date:  ((Document.OrderDate))</br>
             Shipping Method:  ((Document.ShipVia.CarrierID))<br>
             Estimated Shipping Date:  ((Document.ShipDate))</br>
            </mj-text></mj-column>
            </mj-section>

<mj-section>

<mj-column>
      <mj-divider border-width="1px" border-style="solid" border-color="black" />
<mj-text>
<table width="100%" cellpadding="0" cellspacing="0" style="min-width:100%;">

<tr>
<td style="padding:5px;">
<table class="smarttable" width="100%" cellpadding="0" cellspacing="0" style="min-width:100%;"><thead>
                    <tr><th scope="col" style="padding:5px; font-family: Arial,sans-serif; font-size: 14px; line-height:10px;line-height:15px;color:#033047;text-align:left;background-color:#ededed">ITEM</th>
                      <th scope="col" style="padding:5px; font-family: Arial,sans-serif; font-size: 14px; line-height:10px;line-height:15px;color:#033047;text-align:left;background-color:#ededed">SKU</th>
                      <th scope="col" style="padding:5px; font-family: Arial,sans-serif; font-size: 14px; line-height:10px;line-height:15px;color:#033047;text-align:left;background-color:#ededed">QTY</th>

  <th scope="col" style="padding:5px; font-family: Arial,sans-serif; font-size: 14px; line-height:10px;line-height:15px;color:#033047;text-align:left;background-color:#ededed">PRICE EACH</th>

                        <th scope="col" style="padding:5px; font-family: Arial,sans-serif; font-size: 14px; line-height:10px;line-height:15px;color:#033047;text-align:left;background-color:#ededed">ITEM TOTAL</th>

</tr>
</thead>
<tbody>

  <tr><td data-label="ITEM" valign="top" style="padding:5px; font-family: Arial,sans-serif; font-size: 12px; line-height:20px;">((Document.OrderDesc))</td>

                      <td data-label="SKU" valign="top" style="padding:5px; font-family: Arial,sans-serif; font-size: 12px; line-height:20px;">((Transactions.InventoryID.InventoryCD))</td>

                      <td data-label="QTY" valign="top" style="padding:5px; font-family: Arial,sans-serif; font-size: 12px; line-height:20px;">((Transactions.OrderQty))</td>

<td data-label="PRICE EACH" valign="top" style="padding:5px; font-family: Arial,sans-serif; font-size: 12px; line-height:20px;">((Transactions.CuryUnitPrice))</td>

  <td data-label="ITEM TOTAL" valign="top" style="padding:5px; font-family: Arial,sans-serif; font-size: 12px; line-height:20px;">((Transactions.CuryExtPrice))</td>
  </tr></tbody></table></td></tr></table>

</mj-text>
  <mj-divider border-width="1px" border-style="solid" border-color="black" />
</mj-column>
</mj-section>

        <mj-section>
      <mj-column>
      <mj-text>
        <h3 style="color:#033047;font-size:20px; padding-top:25px">SUPPORT & ASSISTANCE</h3></mj-text>

    <mj-text>Feel free to contact us if you need further asisstance.<br></br>
      Phone: 1-888-637-3898<br>
      Email: <a href="mailto:info@graphicproducts.com" target="_blank" style="color:#429df1">info@graphicproducts.com</a></br>
      Website: <a href="GraphicProducts.com" target="_blank" style="color:#429df1">GraphicProducts.com</a><br></br>
        </mj-text>
        </mj-column></mj-section>

  <mj-text align="center"><br>Copyright © 2019, All rights reserved.<br>
    Graphic Products, Inc., 9825 SW Sunshine Ct. Beaverton, OR 97005, United States
    <br>
    View our <a href="https://www.graphicproducts.com/privacy/" target="_blank" style="color:#000">privacy policy</a>
        </mj-text>

</mj-body>
</mjml>
</code>```

I just need to ensure that rows are related when applicable, and item having the description next to it and then having the total relate to the overall table total.

答:
No one ever got back to me on this but I eventually found a solution and wanted to post it here so that if anyone else ever runs into this they can use it.

The data tables have a special code that needs to go around them that makes the table loop and pull info into it.

See article here: https://asiablog.acumatica.com/2018/07/loops-in-notification-templates.html

Title: Setting Up Rows in Tables

Body:
I'm trying to set up custom notifications for order confirmations and am struggling to find in the documentation how to make sure that each line in a data table row is related to that row.  It that what the order line data fields are versus the just regular sales order data fields?

I'm using MJML to create the more stylized customer facing notifications.

I've looked far and wide through the documentation, googles and blog posts.

<mjml>

  <mj-head>

    <mj-style>
        @media all and (max-width: 599px) {
      .container600 {
        width: 100% !important;
      }

      .smarttable {
        border: 0;
      }
      .smarttable thead {
        display:none;
        border: none;
        clip: rect(0 0 0 0);
        height: 0px;
        margin: 0px;
        overflow: hidden;
        padding: 0;
        max-width:0px;
        max-height:0px;
      }
      .smarttable tr {
        display: block;
        width:90%;
        margin:20px auto;
      }
      .smarttable td {
        border-bottom: 1px solid #000;
        display: block;
        font-size: 14px;
        text-align: right;
      }
      .smarttable td:before {
        content: attr(data-label);
        float: left;
        font-weight: bold;
        text-transform: uppercase;
      }
    }
    </mj-style>
       <mj-attributes>
               <mj-text align="left" font-family="sans-serif" color="#000" font-size="14px" line-height="23px" />

      <mj-section background-color="#fff" padding="0px" />
    </mj-attributes>

  </mj-head>

  <mj-body background-color="#ededed">

    <mj-section>
   <mj-column>
        <mj-image width="300px" align="center" src="http://go.pardot.com/l/45492/2019-04-05/72zfh7/45492/214936/splitheader_01.jpg" />
      </mj-column>

         <mj-column>
        <mj-image width="300px" align="center" src="http://go.pardot.com/l/45492/2019-04-05/72zfh9/45492/214938/splitheader_02.jpg" />
      </mj-column>
  </mj-section>
        <mj-section>
      <mj-column>

          <mj-text>
        John Smith,

            Your order #((Document.OrderNbr)) contains one or more backordered items. Most backorders are filled and shipped out within five business days. We apologize for the inconvenience.
        </mj-text>
               </mj-column>
              </mj-section>

                <mj-section> <mj-column>
        <mj-button font-family="Helvetica" background-color="#f45e43" color="white" align="left" padding="0px 25px" href="">
          VIEW ORDER DETAILS
         </mj-button>
                  </mj-column>
          </mj-section>

           <mj-section><mj-column>
           <mj-spacer height="15px" />
           </mj-column>
           </mj-section>

<mj-section> <mj-column>
  <mj-text>
BACKORDER NOTIFICATION
</mj-text>
  </mj-column></mj-section>

          <mj-section> <mj-column>
              <mj-text>
ORDER DETAILS
</mj-text>
           <mj-text>Customer #:  ((Document.CustomerOrderNbr))

             Order #:  ((Document.OrderNbr))

             Purchase Order #:  ((Document.InvoiceNbr))

             Order Date:  ((Document.OrderDate))

             Shipping Method:  ((Document.ShipVia.CarrierID))

             Estimated Shipping Date:  ((Document.ShipDate))

            </mj-text></mj-column>
            </mj-section>

<mj-section>

<mj-column>
      <mj-divider border-width="1px" border-style="solid" border-color="black" />
<mj-text>

ITEM
                      SKU
                      QTY

  PRICE EACH

                        ITEM TOTAL

((Document.OrderDesc))

                      ((Transactions.InventoryID.InventoryCD))

                      ((Transactions.OrderQty))

((Transactions.CuryUnitPrice))

  ((Transactions.CuryExtPrice))

</mj-text>
  <mj-divider border-width="1px" border-style="solid" border-color="black" />
</mj-column>
</mj-section>

        <mj-section>
      <mj-column>
      <mj-text>

SUPPORT & ASSISTANCE
</mj-text>

    <mj-text>Feel free to contact us if you need further asisstance.

      Phone: 1-888-637-3898

      Email: info@graphicproducts.com

      Website: GraphicProducts.com

        </mj-text>
        </mj-column></mj-section>

  <mj-text align="center">
Copyright © 2019, All rights reserved.

    Graphic Products, Inc., 9825 SW Sunshine Ct. Beaverton, OR 97005, United States

    View our privacy policy
        </mj-text>

</mj-body>
</mjml>

I just need to ensure that rows are related when applicable, and item having the description next to it and then having the total relate to the overall table total.


问:
Why does the compiler prevent me from using push on a Vec created using collect()?
The following compiles:

```<code>pub fn build_proverb(list: &[&str]) -> String {
    if list.is_empty() {
        return String::new();
    }
    let mut result = (0..list.len() - 1)
        .map(|i| format!("For want of a {} the {} was lost.", list[i], list[i + 1]))
        .collect::<Vec<String>>();
    result.push(format!("And all for the want of a {}.", list[0]));
    result.join("\n")
}
</code>```

The following does not (see Playground):

```<code>pub fn build_proverb(list: &[&str]) -> String {
    if list.is_empty() {
        return String::new();
    }
    let mut result = (0..list.len() - 1)
        .map(|i| format!("For want of a {} the {} was lost.", list[i], list[i + 1]))
        .collect::<Vec<String>>()
        .push(format!("And all for the want of a {}.", list[0]))
        .join("\n");
    result
}
</code>```

The compiler tells me

error[E0599]: no method named `join` found for type `()` in the current scope
 --> src/lib.rs:9:10
  |
9 |         .join("\n");
  |          ^^^^
```

I get the same type of error if I try to compose just with push.

What I would expect is that collect returns B, aka Vec<String>.  Vec is not (), and Vec of course has the methods I want to include in the list of composed functions.

Why can't I compose these functions? The explanation might include describing the "magic" of terminating the expression after collect() to get the compiler to instantiate the Vec in a way that does not happen when I compose with push etc.

答:
Thank you to everyone for the useful interactions. Everything stated in the previous response is precisely correct. And, there is a bigger picture as I'm learning Rust.

Coming from Haskell (with C training years ago), I bumped into the OO method chaining approach that uses a pointer to chain between method calls; no need for pure functions (i.e., what I was doing with let mut result = ..., which was then used/required to change the value of the Vec using push in result.push(...)). What I believe is a more general observation is that, in OO, it is "aok" to return unit because method chaining does not require a return value.

The custom code below defines push as a trait; it uses the same inputs as the "OO" push, but returns the updated self.  Perhaps only as a side comment, this makes the function pure (output depends on input) but in practice, means the push defined as a trait enables the FP composition of functions I had come to expect was a norm (fair enough I thought at first given how much Rust borrows from Haskell).

What I was trying to accomplish, and at the heart of the question, is captured by the code solution that @Stargateur, @E_net4 and @Shepmaster put forward.  With only the smallest edits is as follows:
(see playground)

```<code>pub fn build_proverb(list: &[&str]) -> String {
    if list.is_empty() {
        return String::new();
    }
    list.windows(2)
        .map(|d| format!("For want of a {} the {} was lost.", d[0], d[1]))
        .collect::<Vec<_>>()
        .push(format!("And all for the want of a {}.", list[0]))
        .join("\n")
}
</code>```

The solution requires that I define push as a trait that return the self,
type Vec in this instance.

```<code>trait MyPush<T> {
    fn push(self, x: T) -> Vec<T>;
}

impl<T> MyPush<T> for Vec<T> {
    fn push(mut self, x: T) -> Vec<T> {
        Vec::push(&mut self, x);
        self
    }
}
</code>```

Final observation, in surveying many of the Rust traits, I could not find a trait function that returns () (modulo e.g., Write that returns Result ()).

This contrasts with what I learned here to expect with struct and enum methods.  Both traits and the OO methods have access to self and thus have each been described as "methods", but there seems to be an inherent difference worth noting: OO methods use a reference to enable sequentially changing self, FP traits (if you will) uses function composition that relies on the use of "pure", state-changing functions to accomplish the same (:: (self, newValue) -> self).

Perhaps as an aside, where Haskell achieves referential transparency in this situation by creating a new copy (modulo behind the scenes optimizations), Rust seems to accomplish something similar in the custom trait code by managing ownership (transferred to the trait function, and handed back by returning self).

A final piece to the "composing functions" puzzle: For composition to work, the output of one function needs to have the type required for the input of the next function.  join worked both when I was passing it a value, and when I was passing it a reference (true with types that implement IntoIterator).  So join seems to have the capacity to work in both the method chaining and function composition styles of programming.

Is this distinction between OO methods that don't rely on a return value and traits generally true in Rust? It seems to be the case "here and there". Case in point, in contrast to push where the line is clear, join seems to be on its way to being part of the standard library defined as both a method for SliceConcatExt and a trait function for SliceConcatExt (see rust src and the rust-lang issue discussion). The next question, would unifying the approaches in the standard library be consistent with the Rust design philosophy? (pay only for what you use, safe, performant, expressive and a joy to use)

Body:
The following compiles:

pub fn build_proverb(list: &[&str]) -> String {
    if list.is_empty() {
        return String::new();
    }
    let mut result = (0..list.len() - 1)
        .map(|i| format!("For want of a {} the {} was lost.", list[i], list[i + 1]))
        .collect::<Vec<String>>();
    result.push(format!("And all for the want of a {}.", list[0]));
    result.join("\n")
}

The following does not (see Playground):

pub fn build_proverb(list: &[&str]) -> String {
    if list.is_empty() {
        return String::new();
    }
    let mut result = (0..list.len() - 1)
        .map(|i| format!("For want of a {} the {} was lost.", list[i], list[i + 1]))
        .collect::<Vec<String>>()
        .push(format!("And all for the want of a {}.", list[0]))
        .join("\n");
    result
}

The compiler tells me

error[E0599]: no method named `join` found for type `()` in the current scope
 --> src/lib.rs:9:10
  |
9 |         .join("\n");
  |          ^^^^

I get the same type of error if I try to compose just with push.

What I would expect is that collect returns B, aka Vec<String>.  Vec is not (), and Vec of course has the methods I want to include in the list of composed functions.

Why can't I compose these functions? The explanation might include describing the "magic" of terminating the expression after collect() to get the compiler to instantiate the Vec in a way that does not happen when I compose with push etc.

Body:
Thank you to everyone for the useful interactions. Everything stated in the previous response is precisely correct. And, there is a bigger picture as I'm learning Rust.

Coming from Haskell (with C training years ago), I bumped into the OO method chaining approach that uses a pointer to chain between method calls; no need for pure functions (i.e., what I was doing with let mut result = ..., which was then used/required to change the value of the Vec using push in result.push(...)). What I believe is a more general observation is that, in OO, it is "aok" to return unit because method chaining does not require a return value.

The custom code below defines push as a trait; it uses the same inputs as the "OO" push, but returns the updated self.  Perhaps only as a side comment, this makes the function pure (output depends on input) but in practice, means the push defined as a trait enables the FP composition of functions I had come to expect was a norm (fair enough I thought at first given how much Rust borrows from Haskell).

What I was trying to accomplish, and at the heart of the question, is captured by the code solution that @Stargateur, @E_net4 and @Shepmaster put forward.  With only the smallest edits is as follows:
(see playground)

pub fn build_proverb(list: &[&str]) -> String {
    if list.is_empty() {
        return String::new();
    }
    list.windows(2)
        .map(|d| format!("For want of a {} the {} was lost.", d[0], d[1]))
        .collect::<Vec<_>>()
        .push(format!("And all for the want of a {}.", list[0]))
        .join("\n")
}

The solution requires that I define push as a trait that return the self,
type Vec in this instance.

trait MyPush<T> {
    fn push(self, x: T) -> Vec<T>;
}

impl<T> MyPush<T> for Vec<T> {
    fn push(mut self, x: T) -> Vec<T> {
        Vec::push(&mut self, x);
        self
    }
}

Final observation, in surveying many of the Rust traits, I could not find a trait function that returns () (modulo e.g., Write that returns Result ()).

This contrasts with what I learned here to expect with struct and enum methods.  Both traits and the OO methods have access to self and thus have each been described as "methods", but there seems to be an inherent difference worth noting: OO methods use a reference to enable sequentially changing self, FP traits (if you will) uses function composition that relies on the use of "pure", state-changing functions to accomplish the same (:: (self, newValue) -> self).

Perhaps as an aside, where Haskell achieves referential transparency in this situation by creating a new copy (modulo behind the scenes optimizations), Rust seems to accomplish something similar in the custom trait code by managing ownership (transferred to the trait function, and handed back by returning self).

A final piece to the "composing functions" puzzle: For composition to work, the output of one function needs to have the type required for the input of the next function.  join worked both when I was passing it a value, and when I was passing it a reference (true with types that implement IntoIterator).  So join seems to have the capacity to work in both the method chaining and function composition styles of programming.

Is this distinction between OO methods that don't rely on a return value and traits generally true in Rust? It seems to be the case "here and there". Case in point, in contrast to push where the line is clear, join seems to be on its way to being part of the standard library defined as both a method for SliceConcatExt and a trait function for SliceConcatExt (see rust src and the rust-lang issue discussion). The next question, would unifying the approaches in the standard library be consistent with the Rust design philosophy? (pay only for what you use, safe, performant, expressive and a joy to use)


问:
How to trigger a late import of another module only when a certain object is needed from my module?

The Situation

I want to have a module that roughly works like the following:

```<code># my_module.py

my_number = 17

from other_module import foo
my_object = foo(23)
</code>```

However, there is a problem: Installing other_module causes problems for some users and is only required for those who want to use my_object – which in turn is only a small fraction of users. I want to spare those users who do not need my_object from installing other_module.

I therefore want the import of other_module to happen only if my_object is imported from my_module. With other words, the user should be able to run the following without having installed other_module:

```<code>from my_module import my_number
</code>```

My best solution so far

I could provide my_object via a function that contains the import:

```<code># in my_module.py

def get_my_object():
    from other_module import foo
    my_object = foo(23)
    return my_object
</code>```

The user would then have to do something like:

```<code>from my_module import get_my_object
my_object = get_my_object()
</code>```

Question

Is there a better way to conditionally trigger the import of other_module? I am mostly interested in keeping things as simple as possible for the users.

答:
I would prefer the get_my_object() approach, but as of Python 3.7, what you ask is possible by defining a module-level __getattr__ function:

```<code># my_module.py

my_number = 17

def __getattr__(name):
    if name != 'my_object':
        raise AttributeError
    global my_object
    from other_module import foo
    my_object = foo(23)
    return my_object
</code>```

This will attempt to import other_module and call foo only once my_object is accessed. A few caveats:

It will not trigger for attempts to access my_object by global variable lookup within my_module. It will only trigger on my_module.my_object attribute access, or a from my_module import my_object import (which performs attribute access under the hood).

If you forget to assign to the global my_object name in __getattr__, my_object will be recomputed on every access.

Module-level __getattr__ does nothing before Python 3.7, so you may want to perform a version check and do something else for Python 3.6 and below:

```<code>import sys
if sys.version_info >= (3, 7):
    def __getattr__(name):
        ...
else:
    # Do something appropriate. Maybe raise an error. Maybe unconditionally
    # import other_module and compute my_object up front.
</code>```

Body:
The Situation

I want to have a module that roughly works like the following:

# my_module.py

my_number = 17

from other_module import foo
my_object = foo(23)

However, there is a problem: Installing other_module causes problems for some users and is only required for those who want to use my_object – which in turn is only a small fraction of users. I want to spare those users who do not need my_object from installing other_module.

I therefore want the import of other_module to happen only if my_object is imported from my_module. With other words, the user should be able to run the following without having installed other_module:

from my_module import my_number

My best solution so far

I could provide my_object via a function that contains the import:

# in my_module.py

def get_my_object():
    from other_module import foo
    my_object = foo(23)
    return my_object

The user would then have to do something like:

from my_module import get_my_object
my_object = get_my_object()

Question

Is there a better way to conditionally trigger the import of other_module? I am mostly interested in keeping things as simple as possible for the users.

Body:
I would prefer the get_my_object() approach, but as of Python 3.7, what you ask is possible by defining a module-level __getattr__ function:

# my_module.py

my_number = 17

def __getattr__(name):
    if name != 'my_object':
        raise AttributeError
    global my_object
    from other_module import foo
    my_object = foo(23)
    return my_object

This will attempt to import other_module and call foo only once my_object is accessed. A few caveats:

It will not trigger for attempts to access my_object by global variable lookup within my_module. It will only trigger on my_module.my_object attribute access, or a from my_module import my_object import (which performs attribute access under the hood).

If you forget to assign to the global my_object name in __getattr__, my_object will be recomputed on every access.

Module-level __getattr__ does nothing before Python 3.7, so you may want to perform a version check and do something else for Python 3.6 and below:

import sys
if sys.version_info >= (3, 7):
    def __getattr__(name):
        ...
else:
    # Do something appropriate. Maybe raise an error. Maybe unconditionally
    # import other_module and compute my_object up front.


问:
How to access a java class variable value (dynamic) from one class to another class?
My requirement is, I wanted to read some data in one page and verify that data with another page data, to make sure that both data's present in two different pages are the same.
I'm using selenium and Java

Note: All the data's I'm reading at run time from the UI.

```<code>Class User{

String userText;

public User(){}

public void getUserName(){

// Here i'm reading the text from the user page
userText = driver.findElement(By.xpath("some xpath")).getText();
}

}

Class Admin{

public adminText;

// Here i'm reading the text from the admin page

public void getAdminUserName(){
adminText = driver.findElement(By.xpath("some xpath")).getText();
}

// Now I wanted to use, User class variable value userText in the admin class. So that I can assert both the data's (User and Admin).

User obj = new User();

assertEquals(obj.userText, adminText); // Asertion failed.

}
}
</code>```

But If I create an object for User class, the userText variable is assigned to null. So my assertion is getting failed.

Can anyone please let me know, how I can I access the value of one class to another class?
I know we can use static, but I felt that is a bad practice to do that here.

答:
You weren't calling the methods, creating the admin object, or defining adminText as String.

```<code>Class User{

String userText;

public User(){}

public void getUserName(){

// Here i'm reading the text from the user page
userText = driver.findElement(By.xpath("some xpath")).getText();
}

}

Class Admin{

String adminText;

// Here i'm reading the text from the admin page

public void getAdminUserName(){
adminText = driver.findElement(By.xpath("some xpath")).getText();
}

// Now I wanted to use, User class variable value userText in the admin class. So that I can assert both the data's (User and Admin).

}

User obj = new User();
obj.getUserName();

Admin adminObj = new Admin();
adminObj.getAdminUserName();

assertEquals(obj.userText, adminObj.adminText); // Asertion failed.
</code>```

Not a complete answer, because you'd still need to navigate to the other page. driver.get(page_1), driver.get(page_2)

Body:
My requirement is, I wanted to read some data in one page and verify that data with another page data, to make sure that both data's present in two different pages are the same.
I'm using selenium and Java

Note: All the data's I'm reading at run time from the UI.

Class User{

String userText;

public User(){}

public void getUserName(){

// Here i'm reading the text from the user page
userText = driver.findElement(By.xpath("some xpath")).getText();
}

}

Class Admin{

public adminText;

// Here i'm reading the text from the admin page

public void getAdminUserName(){
adminText = driver.findElement(By.xpath("some xpath")).getText();
}

// Now I wanted to use, User class variable value userText in the admin class. So that I can assert both the data's (User and Admin).

User obj = new User();

assertEquals(obj.userText, adminText); // Asertion failed.

}
}

But If I create an object for User class, the userText variable is assigned to null. So my assertion is getting failed.

Can anyone please let me know, how I can I access the value of one class to another class?
I know we can use static, but I felt that is a bad practice to do that here.

Body:
You weren't calling the methods, creating the admin object, or defining adminText as String.

Class User{

String userText;

public User(){}

public void getUserName(){

// Here i'm reading the text from the user page
userText = driver.findElement(By.xpath("some xpath")).getText();
}

}

Class Admin{

String adminText;

// Here i'm reading the text from the admin page

public void getAdminUserName(){
adminText = driver.findElement(By.xpath("some xpath")).getText();
}

// Now I wanted to use, User class variable value userText in the admin class. So that I can assert both the data's (User and Admin).

}

User obj = new User();
obj.getUserName();

Admin adminObj = new Admin();
adminObj.getAdminUserName();

assertEquals(obj.userText, adminObj.adminText); // Asertion failed.

Not a complete answer, because you'd still need to navigate to the other page. driver.get(page_1), driver.get(page_2)


问:
Merge array within array
I have an array containing a further 2 arrays of objects and I wanted to turn it into a single array of objects. I have posted the current code and result I want

I have tried the concat method but possibly implementing wrong?

```<code>var code = [
  [{Adults:"1", Price: "14.50"}],
  [{Adults:"1", Price: "20.50"}]
]

var result = [
  {Adults: "1", Price: "14.50" },
  {Adults: "1", Price: "20.50"}
]
</code>```

答:
You can use flat

var code = [
  [{Adults:"1", Price: "14.50"}],
  [{Adults:"1", Price: "20.50"}]
]

let op = code.flat()

console.log(op)```

Title: Merge array within array

Body:
I have an array containing a further 2 arrays of objects and I wanted to turn it into a single array of objects. I have posted the current code and result I want

I have tried the concat method but possibly implementing wrong?

var code = [
  [{Adults:"1", Price: "14.50"}],
  [{Adults:"1", Price: "20.50"}]
]

var result = [
  {Adults: "1", Price: "14.50" },
  {Adults: "1", Price: "20.50"}
]


问:
Azure Service Bus through Azure API Management
We are considering improving security management around our Azure Service Bus stack used a an Enterprise Service Bus.

Azure API management seems a pretty good candidate (and would allow plenty other usages in our ecosystem) but is there any cons behind ?

For example, service bus can connect with Http/Https/Tcp (https://learn.microsoft.com/en-us/dotnet/api/microsoft.servicebus.connectivitymode?view=azure-dotnet)

As far as I can tell, when possible, Tcp would provide better performance (?), but I suspect it won't be supported anymore if exposed with Azure API Management ?

Is there other limitations to expect ? as an example, 'older' (replaced) javascript library relied on SB REST API (https://www.npmjs.com/package/azure-sb) had some limitations such missing Defer / Abandon (https://github.com/Azure/azure-sdk-for-node/issues/2019)

答:
From APIM perspective:

You will have to use HTTP since that is the only protocol APIM supports.

APIM will introduce additional hop in your network, that will affect latency.

APIM does not maintain any connection affinity between client and backend, i.e. requests received from multiple clients over multiple connections may be sent to backend over single connection, and other way around.


问:
Spring Rest JSON Binding
I'm trying to create a Restful service with Spring.

A method accepts a "UserContext" object via argument i.e. @RequestBody.

The client sends the JSON object with content-type "application/json". But I get the error "HTTP/1.1 415 Unsupported Media Type".

..even when the client sends a null "{}" JSON object.

My controller:

```<code>@Controller
@RequestMapping(value = "/entityService")
class RestfulEntityService {

  @Resource
  private EntityService entityService;

  @ResponseBody
  @RequestMapping(value = "/getListOfEntities", method = RequestMethod.POST)
  public List<Entity> getListOfEntities(@RequestBody UserContext userContext) {
    System.out.println(userContext);
    return null;
  }
}
</code>```

UserContext.java

```<code>public class UserContext {

    private Long userId;

    private String userName;

    private UserAddress userAddress;

    private CustomerInfo customerInfo;

}
</code>```

Application context:

  <bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"/>
  <bean id="xmlMessageConverter"
        class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
    <constructor-arg ref="xstreamMarshaller"/>
    <property name="supportedMediaTypes" value="application/xml"/>
  </bean>

  <bean id="jsonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json"/>
  </bean>

  <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
      <util:list id="beanList">
        <ref bean="xmlMessageConverter" />
        <ref bean="jsonHttpMessageConverter"/>
      </util:list>
    </property>
  </bean>

  <mvc:annotation-driven/>
```

Struggling with this for a while. Help will be appreciated!

答:
This is probably not the main problem, but your UserContext bean would not work as is, if it only has private fields. There are multiple ways to resolve this; from making fields public, to adding @JsonProperty for each, or just changing minimum visibility jackson uses for detecting property fields (@JsonAutoDetect annotation).

But with empty JSON, this should not give problems; and if there was an issue, you should see different kind of error/exception (I assume).

Title: Spring Rest JSON Binding

Body:
I'm trying to create a Restful service with Spring.

A method accepts a "UserContext" object via argument i.e. @RequestBody.

The client sends the JSON object with content-type "application/json". But I get the error "HTTP/1.1 415 Unsupported Media Type".

..even when the client sends a null "{}" JSON object.

My controller:

@Controller
@RequestMapping(value = "/entityService")
class RestfulEntityService {

  @Resource
  private EntityService entityService;

  @ResponseBody
  @RequestMapping(value = "/getListOfEntities", method = RequestMethod.POST)
  public List<Entity> getListOfEntities(@RequestBody UserContext userContext) {
    System.out.println(userContext);
    return null;
  }
}

UserContext.java

public class UserContext {

    private Long userId;

    private String userName;

    private UserAddress userAddress;

    private CustomerInfo customerInfo;

}

Application context:

  <bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"/>
  <bean id="xmlMessageConverter"
        class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
    <constructor-arg ref="xstreamMarshaller"/>
    <property name="supportedMediaTypes" value="application/xml"/>
  </bean>

  <bean id="jsonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes" value="application/json"/>
  </bean>

  <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
      <util:list id="beanList">
        <ref bean="xmlMessageConverter" />
        <ref bean="jsonHttpMessageConverter"/>
      </util:list>
    </property>
  </bean>

  <mvc:annotation-driven/>

Struggling with this for a while. Help will be appreciated!