问:
UWP TextBox won't stretch in StackPanel
I have a TextBlock and TextBox controls inside StackPanel, and I need to stretch TextBox to resize by the parent size in UWP.

```<code><StackPanel Grid.Column="0" Grid.Row="1" Orientation="Horizontal">
    <TextBlock Text="Name:" VerticalAlignment="Center" Width="130" />
    <TextBox VerticalAlignment="Center" HorizontalAlignment="Stretch" />
</StackPanel>
</code>```

This not works.. Any ideas?

答:
I worked out a similar problem in UWP</p>

```<code>    <StackPanel Margin="{StaticResource SmallTopBottomMargin}" Orientation="Vertical">
        <TextBlock Text="Project Name:" />
        <TextBox />    <--full width
        <TextBlock Text="Exported Template:" /> <--full width
        <Grid HorizontalAlignment="Stretch">
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition Width="auto"/>
            </Grid.ColumnDefinitions>
            <TextBox />  <--max width - button width
            <Button Grid.Column="1">...</Button>
        </Grid>
</code>```

Title: UWP TextBox won't stretch in StackPanel

Body:
I have a TextBlock and TextBox controls inside StackPanel, and I need to stretch TextBox to resize by the parent size in UWP.

<StackPanel Grid.Column="0" Grid.Row="1" Orientation="Horizontal">
    <TextBlock Text="Name:" VerticalAlignment="Center" Width="130" />
    <TextBox VerticalAlignment="Center" HorizontalAlignment="Stretch" />
</StackPanel>

This not works.. Any ideas?

Body:
I worked out a similar problem in UWP

    <StackPanel Margin="{StaticResource SmallTopBottomMargin}" Orientation="Vertical">
        <TextBlock Text="Project Name:" />
        <TextBox />    <--full width
        <TextBlock Text="Exported Template:" /> <--full width
        <Grid HorizontalAlignment="Stretch">
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition Width="auto"/>
            </Grid.ColumnDefinitions>
            <TextBox />  <--max width - button width
            <Button Grid.Column="1">...</Button>
        </Grid>


来源: stackexchange

问:
Are GCP default firewall-rules a security-concern?
Whenever you create a project in GCP there is a default firewall-rule called: "default-allow-ssh", which allows 0.0.0.0/0 on port 22, which makes it easy to ssh into the machines with external ip from the browser. But that allows any machine from the internet to access my machine on port 22, and bots are constantly trying to access whatever they can find. I suppose they would still need to crack the password or ssh-key or something, but isn't that a very dangerous default setup rule? There are not really any warnings when you spin up a new machine with external-ip, and I was expecting GCP to have a more restricted approach.
If anyone can help me clarify this, it would be much appreciated.
And if I remove this default rule and still want to access my machines through ssh, which approach would be simple and secure?</p>

答:
Without this rule, when you try to SSH in using the gcloud command-line tool, the request would be immediately rejected, so AFAIK, the Compute Engine's choice here was optimized toward ease of getting started with GCE.

I also think that password authentication is disabled by default, so any attacker has two avenues of entry:

Crack an SSH private key

Exploit a vulnerability in the SSH agent binary

I think the first is pretty far fetched given today's technology. If this were sufficiently easy, we'd have much bigger problems in the world.

The second seems like something to worry about if you didn't have automatic security patches deployed by Google Cloud Platform on a regular basis. Yes, this is still vulnerable to 0-day exploits, but given that Google's security team were the ones who discovered several of the recent security vulnerabilities in popular projects (e.g., I'm pretty sure that Heartbleed was discovered, patched, and disclosed by Google), it's pretty likely that if there were a security bug in the SSH agent used by all of GCE VMs, Google would get it patched faster than anyone else would.

That said, if you really don't like this rule, I'm pretty sure you can go in and change the rule's definition so that it only allows some specific list of IPs or subnets by default for all of your VMs.

ContentLicense: CC BY-SA 4.0


问:
How to display Base64 images in HTML
I'm having trouble displaying a Base64 image inline.

How can I do it?

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Display Image</title>
  </head>
  <body>
    <img style='display:block; width:100px;height:100px;' id='base64image'
       src='data:image/jpeg;base64, LzlqLzRBQ... <!-- Base64 data -->' />
  </body>
</html>
</code>```

答:
Storing Base64-image as a variable and display it using plain HTML and JavaScript:

```<code><img id="image"/>

</code>```

Fiddle example, to try it directly.

Title: How to display Base64 images in HTML

Body:
I'm having trouble displaying a Base64 image inline.

How can I do it?

<!DOCTYPE html>

    <title>Display Image</title>

Body:
Storing Base64-image as a variable and display it using plain HTML and JavaScript:

<img id="image"/>
<script>
var ticket = {
            "validationDataValidDate": "2019-05-30",
            "validationImage": "[encoded data, 26492 characters]"
        };
document.querySelectorAll('[id="image"]')[0].src = 'data:image/png;base64, '+ticket["validationImage"];
</script>

Fiddle example, to try it directly.


问:
Creating an editable HTML table from 2D array
So I am trying to make a flashcards website, where users can add, edit, and delete flashcards. There are two cards - front and back. The user can already add words, but cannot edit or delete them. For the purposes of this question I will use an example array:

```<code>var flashcards = [["Uomo", "Man"],["Donna", "Woman"],["Ragazzo", "Boy"]]
</code>```

But I would like a more user-friendly way to edit the flashcards, preferably using a table like this:

```<code><table>
  <tr>
    <th>Front</th>
    <th>Back</th>
  </tr>
  <tr>
    <td><input type="text" name="flashcard" value="Uomo"> </td>
    <td><input type="text" name="flashcard" value="Man"></td>
  </tr>
    <tr>
    <td><input type="text" name="flashcard" value="Donna"></td>
    <td><input type="text" name="flashcard" value="Woman"></td>
  </tr>
      <tr>
    <td><input type="text" name="flashcard" value="Ragazzo"></td>
    <td><input type="text" name="flashcard" value="Boy"></td>
  </tr>
</table>

<button type="button">Add more</button>
<br>
<button type="button">Save changes</button>
</code>```

So they can update their flashcards editing the input fields, or clicking "add more" and it creating a new row. Clicking "save changes" updates the array to the content of the table.

I don't mind it not being a HTML table per se, but something that is easy to edit for the user.

I just cannot figure out the best way to approach this. Any advice?

答:
I already recommended VueJS - it really is a pretty good tool for this problem. Regardless, I have typed up a basic solution using vanilla JavaScript. For the editing part it uses the contenteditable HTML attribute which allows the end-user to double click an element and change it's textContent.
The html display is basic so you can change it however to fit your needs</p>

```<code><div id=style="width: 100%;">
  <ul id="table" style="list-style-type: none; display: inline-block;">

  </ul>
</div>
<script>
var flashcards = [["Uomo", "Man"],["Donna", "Woman"],["Ragazzo", "Boy"]];
var displayedCard = []; //Using a parallel array to keep track of which side is shown
for(var i = 0; i < flashcards.length; i++){
    displayedCard.push(0);
}
function renderFlashcardTable(){ //This will do the initial rendering of the table
    let ulTable = document.getElementById("table");
    for(var i = 0; i < flashcards.length; i++){
        let card = flashcards[i];
        let indexOfSideShown = displayedCard[i];
        let li = document.createElement("li");
        let cardValueSpan = document.createElement("span");
        cardValueSpan.innerHTML = card[indexOfSideShown]; //Get the value of the side of the card that is shown
        cardValueSpan.setAttribute("contenteditable", "true");
        cardValueSpan.oninput = function(e){ //This method gets called when the user de-selects the element they have been editing
            let li = this.parentElement;
            let sideIndex = parseInt(li.getAttribute("side-index"));
            card[sideIndex] = this.textContent;
        }
        li.appendChild(cardValueSpan);
        li.appendChild(getFlipSidesButton(li));
        li.setAttribute("side-index", indexOfSideShown);
        li.setAttribute("card-index", i);
        ulTable.appendChild(li);
    }
}
function getFlipSidesButton(listItem){//This is generated for each card and when clicked it "flips the switch"
    let btn = document.createElement("button");
    btn.innerHTML = "Flip card";
    btn.onclick = function(e){
        let card = flashcards[listItem.getAttribute("card-index")];
        let index = parseInt(listItem.getAttribute("side-index"));
        let nextSide = (index == 1) ? 0 : 1;
        listItem.setAttribute("side-index", nextSide);
        listItem.children[0].innerHTML = card[nextSide];
    }
    return btn;
}

renderFlashcardTable();
</script>
</code>```

Body:
So I am trying to make a flashcards website, where users can add, edit, and delete flashcards. There are two cards - front and back. The user can already add words, but cannot edit or delete them. For the purposes of this question I will use an example array:

var flashcards = [["Uomo", "Man"],["Donna", "Woman"],["Ragazzo", "Boy"]]

But I would like a more user-friendly way to edit the flashcards, preferably using a table like this:

    Front
    Back

    <input type="text" name="flashcard" value="Uomo">
    <input type="text" name="flashcard" value="Man">

    <input type="text" name="flashcard" value="Donna">
    <input type="text" name="flashcard" value="Woman">

    <input type="text" name="flashcard" value="Ragazzo">
    <input type="text" name="flashcard" value="Boy">

<button type="button">Add more</button>

<button type="button">Save changes</button>

So they can update their flashcards editing the input fields, or clicking "add more" and it creating a new row. Clicking "save changes" updates the array to the content of the table.

I don't mind it not being a HTML table per se, but something that is easy to edit for the user.

I just cannot figure out the best way to approach this. Any advice?

Body:
I already recommended VueJS - it really is a pretty good tool for this problem. Regardless, I have typed up a basic solution using vanilla JavaScript. For the editing part it uses the contenteditable HTML attribute which allows the end-user to double click an element and change it's textContent.
The html display is basic so you can change it however to fit your needs

<div id=style="width: 100%;">
  <ul id="table" style="list-style-type: none; display: inline-block;">

  </ul>
</div>
<script>
var flashcards = [["Uomo", "Man"],["Donna", "Woman"],["Ragazzo", "Boy"]];
var displayedCard = []; //Using a parallel array to keep track of which side is shown
for(var i = 0; i < flashcards.length; i++){
    displayedCard.push(0);
}
function renderFlashcardTable(){ //This will do the initial rendering of the table
    let ulTable = document.getElementById("table");
    for(var i = 0; i < flashcards.length; i++){
        let card = flashcards[i];
        let indexOfSideShown = displayedCard[i];
        let li = document.createElement("li");
        let cardValueSpan = document.createElement("span");
        cardValueSpan.innerHTML = card[indexOfSideShown]; //Get the value of the side of the card that is shown
        cardValueSpan.setAttribute("contenteditable", "true");
        cardValueSpan.oninput = function(e){ //This method gets called when the user de-selects the element they have been editing
            let li = this.parentElement;
            let sideIndex = parseInt(li.getAttribute("side-index"));
            card[sideIndex] = this.textContent;
        }
        li.appendChild(cardValueSpan);
        li.appendChild(getFlipSidesButton(li));
        li.setAttribute("side-index", indexOfSideShown);
        li.setAttribute("card-index", i);
        ulTable.appendChild(li);
    }
}
function getFlipSidesButton(listItem){//This is generated for each card and when clicked it "flips the switch"
    let btn = document.createElement("button");
    btn.innerHTML = "Flip card";
    btn.onclick = function(e){
        let card = flashcards[listItem.getAttribute("card-index")];
        let index = parseInt(listItem.getAttribute("side-index"));
        let nextSide = (index == 1) ? 0 : 1;
        listItem.setAttribute("side-index", nextSide);
        listItem.children[0].innerHTML = card[nextSide];
    }
    return btn;
}

renderFlashcardTable();
</script>


问:
Excel VBA changing time/day format on columns
I am having to change the Day/Time format for over 9000 provider records. I am new at vba and am not sure what way to go about it, since there are over 100 varieties of provider office hours.

I thought about using a button that would create a new column that would populate the correct information, but I am not sure that is the right path. I thought about doing If statements but I know that would be over 100 If statements due to the variety of office hours.

The current day/time format the is generated in Excel is:

```<code>M 8:30 AM-5:30 PM
T 8:30 AM-5:30 PM
W 8:30 AM-5:30 PM
R 8:30 AM-5:30 PM
F 8:30 AM-5:30 PM
</code>```

I need to turn that into M-F 8:30 AM-5:30 PM

Here is another example

```<code>M 7:30 AM-11:00 PM
T 7:30 AM-11:00 PM
W 7:30 AM-11:00 PM
R 7:30 AM-11:00 PM
F 7:30 AM-11:00 PM
S 8:00 AM-9:00 PM
</code>```

Desired end result:

```<code>M-F 7:30 AM - 11:00 PM; SA 8:00 AM - 9:00 PM
</code>```

答:
Step

1   Replace - with space (Column C with formula =SUBSTITUTE(B6,"-"," "))

2   Extract Day of Week (Column D with Formula =TIMEVALUE(TRIM(MID(SUBSTITUTE(C6," ",REPT(" ",LEN(C6))),(1)*LEN(C6)+1,LEN(C6)))&" "&TRIM(MID(SUBSTITUTE(C6," ",REPT(" ",LEN(C6))),(2)*LEN(C6)+1,LEN(C6))))

3   Extract Time Start(Column E with formula =TIMEVALUE(TRIM(MID(SUBSTITUTE(C25," ",REPT(" ",LEN(C25))),(1)*LEN(C25)+1,LEN(C25)))&" "&TRIM(MID(SUBSTITUTE(C25," ",REPT(" ",LEN(C25))),(2)*LEN(C25)+1,LEN(C25))))

4   Extract Time End (Column f with formula =TIMEVALUE(TRIM(MID(SUBSTITUTE(C25," ",REPT(" ",LEN(C25))),(3)*LEN(C25)+1,LEN(C25)))&" "&TRIM(MID(SUBSTITUTE(C25," ",REPT(" ",LEN(C25))),(4)*LEN(C25)+1,LEN(C25))))

5   Determine if Saturday is included(D32 with formula =IF(COUNTIF(D25:D30,"S"),"Yes","No"))

6   Get Min Time Start (E32 with formula =MIN(E25:E29))

7   Get Max Time End (F32 with formula =MAX(F25:F29))

9   Get final result (B34 with Formula =IF(D32="No",("M-F "&TEXT(E32,"hh:mm AM/PM")&"-"&TEXT(F32,"hh:mm AM/PM")),("M-F "&TEXT(E32,"hh:mm AM/PM")&"-"&TEXT(F32,"hh:mm AM/PM")&(",SA "&TEXT(VLOOKUP("S",D25:F30,2,FALSE),"hh:mm AM/PM")&"-"&TEXT(VLOOKUP("S",D25:F30,3,FALSE),"hh:mm AM/PM")))))

ASSUMPTIONS

1   All original text is formatted the same

2   You are looking for the earliest start time in the array

3   you are looking for the latest end time in the array

NOTES

1   These are the steps in excel. You can copy them over to VBA and put them in a loop if you choose

2   "The formulas are complex, but flexable and could be used as templates should your original Data Change."

3   You can combine the various formulas to create a single extract, but they will get rather hard to read

4   Personally, I would do this in excel So I could review the results (and look for non conforming patterns) so I could adjust as necessary.

5   Once I had validated my data I would Copy and paste the results.

6   This is my first time answering a question on this forum so I hope this is germane.

XLSX Example
I would attach an the spreadsheet but I don't see a way. It may not be allowed on the forum.

Body:
I am having to change the Day/Time format for over 9000 provider records. I am new at vba and am not sure what way to go about it, since there are over 100 varieties of provider office hours.

I thought about using a button that would create a new column that would populate the correct information, but I am not sure that is the right path. I thought about doing If statements but I know that would be over 100 If statements due to the variety of office hours.

The current day/time format the is generated in Excel is:

M 8:30 AM-5:30 PM
T 8:30 AM-5:30 PM
W 8:30 AM-5:30 PM
R 8:30 AM-5:30 PM
F 8:30 AM-5:30 PM

I need to turn that into M-F 8:30 AM-5:30 PM

Here is another example

M 7:30 AM-11:00 PM
T 7:30 AM-11:00 PM
W 7:30 AM-11:00 PM
R 7:30 AM-11:00 PM
F 7:30 AM-11:00 PM
S 8:00 AM-9:00 PM

Desired end result:

M-F 7:30 AM - 11:00 PM; SA 8:00 AM - 9:00 PM


问:
unable to delete keys with prefix from redis
How does one deletes keys with certain prefix from Redis 5+?

I've tried following, yet didn't work for me(

```<code>root@1acb94e11aa2:/data# redis-cli --version
redis-cli 5.0.4
root@1acb94e11aa2:/data# redis-cli -n 9 KEYS ISO:* | wc -l
935
root@1acb94e11aa2:/data# redis-cli -n 9 KEYS ISO:* | xargs -0 redis-cli -n 9 DEL
(integer) 0
root@1acb94e11aa2:/data# redis-cli -n 9 KEYS ISO:* | wc -l
935
root@1acb94e11aa2:/data# redis-cli -n 9 --scan --pattern ISO:* | xargs -0 redis-cli -n 9 unlink
(integer) 0
root@1acb94e11aa2:/data#
</code>```

Please advise.

答:
As long as your key names do not include spaces, you should be able to run this:

```<code>$ redis-cli -n 9 --scan --pattern "ISO:*" | xargs -n 1 redis-cli -n 9 UNLINK
</code>```

EDIT: if they do include spaces, you can do:

```<code>$ redis-cli -n 9 --scan --pattern "ISO:*" | xargs -n 1 -d "\n" redis-cli -n 9 UNLINK
</code>```

Body:
How does one deletes keys with certain prefix from Redis 5+?

I've tried following, yet didn't work for me(

root@1acb94e11aa2:/data# redis-cli --version
redis-cli 5.0.4
root@1acb94e11aa2:/data# redis-cli -n 9 KEYS ISO:* | wc -l
935
root@1acb94e11aa2:/data# redis-cli -n 9 KEYS ISO:* | xargs -0 redis-cli -n 9 DEL
(integer) 0
root@1acb94e11aa2:/data# redis-cli -n 9 KEYS ISO:* | wc -l
935
root@1acb94e11aa2:/data# redis-cli -n 9 --scan --pattern ISO:* | xargs -0 redis-cli -n 9 unlink
(integer) 0
root@1acb94e11aa2:/data#

Please advise.

Body:
As long as your key names do not include spaces, you should be able to run this:

$ redis-cli -n 9 --scan --pattern "ISO:*" | xargs -n 1 redis-cli -n 9 UNLINK

EDIT: if they do include spaces, you can do:

$ redis-cli -n 9 --scan --pattern "ISO:*" | xargs -n 1 -d "\n" redis-cli -n 9 UNLINK


问:
Is this an efficient sql server query?
If I write a sproc in this format, will sql server do this effeciently or should the sql 'weaving' be done on the server side (.net)?

Note: this is just a rough idea of what my query looks like, there are more 'if' clauses the build up my query that I execute using 'exec'

```<code>declare @sql nvarchar(4000)
declare @order nvarchar(4000)

set @sql = 'select id, name'
set @sql = @sql + ' ....'

if(@sortOrder)
    set @order = 'order by name desc'

exec @sql + @order
</code>```

答: The most efficient is to get whatever data you want from the database and then handle the sorting in your application. Changing the order by isn't going to change the amount of data. If the user changes the sort order, why make another trip to the database?</p>

OwnerDisplayName: Blankman

ContentLicense: CC BY-SA 2.5

Title: Is this an efficient sql server query?

Body:
If I write a sproc in this format, will sql server do this effeciently or should the sql 'weaving' be done on the server side (.net)?

Note: this is just a rough idea of what my query looks like, there are more 'if' clauses the build up my query that I execute using 'exec'

declare @sql nvarchar(4000)
declare @order nvarchar(4000)

set @sql = 'select id, name'
set @sql = @sql + ' ....'

if(@sortOrder)
    set @order = 'order by name desc'

exec @sql + @order

LastEditorDisplayName: Doug Currie

OwnerDisplayName: Guiness


问:
z-index between two absolutely positioned columns?
I have a two-column layout with two 'absolute' positioned divs.

```<code>    #left {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
    }

    #right {
        position: absolute;
        top: 0;
        left: 0
        z-index: 0;
    }
</code>```

In each column I have images and would like them to be able to overlap one another in differing configurations with z-index. Using wordpress, #left is populated with posts from one category then subsequently, #right is populated.

Is it possible for an image from #left to be positioned above an image in #right but not all? In essence - can the z-indexes between two separate divs be relative to one another?

I have assigned z-index for images in #left higher than that of #right, but images in #right are always on top. I assume it is something to do with the fact that #left appears first in the code?

答: Just an idea: why don't you use a div for every image? I mean, one div per image...</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a two-column layout with two 'absolute' positioned divs.

    #left {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
    }

    #right {
        position: absolute;
        top: 0;
        left: 0
        z-index: 0;
    }

In each column I have images and would like them to be able to overlap one another in differing configurations with z-index. Using wordpress, #left is populated with posts from one category then subsequently, #right is populated.

Is it possible for an image from #left to be positioned above an image in #right but not all? In essence - can the z-indexes between two separate divs be relative to one another?

I have assigned z-index for images in #left higher than that of #right, but images in #right are always on top. I assume it is something to do with the fact that #left appears first in the code?


问:
Checking for null and empty values in javascript
What is wrong with this if statement? If i pass not empty values i still don't get in to the if block

Both val1 and val2 have values:

let val1 = 'category'
let val2 = 'medical'

if ((val1 !== null || val1 !== '') && (val2 !== null || val2 !== '')) {

  console.log(val1, val2);
}```
</div>
</div>
</p>

<p><code>val1</code> is empty and <code>val2</code> has a value:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let val1 = ''
let val2 = 'medical'

if ((val1 !== null || val1 !== '') && (val2 !== null || val2 !== '')) {

  console.log(val1, val2);
}</code>```

答:
As other answers have mentioned, this sort of expression (val1 !== null || val1 !== '') needs to be changed to (val1 !== null && val1 !== ''), otherwise the condition will be true for val1 = null or val1 = '', example:

Assume val1 = null, then (val1 !== null || val1 !== '') will be evaluated to (null !== null || null !== '') and this will result in (false || true) that equals true.

Now, for your particular case, you can create a method that returns true when you consider a variable is "defined" (you may check for undefined also) and do something like this:

function _isDefined(val)
{
    return ![null, undefined, ""].includes(val);
}

let tests = [
  ["category", "medical"],
  ["category", null],
  [undefined, "medical"],
  ["", null],
  ["something", ""]
];

tests.forEach(function(test)
{
    let [val1, val2] = test;

    if (_isDefined(val1) && _isDefined(val2))
        console.log(val1, val2);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}</code>```

Body:
What is wrong with this if statement? If i pass not empty values i still don't get in to the if block

Both val1 and val2 have values:

let val1 = 'category'
let val2 = 'medical'

if ((val1 !== null || val1 !== '') && (val2 !== null || val2 !== '')) {

  console.log(val1, val2);
}

val1 is empty and val2 has a value:

let val1 = ''
let val2 = 'medical'

if ((val1 !== null || val1 !== '') && (val2 !== null || val2 !== '')) {

  console.log(val1, val2);
}

Body:
As other answers have mentioned, this sort of expression (val1 !== null || val1 !== '') needs to be changed to (val1 !== null && val1 !== ''), otherwise the condition will be true for val1 = null or val1 = '', example:

Assume val1 = null, then (val1 !== null || val1 !== '') will be evaluated to (null !== null || null !== '') and this will result in (false || true) that equals true.

Now, for your particular case, you can create a method that returns true when you consider a variable is "defined" (you may check for undefined also) and do something like this:

function _isDefined(val)
{
    return ![null, undefined, ""].includes(val);
}

let tests = [
  ["category", "medical"],
  ["category", null],
  [undefined, "medical"],
  ["", null],
  ["something", ""]
];

tests.forEach(function(test)
{
    let [val1, val2] = test;

    if (_isDefined(val1) && _isDefined(val2))
        console.log(val1, val2);
});

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}


问:
IIS Server error because of the current total memory
How to solve this error ultimately?

Server Error in '/****StatWCF_OData' Application.

```<code>Memory gates checking failed because the free memory (373817344 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InsufficientMemoryException: Memory gates checking failed because the free memory (373817344 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.
</code>```

Source Error:

```<code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
</code>```

Stack Trace:

```<code>[InsufficientMemoryException: Memory gates checking failed because the free memory (373817344 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.]
   System.ServiceModel.Activation.ServiceMemoryGates.Check(Int32 minFreeMemoryPercentage, Boolean throwOnLowMemory, UInt64& availableMemoryBytes) +121924
   System.ServiceModel.HostingManager.CheckMemoryCloseIdleServices(EventTraceActivity eventTraceActivity) +86
   System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +883

[ServiceActivationException: The service '/****StatWCF_OData/OData.svc' cannot be activated due to an exception during compilation.  The exception message is: Memory gates checking failed because the free memory (373817344 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element..]
   System.Runtime.AsyncResult.End(IAsyncResult result) +650220
   System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +210733
   System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +282
</code>```

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929

答:
The web.config worked for me, but also the SQL Server memory was an issue that needed addressed.

I was able to resolve the sql server memory issue without restarting the MSSQL server processes simply by reducing the server properties memory Maximum server memory to a lower value.  The default was the effectively unlimited.

Without a MS SQL Service restart, the process automatically started reducing the memory footprint to the configured value.

Body:
How to solve this error ultimately?

Server Error in '/****StatWCF_OData' Application.

Memory gates checking failed because the free memory (373817344 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InsufficientMemoryException: Memory gates checking failed because the free memory (373817344 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InsufficientMemoryException: Memory gates checking failed because the free memory (373817344 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.]
   System.ServiceModel.Activation.ServiceMemoryGates.Check(Int32 minFreeMemoryPercentage, Boolean throwOnLowMemory, UInt64& availableMemoryBytes) +121924
   System.ServiceModel.HostingManager.CheckMemoryCloseIdleServices(EventTraceActivity eventTraceActivity) +86
   System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +883

[ServiceActivationException: The service '/****StatWCF_OData/OData.svc' cannot be activated due to an exception during compilation.  The exception message is: Memory gates checking failed because the free memory (373817344 bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element..]
   System.Runtime.AsyncResult.End(IAsyncResult result) +650220
   System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +210733
   System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +282

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929


问:
how to split words before and after colon in separate columns to rows in sql
I have a column [LongText] in a table and its row value is merging of all Attributes and their values. Below is the example.
Can we split colon before and after words into two columns as shown in expected result? need it in sql 2014

```<code>Longtext

TYPE: SOLID WEDGE 1,SOLID WEDGE 2,  VALVE SIZE: 1 IN,  PRESSURE RATING: 800 LB,  CONNECTION TYPE: SOCKET WELD,  BONNET STYLE: BOLTED
</code>```

Expected Output into 2 columns Attribute and Value:

```<code>Attribute        | Value
----------------------------------------------
TYPE             | SOLID WEDGE 1,SOLID WEDGE 2
VALVE SIZE       | 1 IN
PRESSURE RATING  | 800 LB
CONNECTION TYPE  | SOCKET WELD
BONNET STYLE     | BOLTED
</code>```

答:
to get started wit STRING_SPLIT(), something like:

```<code>DECLARE @string varchar(max) = 'TYPE: SOLID WEDGE 1,SOLID WEDGE 2,  VALVE SIZE: 1 IN,  PRESSURE RATING: 800 LB .....';
DECLARE @output varchar(max) = '';
DECLARE @v varchar(max) = (SELECT TOP(1) value from string_split(@string,' '));
WHILE @v <> ''
BEGIN
    select @v;
    SET @string = (SELECT ltrim(substring(@string,LEN(@v)+1,1024)));
    select @string;
    SET @v = (SELECT TOP(1) value from string_split(@string,' '));
END
</code>```

which gives:

as @Tim said, the order is not guaranteed to be correct for above approach.

so, second attempt :

```<code>DECLARE @string varchar(max) = 'TYPE: SOLID WEDGE 1,SOLID WEDGE 2,  VALVE SIZE: 1 IN,  PRESSURE RATING: 800 LB,  CONNECTION TYPE: SOCKET WELD,  BONNET STYLE: BOLTED';
SELECT * FROM string_split(REPLACE(@string,'  ','#'),'#');
</code>```

This hopes (='does-not-check') that there are no '#' characters in the original string.

Body:
I have a column [LongText] in a table and its row value is merging of all Attributes and their values. Below is the example.
Can we split colon before and after words into two columns as shown in expected result? need it in sql 2014

Longtext

TYPE: SOLID WEDGE 1,SOLID WEDGE 2,  VALVE SIZE: 1 IN,  PRESSURE RATING: 800 LB,  CONNECTION TYPE: SOCKET WELD,  BONNET STYLE: BOLTED

Expected Output into 2 columns Attribute and Value:

Attribute        | Value
----------------------------------------------
TYPE             | SOLID WEDGE 1,SOLID WEDGE 2
VALVE SIZE       | 1 IN
PRESSURE RATING  | 800 LB
CONNECTION TYPE  | SOCKET WELD
BONNET STYLE     | BOLTED

Body:
to get started wit STRING_SPLIT(), something like:

DECLARE @string varchar(max) = 'TYPE: SOLID WEDGE 1,SOLID WEDGE 2,  VALVE SIZE: 1 IN,  PRESSURE RATING: 800 LB .....';
DECLARE @output varchar(max) = '';
DECLARE @v varchar(max) = (SELECT TOP(1) value from string_split(@string,' '));
WHILE @v <> ''
BEGIN
    select @v;
    SET @string = (SELECT ltrim(substring(@string,LEN(@v)+1,1024)));
    select @string;
    SET @v = (SELECT TOP(1) value from string_split(@string,' '));
END

which gives:

as @Tim said, the order is not guaranteed to be correct for above approach.

so, second attempt :

DECLARE @string varchar(max) = 'TYPE: SOLID WEDGE 1,SOLID WEDGE 2,  VALVE SIZE: 1 IN,  PRESSURE RATING: 800 LB,  CONNECTION TYPE: SOCKET WELD,  BONNET STYLE: BOLTED';
SELECT * FROM string_split(REPLACE(@string,'  ','#'),'#');

This hopes (='does-not-check') that there are no '#' characters in the original string.


问:
How to determine the result of a code without running it
If I am given the code below, how can I tell what the resulting y-value would be. I apologize if this is a simple question but I find these types of questions very difficult.

For foo(-1,10)

```<code>function y = foo(x, a)
for k=-1:0
b=x-k;
while (x > -2) && (x < 2)
x=x+a+1;
end
end
y = b + x;
end
</code>```

When running the programme I can see that b=10 but I don't understand how you get that. I would appreciate if someone could make this clearer for me.

Thank you!

答:
Start from the top:

foo(x, a) has two parameters: x and a

foo(-1, 10) would mean that x = -1 and a = 10.

From there go down each line.

b = x - k would start out as b = -1 + (the value of k on that current iteration of the loop

Then you would do the same for the while loop.

x = -1 + 10 + 1

So,

x = 10

Now take that value and plug it into the while loop condition:

(10 > -2) and (10 < 2)

Is this condition true? No. So you move on to the next iteration of the for loop

At the end you set y equal to the value you got for b + the value you got for x

Body:
If I am given the code below, how can I tell what the resulting y-value would be. I apologize if this is a simple question but I find these types of questions very difficult.

For foo(-1,10)

function y = foo(x, a)
for k=-1:0
b=x-k;
while (x > -2) && (x < 2)
x=x+a+1;
end
end
y = b + x;
end

When running the programme I can see that b=10 but I don't understand how you get that. I would appreciate if someone could make this clearer for me.

Thank you!


问:
Change Order of Created Concatenated Column Variables
Here is my question - is there a way I can edit my code so that the RequestedDateTime1 time from query 1 remains aligned with the its corresponding EventDisplay1 from query 1?

Below is how I arrived with this question.

I have the following code:

```<code>SELECT [Financial Number], [Depart Date & Time],
             (Cast(Year([Arrival Date & Time]) as nvarchar) +'-'+ Cast (Month([Arrival Date & Time]) as nvarchar)) as Yr_Mon,
             [Event 1 Display],
             [Event 1 Personnel - Completed],
             [Requested 1 Date & Time],
             [Completed 1 Date & Time],
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Event 1 Display]) AS RB,
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Requested 1 Date & Time]) AS RN,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Completed 1 Date & Time]) AS RM,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Event 1 Personnel - Completed]) AS RO,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Arrival Date & Time]) as AD,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Depart Date & Time]) as DT
FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] AS ED
</code>```

Which produces results that look like the following (this is abbreviated for space reasons):

```<code>[Financial Number] [Depart Date & Time] .. EventDisplay1 RequestedDateTime1
      1              2018-01-01 10:19:11     EP Exam     2018-01-01 11:19
      1              2018-01-01 10:19:11     Discharge   2018-01-01 12:20
      2              2018-01-01 13:49:11     EP Exam     2018-01-01 12:20
</code>```

I then add a query to the data query 1 produces:

```<code>Select [Financial Number],
   MIN(CASE DT WHEN 1 THEN [Depart Date & Time] END) AS [Depart Date &
   Time1],
   MIN(CASE RB WHEN 1 THEN [Event 1 Display] END) AS EventDisplay1,
   MIN(CASE RB WHEN 2 THEN [Event 1 Display] END) AS EventDisplay2,
   MIN(CASE RB WHEN 3 THEN [Event 1 Display] END) AS EventDisplay3,
   MIN(CASE RO WHEN 1 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted1,
   MIN(CASE RO WHEN 2 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted2,
   MIN(CASE RO WHEN 3 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted3,
   MIN(CASE RN WHEN 1 THEN [Requested 1 Date & Time] END) AS RequestedDateTime1,
   MIN(CASE RN WHEN 2 THEN [Requested 1 Date & Time] END) AS RequestedDateTime2,
   MIN(CASE RN WHEN 3 THEN [Requested 1 Date & Time] END) AS RequestedDateTime3,
   MIN(CASE RM WHEN 1 THEN [Completed 1 Date & Time] END) AS CompletedDateTime1,
   MIN(CASE RM WHEN 2 THEN [Completed 1 Date & Time] END) AS CompletedDateTime2,
   MIN(CASE RM WHEN 3 THEN [Completed 1 Date & Time] END) AS CompletedDateTime3,

  FROM
 (

SELECT [Financial Number], [Depart Date & Time],
             (Cast(Year([Arrival Date & Time]) as nvarchar) +'-'+ Cast (Month([Arrival Date & Time]) as nvarchar)) as Yr_Mon,
             [Event 1 Display],
             [Event 1 Personnel - Completed],
             [Requested 1 Date & Time],
             [Completed 1 Date & Time],
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Event 1 Display]) AS RB,
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Requested 1 Date & Time]) AS RN,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Completed 1 Date & Time]) AS RM,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Event 1 Personnel - Completed]) AS RO,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Arrival Date & Time]) as AD,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Depart Date & Time]) as DT
  FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] AS ED
   )sub group by [Financial Number]
</code>```

This query produces results that concatenate each row so each row is one unique Financial Number; however in doing so it messes up the alignment of the RequestedDateTime1 variable with the EventDisplay1 variable. For example, using the sample data above, the RequestedDateTime1 of 2018-01-01 12:20, which was aligned with DISCHARGE is now aligned with EP EXAM. I believe this is because the code orders the newly created EventDisplay1, EventDisplay2, EventDisplay3 variables in alphabetical order.

Example Results which are incorrect because the Discharge RequestedDateTime1 is aligned with the EP RequestedDateTime1:

```<code> [Financial Number]   [Depart Date & Time]  EventDisplay1    EventDisplay2 RequestedDateTime1 RequestedDateTime2
        1             2018-01-01 10:19:11    Discharge         EP Exam 2018-01-01 11:19  2018-01-01 12:20
</code>```

Long story short, is there a way I can edit my code so that the RequestedDateTime1 time from query 1 remains aligned with the its corresponding EventDisplay1 from query 1?

Desired Results:

```<code>   [Financial Number]   [Depart Date & Time]  EventDisplay1    EventDisplay2 RequestedDateTime1 RequestedDateTime2
        1             2018-01-01 10:19:11     EP Exam        Discharge     2018-01-01 11:19  2018-01-01 12:20
</code>```

答:
The problem is you are not accounting for NULL and you are using MIN not max.
Cast the values to string if you want to be able to have a valid value for null:

Replace every line that looks like this

```<code>MIN(CASE RB WHEN 1 THEN [Event 1 Display] END) AS EventDisplay1,
</code>```

with something that looks like this

```<code>COALESCE(CAST(MAX(CASE WHERE RB = 1 THEN [Event 1 Display] ELSE NULL END) AS VARCHAR(20)),
         '    -- NO VALUE --  ') AS EventDisplay1,
</code>```

Body:
Here is my question - is there a way I can edit my code so that the RequestedDateTime1 time from query 1 remains aligned with the its corresponding EventDisplay1 from query 1?

Below is how I arrived with this question.

I have the following code:

SELECT [Financial Number], [Depart Date & Time],
             (Cast(Year([Arrival Date & Time]) as nvarchar) +'-'+ Cast (Month([Arrival Date & Time]) as nvarchar)) as Yr_Mon,
             [Event 1 Display],
             [Event 1 Personnel - Completed],
             [Requested 1 Date & Time],
             [Completed 1 Date & Time],
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Event 1 Display]) AS RB,
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Requested 1 Date & Time]) AS RN,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Completed 1 Date & Time]) AS RM,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Event 1 Personnel - Completed]) AS RO,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Arrival Date & Time]) as AD,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Depart Date & Time]) as DT
FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] AS ED

Which produces results that look like the following (this is abbreviated for space reasons):

[Financial Number] [Depart Date & Time] .. EventDisplay1 RequestedDateTime1
      1              2018-01-01 10:19:11     EP Exam     2018-01-01 11:19
      1              2018-01-01 10:19:11     Discharge   2018-01-01 12:20
      2              2018-01-01 13:49:11     EP Exam     2018-01-01 12:20

I then add a query to the data query 1 produces:

Select [Financial Number],
   MIN(CASE DT WHEN 1 THEN [Depart Date & Time] END) AS [Depart Date &
   Time1],
   MIN(CASE RB WHEN 1 THEN [Event 1 Display] END) AS EventDisplay1,
   MIN(CASE RB WHEN 2 THEN [Event 1 Display] END) AS EventDisplay2,
   MIN(CASE RB WHEN 3 THEN [Event 1 Display] END) AS EventDisplay3,
   MIN(CASE RO WHEN 1 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted1,
   MIN(CASE RO WHEN 2 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted2,
   MIN(CASE RO WHEN 3 THEN [Event 1 Personnel - Completed] END) AS
   EventPersonnelCompleted3,
   MIN(CASE RN WHEN 1 THEN [Requested 1 Date & Time] END) AS RequestedDateTime1,
   MIN(CASE RN WHEN 2 THEN [Requested 1 Date & Time] END) AS RequestedDateTime2,
   MIN(CASE RN WHEN 3 THEN [Requested 1 Date & Time] END) AS RequestedDateTime3,
   MIN(CASE RM WHEN 1 THEN [Completed 1 Date & Time] END) AS CompletedDateTime1,
   MIN(CASE RM WHEN 2 THEN [Completed 1 Date & Time] END) AS CompletedDateTime2,
   MIN(CASE RM WHEN 3 THEN [Completed 1 Date & Time] END) AS CompletedDateTime3,

  FROM
 (

SELECT [Financial Number], [Depart Date & Time],
             (Cast(Year([Arrival Date & Time]) as nvarchar) +'-'+ Cast (Month([Arrival Date & Time]) as nvarchar)) as Yr_Mon,
             [Event 1 Display],
             [Event 1 Personnel - Completed],
             [Requested 1 Date & Time],
             [Completed 1 Date & Time],
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Event 1 Display]) AS RB,
             ROW_NUMBER() OVER (PARTITION BY [Financial Number] ORDER BY [Requested 1 Date & Time]) AS RN,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Completed 1 Date & Time]) AS RM,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Event 1 Personnel - Completed]) AS RO,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Arrival Date & Time]) as AD,
             ROW_NUMBER() OVER (PARTITION by [Financial Number] ORDER BY [Depart Date & Time]) as DT
  FROM [ED_Dispo_Events_Using_Event_1 Triage Level 3] AS ED
   )sub group by [Financial Number]

This query produces results that concatenate each row so each row is one unique Financial Number; however in doing so it messes up the alignment of the RequestedDateTime1 variable with the EventDisplay1 variable. For example, using the sample data above, the RequestedDateTime1 of 2018-01-01 12:20, which was aligned with DISCHARGE is now aligned with EP EXAM. I believe this is because the code orders the newly created EventDisplay1, EventDisplay2, EventDisplay3 variables in alphabetical order.

Example Results which are incorrect because the Discharge RequestedDateTime1 is aligned with the EP RequestedDateTime1:

 [Financial Number]   [Depart Date & Time]  EventDisplay1    EventDisplay2 RequestedDateTime1 RequestedDateTime2
        1             2018-01-01 10:19:11    Discharge         EP Exam 2018-01-01 11:19  2018-01-01 12:20

Long story short, is there a way I can edit my code so that the RequestedDateTime1 time from query 1 remains aligned with the its corresponding EventDisplay1 from query 1?

Desired Results:

   [Financial Number]   [Depart Date & Time]  EventDisplay1    EventDisplay2 RequestedDateTime1 RequestedDateTime2
        1             2018-01-01 10:19:11     EP Exam        Discharge     2018-01-01 11:19  2018-01-01 12:20

Body:
The problem is you are not accounting for NULL and you are using MIN not max.
Cast the values to string if you want to be able to have a valid value for null:

Replace every line that looks like this

MIN(CASE RB WHEN 1 THEN [Event 1 Display] END) AS EventDisplay1,

with something that looks like this

COALESCE(CAST(MAX(CASE WHERE RB = 1 THEN [Event 1 Display] ELSE NULL END) AS VARCHAR(20)),
         '    -- NO VALUE --  ') AS EventDisplay1,


问:
HTML5 localStorage space limit on iPad Safari
To clarify I'm referring to the key/value localStorage pairs, not Web SQL DB or IndexedDB.

Is it strictly a 5MB limit for the iPad, or is it true that it's unlimited but it will ask the user to allow/deny once you exceed 5MB?

I'm hoping to use localStorage to store a large amount of data and so is important that it's unlimited.

答: I know you are looking for localstorage key/value pairs. Just like myself. I tried a native solution and apparently my iPad had 2.5 MB only for localstorage. So I switched to locaForage which is a IndexedDB (+more) wrapper in a very similar to localstorage api. It doesnt have these limitations of localstorage.</p>


问:
JPA 2.1 - Strange behaviour with a one to one relationship
I'm experiencing some strange behaviour with a one to one relationship. I have a one to one relationship between two entities: GeographicalLocation and IdentityDocument. In this relationship GeographicalLocation is the parent entity. The relationship is owned by the IdnetityDocument entity. Here is the JPA implementation:

```<code>@Entity
@Table(name="GEOGRAPHICAL_LOCATION")
public class GeographicalLocation implements Serializable
{
  private Long id;
  ...

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "GEOGRAPHICAL_LOCATION_ID")
  public Long getId()
  {
    return id;
  }

  public void setId(Long id)
  {
    this.id = id;
  }
  ...
}

@Entity
@Table(name="IDENTITY_DOCUMENT")
public class IdentityDocument implements Serializable
{
  private Long id;
  ...
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "IDENTITY_DOCUMENT_ID")
  public Long getId()
  {
    return id;
  }

  public void setId(Long id)
  {
    this.id = id;
  }

  @OneToOne
  @MapsId
  @JoinColumn(name = "IDENTITY_DOCUMENT_ID")
  public GeographicalLocation getPlaceOfIssue()
  {
    return placeOfIssue;
  }

  public void setPlaceOfIssue(GeographicalLocation placeOfIssue)
  {
    this.placeOfIssue = placeOfIssue;
  }
</code>```

This generates the following database model:

Now, trying to persist these entities like this:

```<code>GeographicalLocation geographicalLocation = ...;
IdentityDocument identityDocument = ...;
geographicalLocationFacade.save(geographicalLocation);
identityDocument.setPlaceOfIssue(geographicalLocation);
identityDocumentFacade.save(identityDocument);
</code>```

creates two records in the GEOGRAPHICAL_LOCATION table and none in the IDENTITY_DOCUMENT one.

What seems to happen is that persisting the offspring entity creates a record in the master table while persisting the master entity correctly creates a record in the master table and none in the offspring table. I tried to play with different scenario and to google around, but I still don't understand what might happen here.
Many thanks in advance to whoever can shade some light.
kind regards,
Nicolas

答: This is a bug in hibernate which i have experienced it too. Found that @GeneratedValue(strategy = GenerationType.IDENTITY) was the reason. If you use AUTO instead of IDENTITY then it will work, but the main reason we use IDENTITY is to prevent the extra select query by hibernate to determine the max value of id, leaving it to the DB, which will be a trade off you have to do.

Body:
I'm experiencing some strange behaviour with a one to one relationship. I have a one to one relationship between two entities: GeographicalLocation and IdentityDocument. In this relationship GeographicalLocation is the parent entity. The relationship is owned by the IdnetityDocument entity. Here is the JPA implementation:

@Entity
@Table(name="GEOGRAPHICAL_LOCATION")
public class GeographicalLocation implements Serializable
{
  private Long id;
  ...

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "GEOGRAPHICAL_LOCATION_ID")
  public Long getId()
  {
    return id;
  }

  public void setId(Long id)
  {
    this.id = id;
  }
  ...
}

@Entity
@Table(name="IDENTITY_DOCUMENT")
public class IdentityDocument implements Serializable
{
  private Long id;
  ...
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "IDENTITY_DOCUMENT_ID")
  public Long getId()
  {
    return id;
  }

  public void setId(Long id)
  {
    this.id = id;
  }

  @OneToOne
  @MapsId
  @JoinColumn(name = "IDENTITY_DOCUMENT_ID")
  public GeographicalLocation getPlaceOfIssue()
  {
    return placeOfIssue;
  }

  public void setPlaceOfIssue(GeographicalLocation placeOfIssue)
  {
    this.placeOfIssue = placeOfIssue;
  }

This generates the following database model:

Now, trying to persist these entities like this:

GeographicalLocation geographicalLocation = ...;
IdentityDocument identityDocument = ...;
geographicalLocationFacade.save(geographicalLocation);
identityDocument.setPlaceOfIssue(geographicalLocation);
identityDocumentFacade.save(identityDocument);

creates two records in the GEOGRAPHICAL_LOCATION table and none in the IDENTITY_DOCUMENT one.

What seems to happen is that persisting the offspring entity creates a record in the master table while persisting the master entity correctly creates a record in the master table and none in the offspring table. I tried to play with different scenario and to google around, but I still don't understand what might happen here.
Many thanks in advance to whoever can shade some light.
kind regards,
Nicolas


问:
RegEx for matching trigrams
I'm trying to get all groups of three words from a string - which can consist of multiple sentences - without going across sentence boundaries. I've got it working for words that only have standard letters of the alphabet:

```<code>preg_match_all("/(?=(\b(\w+)(?:\s+(\w+)\b|$)(?:\s+(\w+)\b|$)))/",$utext,$matches);
print_r($matches[1]);
</code>```

But it falls down where there are apostrophes or hyphens. So, with this sample text:

```<code>The quick brown fox's feet jumped over the lazy dog. The rain falls head-first in the plain.
</code>```

I want this list:

The quick brown

quick brown fox's

brown fox's feet

fox's feet jumped

feet jumped over

jumped over the

over the lazy

the lazy dog

The rain falls

rain falls head-first

falls head-first in

head-first in the

in the plain

I've tried using [\w'-] for each \w above, but that gives some oddities:

```<code>Array ( [0] => The quick brown [1] => quick brown fox's [2] => brown fox's feet [3] => fox's feet jumped [4] => 's feet jumped [5] => s feet jumped [6] => feet jumped over [7] => jumped over the [8] => over the lazy [9] => the lazy dog [10] => The rain falls [11] => rain falls head-first [12] => falls head-first in [13] => head-first in the [14] => -first in the [15] => first in the [16] => in the plain )
</code>```

What am I missing? Thanks.

答:
Just change \w to [^\s.] (not space or dot) and remove the word boudaries. Another change is to add an alternation "beginning of line OR space" at the beginning of the regex:

```<code>$text = "The quick brown fox's feet jumped over the lazy dog. The rain falls head-first in the plain.";

preg_match_all("/(?=((?<=^|\s)[^\s.]+(?:\s+[^\s.]+|$)(?:\s+[^\s.]+|$)))/",$text,$matches);
print_r($matches[1]);
</code>```

Output:

Array
(
    [0] => The quick brown
    [1] => quick brown fox's
    [2] => brown fox's feet
    [3] => fox's feet jumped
    [4] => feet jumped over
    [5] => jumped over the
    [6] => over the lazy
    [7] => the lazy dog
    [8] => The rain falls
    [9] => rain falls head-first
    [10] => falls head-first in
    [11] => head-first in the
    [12] => in the plain
)
```

<p><strong>Regex explanation:</strong></p>

<pre class="lang-none prettyprint-override"><code>(?=                     # lookahead
    (                   # start group 1
        (?<=^|\s)       # lookbehind, make sure we have beginning of line or space before
        [^\s.]+         # 1 or more non space, non dot
        (?:             # non capture group
            \s+         # 1 or more spaces
            [^\s.]+     # 1 or more non space, non dot
          |             # OR
            $           # end of line
        )               # end group
        (?:             # non capture group
            \s+         # 1 or more spaces
            [^\s.]+     # 1 or more non space, non dot
          |             # OR
            $           # end of line
        )               # end group
    )                   # end group 1
)                       # end lookahead
</code>```

Edit according to comment.

$text = "The quick brown fox's feet jumped over the lazy dog. The rain falls head-first in the plain. 'This is a quote,' I say, and that's that.";

preg_match_all("/(?=((?<=^|\s|')(?:(?<=[a-zA-Z])'(?=[a-zA-Z])|[^\s.,'])+(?:\s+(?:(?<=[a-zA-Z])'(?=[a-zA-Z])|[^\s.,'])+|$){2}))/",$text,$matches);
print_r($matches[1]);
```

<p><strong>Output:</strong></p>

<pre class="lang-none prettyprint-override"><code>Array
(
    [0] => The quick brown
    [1] => quick brown fox's
    [2] => brown fox's feet
    [3] => fox's feet jumped
    [4] => s feet jumped
    [5] => feet jumped over
    [6] => jumped over the
    [7] => over the lazy
    [8] => the lazy dog
    [9] => The rain falls
    [10] => rain falls head-first
    [11] => falls head-first in
    [12] => head-first in the
    [13] => in the plain
    [14] => This is a
    [15] => is a quote
    [16] => and that's that
)
</code>```

Regex explanation:

(?=                             # lookahead
    (                           # start group 1
        (?<=^|\s|')             # lookbehind, make sure we have beginning of line or space or quote before
        (?:                     # start non capture group
            (?<=[a-zA-Z])       # lookbehind, make sure we have a letter before
            '                   # a single quote
            (?=[a-zA-Z])        # lookahead, make sure we have a letter after
          |                     # OR
            [^\s.,']            # not a space or dot or comma or single quote
        )+                      # group may appear 1 or more times
        (?:                     # non capture group
            \s+                 # 1 or more spaces
            (?:                 # non capture group
                (?<=[a-zA-Z])   # lookbehind, make sure we have a letter before
                '               # a single quote
                (?=[a-zA-Z])    # lookahead, make sure we have a letter after
              |                 # OR
                [^\s.,']        # not a space or dot or comma or single quote
            )+                  # group may appear 1 or more times
          |                     # OR
            $                   # end of line
        ){2}                    # end group, must appear twice
    )                           # end group 1
)                               # end lookahead
```

Title: RegEx for matching trigrams

Body:
I'm trying to get all groups of three words from a string - which can consist of multiple sentences - without going across sentence boundaries. I've got it working for words that only have standard letters of the alphabet:

preg_match_all("/(?=(\b(\w+)(?:\s+(\w+)\b|$)(?:\s+(\w+)\b|$)))/",$utext,$matches);
print_r($matches[1]);

But it falls down where there are apostrophes or hyphens. So, with this sample text:

The quick brown fox's feet jumped over the lazy dog. The rain falls head-first in the plain.

I want this list:

The quick brown

quick brown fox's

brown fox's feet

fox's feet jumped

feet jumped over

jumped over the

over the lazy

the lazy dog

The rain falls

rain falls head-first

falls head-first in

head-first in the

in the plain

I've tried using [\w'-] for each \w above, but that gives some oddities:

Array ( [0] => The quick brown [1] => quick brown fox's [2] => brown fox's feet [3] => fox's feet jumped [4] => 's feet jumped [5] => s feet jumped [6] => feet jumped over [7] => jumped over the [8] => over the lazy [9] => the lazy dog [10] => The rain falls [11] => rain falls head-first [12] => falls head-first in [13] => head-first in the [14] => -first in the [15] => first in the [16] => in the plain )

What am I missing? Thanks.

Body:
Just change \w to [^\s.] (not space or dot) and remove the word boudaries. Another change is to add an alternation "beginning of line OR space" at the beginning of the regex:

$text = "The quick brown fox's feet jumped over the lazy dog. The rain falls head-first in the plain.";

preg_match_all("/(?=((?<=^|\s)[^\s.]+(?:\s+[^\s.]+|$)(?:\s+[^\s.]+|$)))/",$text,$matches);
print_r($matches[1]);

Output:

Array
(
    [0] => The quick brown
    [1] => quick brown fox's
    [2] => brown fox's feet
    [3] => fox's feet jumped
    [4] => feet jumped over
    [5] => jumped over the
    [6] => over the lazy
    [7] => the lazy dog
    [8] => The rain falls
    [9] => rain falls head-first
    [10] => falls head-first in
    [11] => head-first in the
    [12] => in the plain
)

Regex explanation:

(?=                     # lookahead
    (                   # start group 1
        (?<=^|\s)       # lookbehind, make sure we have beginning of line or space before
        [^\s.]+         # 1 or more non space, non dot
        (?:             # non capture group
            \s+         # 1 or more spaces
            [^\s.]+     # 1 or more non space, non dot
          |             # OR
            $           # end of line
        )               # end group
        (?:             # non capture group
            \s+         # 1 or more spaces
            [^\s.]+     # 1 or more non space, non dot
          |             # OR
            $           # end of line
        )               # end group
    )                   # end group 1
)                       # end lookahead

Edit according to comment.

$text = "The quick brown fox's feet jumped over the lazy dog. The rain falls head-first in the plain. 'This is a quote,' I say, and that's that.";

preg_match_all("/(?=((?<=^|\s|')(?:(?<=[a-zA-Z])'(?=[a-zA-Z])|[^\s.,'])+(?:\s+(?:(?<=[a-zA-Z])'(?=[a-zA-Z])|[^\s.,'])+|$){2}))/",$text,$matches);
print_r($matches[1]);

Output:

Array
(
    [0] => The quick brown
    [1] => quick brown fox's
    [2] => brown fox's feet
    [3] => fox's feet jumped
    [4] => s feet jumped
    [5] => feet jumped over
    [6] => jumped over the
    [7] => over the lazy
    [8] => the lazy dog
    [9] => The rain falls
    [10] => rain falls head-first
    [11] => falls head-first in
    [12] => head-first in the
    [13] => in the plain
    [14] => This is a
    [15] => is a quote
    [16] => and that's that
)

Regex explanation:

(?=                             # lookahead
    (                           # start group 1
        (?<=^|\s|')             # lookbehind, make sure we have beginning of line or space or quote before
        (?:                     # start non capture group
            (?<=[a-zA-Z])       # lookbehind, make sure we have a letter before
            '                   # a single quote
            (?=[a-zA-Z])        # lookahead, make sure we have a letter after
          |                     # OR
            [^\s.,']            # not a space or dot or comma or single quote
        )+                      # group may appear 1 or more times
        (?:                     # non capture group
            \s+                 # 1 or more spaces
            (?:                 # non capture group
                (?<=[a-zA-Z])   # lookbehind, make sure we have a letter before
                '               # a single quote
                (?=[a-zA-Z])    # lookahead, make sure we have a letter after
              |                 # OR
                [^\s.,']        # not a space or dot or comma or single quote
            )+                  # group may appear 1 or more times
          |                     # OR
            $                   # end of line
        ){2}                    # end group, must appear twice
    )                           # end group 1
)                               # end lookahead


问:
how to set webservice url properly?
I have a ASP.NET application. Inside the asp.net application I have a folder called WebServices  where I keep all the .asmx files.

I am referring these asmx files inside asp.net .cs files. Instead of giving the full url to the webservice.url property how can i set the path like this.

```<code> ds.Url = this.ResolveUrl("~/WebServices/xxx.asmx");
</code>```

答: If your services and cs files both are in same project then you donot need to set the URL as such. These services can be called as if you can call other classes in your application.</p>

Title: how to set webservice url properly?

Body:
I have a ASP.NET application. Inside the asp.net application I have a folder called WebServices  where I keep all the .asmx files.

I am referring these asmx files inside asp.net .cs files. Instead of giving the full url to the webservice.url property how can i set the path like this.

 ds.Url = this.ResolveUrl("~/WebServices/xxx.asmx");


问:
Showing Read At for Twilio Programmable chat
I'm using Programmable chat. I'm trying to show ReadAt meta data to users. I know when the user is getting the message on the frontend since I'm listening to messageAdded on the current Channel in the Twilio Javascript SDK. I'm storing the message by listening to Webhook on the preMessageSend to make sure that the message is saved in DB. When I get this message, the problem is I'm not getting the messageId which I'm getting on the Javascript SDK message. Can someone help me in understanding how to correlate both the messages?</p>

答:
According to the Twilio developer docs:

Pre-Event Webhooks will fire before an action has been committed to the Chat instance, blocking publication until a response is received. This gives your backend (or Function) the opportunity to intercept, modify, or reject any action across the instance, making these hooks useful for spam/language filtering, complex permission schemes, or other business logic. Pre-event webhooks are fired only for actions from the Chat SDK; the REST API actions will never fire them.

So I suspect the messageId is not created until after this webhook.


问:
is it possible to pass interface or base class type to java.lang.Class as generic type
I have an interface A and classes B,C which extends A.

I want to store class types of B and C in one ArrayList.
In order to do that I have create a list and add elements like below;

```<code>private List<Class<A>> classes = new ArrayList<>();

classes.add(B.class);
classes.add(C.class);
</code>```

it doesn't accept to add these types.
is there any way to do it?

答:
As Benjamin said, the below is valid and compiles. If it doesn't work for you then there must be something significant that you're omitting:</p>

```<code>public class Main {
    interface A {}
    class B implements A {}
    class C implements A {}
    private List<Class<? extends A>> classes = new ArrayList<>();
    {
        classes.add(B.class);
        classes.add(C.class);
    }
}
</code>```

Body:
I have an interface A and classes B,C which extends A.

I want to store class types of B and C in one ArrayList.
In order to do that I have create a list and add elements like below;

private List<Class> classes = new ArrayList<>();

classes.add(B.class);
classes.add(C.class);

it doesn't accept to add these types.
is there any way to do it?

Body:
As Benjamin said, the below is valid and compiles. If it doesn't work for you then there must be something significant that you're omitting:

public class Main {
    interface A {}
    class B implements A {}
    class C implements A {}
    private List<Class<? extends A>> classes = new ArrayList<>();
    {
        classes.add(B.class);
        classes.add(C.class);
    }
}


问:
Xamarin iOS, FileNotFound for Bundle Resources
I keep getting the error like this:

```<code>Error       System.IO.FileNotFoundException: /Users/Nathaniel/Library/Caches/Xamarin/mtbs/builds/EagleEyePrism.iOS/7b66664107c017167463bbde19c6a2f4/obj/iPhone/Debug/optimized/upload_blue.png does not exist
File name: '/Users/Nathaniel/Library/Caches/Xamarin/mtbs/builds/EagleEyePrism.iOS/7b66664107c017167463bbde19c6a2f4/obj/iPhone/Debug/optimized/upload_blue.png'
  at System.IO.File.Copy (System.String sourceFileName, System.String destFileName, System.Boolean overwrite) [0x00193] in /Users/builder/jenkins/workspace/build-package-osx-mono/2018-08/external/bockbuild/builds/mono-x64/mcs/class/corlib/System.IO/File.cs:111
  at Xamarin.MacDev.Tasks.SmartCopyTaskBase.CopyFile (System.String source, System.String target, System.String targetItemSpec) [0x0002d] in <cd319828b05749ae9de0c80034a6d2bc>:0
  at Xamarin.MacDev.Tasks.SmartCopyTaskBase.Execute () [0x000b6] in <cd319828b05749ae9de0c80034a6d2bc>:0    EagleEyePrism.iOS
</code>```

It doesn't matter what file it is.  If I remove upload_blue.png, it throws an error on the next Resource.

I have tried everything.  I have deleted the Xamarin cache on the Mac, I've deleted AppData\Local\Xamarin on the PC, it simply will not compile.
If I set all the BundleResources to Embedded Resources, it will compile and run, but then none of my image collateral gets displayed.

I've scoured the internet for hours trying to solve this problem.

I'm running the latest XCode on the Mac, with MacOS Mojave, and Windows 10 with Visual Studio 2019 on the PC.

答: I solved it by disabling the Optimize PNG images option in the iOS Build Options</p>

Body:
I keep getting the error like this:

Error       System.IO.FileNotFoundException: /Users/Nathaniel/Library/Caches/Xamarin/mtbs/builds/EagleEyePrism.iOS/7b66664107c017167463bbde19c6a2f4/obj/iPhone/Debug/optimized/upload_blue.png does not exist
File name: '/Users/Nathaniel/Library/Caches/Xamarin/mtbs/builds/EagleEyePrism.iOS/7b66664107c017167463bbde19c6a2f4/obj/iPhone/Debug/optimized/upload_blue.png'
  at System.IO.File.Copy (System.String sourceFileName, System.String destFileName, System.Boolean overwrite) [0x00193] in /Users/builder/jenkins/workspace/build-package-osx-mono/2018-08/external/bockbuild/builds/mono-x64/mcs/class/corlib/System.IO/File.cs:111
  at Xamarin.MacDev.Tasks.SmartCopyTaskBase.CopyFile (System.String source, System.String target, System.String targetItemSpec) [0x0002d] in <cd319828b05749ae9de0c80034a6d2bc>:0
  at Xamarin.MacDev.Tasks.SmartCopyTaskBase.Execute () [0x000b6] in <cd319828b05749ae9de0c80034a6d2bc>:0    EagleEyePrism.iOS

It doesn't matter what file it is.  If I remove upload_blue.png, it throws an error on the next Resource.

I have tried everything.  I have deleted the Xamarin cache on the Mac, I've deleted AppData\Local\Xamarin on the PC, it simply will not compile.
If I set all the BundleResources to Embedded Resources, it will compile and run, but then none of my image collateral gets displayed.

I've scoured the internet for hours trying to solve this problem.

I'm running the latest XCode on the Mac, with MacOS Mojave, and Windows 10 with Visual Studio 2019 on the PC.


问:
Can't import: 'unable to import rest_framework' when importing serializer? (windows)
I have 'rest_framework' in my INSTALLED_APPS of settings.py and I can import it with no problem in cmd

But I receive an "Unable to import 'rest_framework'" message

I can import rest_framework no problem in my cmd prompt, so I really have no idea what the issue is?

答:
vs code_taskbar
I see you're using VS Code. A quick fix is to go to the Python environment settings at the bottom-left corner[Taskbar] of the VS Code-> tap on [Python 2/3...] and it will prompt you to choose the environment from the default Python installation directory to your Project Virtual Environment(venv) directory and that should fix all the import issues.</p>


问:
Python error while finding greatest number
I am trying techgig problem of finding greatest of 3 numbers. problem as follows

You just need to take three number as input from stdin and you need to
  find greatest of them.

Input Format

You will be taking three numbers as an input from stdin one on each line respectively.

Constraints

-100000 <= N <= 100000

Output Format

You need to print the greatest of the three numbers to the stdout.

Sample TestCase 1

Input

```<code>902
100
666
</code>```

I done this

```<code>''' Read input from STDIN. Print your output to STDOUT '''
#Use input() to read input from STDIN and use print to write your output to STDOUT
import sys
def main():

    s=sys.stdin.read()
    s=s.split("\n")
    a=int(s[0])
    b=int(s[1])
    c=int(s[2])
    temp=0
    e=[a,b,c]
    for i in e:
        if i > temp:
            temp=i
    print(temp)

    '''if (a>b) and (a>c):
        temp = a
    elif (b>a) and (b>c):
        temp = b
    else:
        temp = c
    print(temp)'''

main()
</code>```

It has predefined input 902, 100, 666. My code shows 902 output and expected also shows 902, but its showing failed, Why? In above code commented or non commented thing both showing failed.

答:
temp is being initialized as 0, but the input allows for negative numbers. 0 will considered larger than any negative input though. This means your algorithm will fail for test cases that have negative input.

Initialize temp to a value smaller than the minimum allowed input:

```<code>temp = -100001 # One less than the minimum
</code>```

Body:
I am trying techgig problem of finding greatest of 3 numbers. problem as follows

You just need to take three number as input from stdin and you need to
  find greatest of them.

Input Format

You will be taking three numbers as an input from stdin one on each line respectively.

Constraints

-100000 <= N <= 100000

Output Format

You need to print the greatest of the three numbers to the stdout.

Sample TestCase 1

Input

902
100
666

I done this

''' Read input from STDIN. Print your output to STDOUT '''
#Use input() to read input from STDIN and use print to write your output to STDOUT
import sys
def main():

    s=sys.stdin.read()
    s=s.split("\n")
    a=int(s[0])
    b=int(s[1])
    c=int(s[2])
    temp=0
    e=[a,b,c]
    for i in e:
        if i > temp:
            temp=i
    print(temp)

    '''if (a>b) and (a>c):
        temp = a
    elif (b>a) and (b>c):
        temp = b
    else:
        temp = c
    print(temp)'''

main()

It has predefined input 902, 100, 666. My code shows 902 output and expected also shows 902, but its showing failed, Why? In above code commented or non commented thing both showing failed.

Body:
temp is being initialized as 0, but the input allows for negative numbers. 0 will considered larger than any negative input though. This means your algorithm will fail for test cases that have negative input.

Initialize temp to a value smaller than the minimum allowed input:

temp = -100001 # One less than the minimum


问:
Pod setup failure
Right after installing cocoapods with brew and running pod setup it exists with the following messages:

```<code>Setting up CocoaPods master repo
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/yaml.rb:5:in `<top (required)>':
It seems your ruby installation is missing psych (for YAML output).
To eliminate this warning, please install libyaml and reinstall your ruby.
Assertion failed: (0 && "LoadedImage not found"), function findLoadedImage, file /BuildRoot/Library/Caches/com.apple.xbs/Sources/libdyld/dyld-655.1/dyld3/ClosureBuilder.cpp, line 469.
Abort trap: 6
</code>```

答: This is most likely an issue with your ruby config. I use RVM to manage my ruby installations and running rvm get stable --auto-dotfiles fixed the issue.

Title: Pod setup failure

Body:
Right after installing cocoapods with brew and running pod setup it exists with the following messages:

Setting up CocoaPods master repo
/System/Library/Frameworks/Ruby.framework/Versions/2.3/usr/lib/ruby/2.3.0/yaml.rb:5:in `<top (required)>':
It seems your ruby installation is missing psych (for YAML output).
To eliminate this warning, please install libyaml and reinstall your ruby.
Assertion failed: (0 && "LoadedImage not found"), function findLoadedImage, file /BuildRoot/Library/Caches/com.apple.xbs/Sources/libdyld/dyld-655.1/dyld3/ClosureBuilder.cpp, line 469.
Abort trap: 6


问:
var output = 1 + 2 + 3 + "4" + 5 + "90"; Output : 64590;; Just want to know why?
Need to know the logical reason behind the stated output

```<code>var output = 1 + 2 + 3 + "4" + 5 + "90";
</code>```

Output : "64590"

答:
when you input a value without declaring its type then its type is decided implicitly, So, here 1 2 3 are integers and gives the arithmetic sum 6. And the next "4" is a string so it is being concatenated  and next 5 is an integer which is also being concatenated ,Which might be confusing.

So here your question should be why string + integers or integers + strings are concatenated, thats because, in real world there is no result of "ab" + 2 or 3 + "laila" or "hi" + 5 etc , thats why here compiler assumes that you are not intentionally trying to add alphabets with integers you are trying to concatenate them.So , compiler implicitly does this for your ease.

Body:
Need to know the logical reason behind the stated output

var output = 1 + 2 + 3 + "4" + 5 + "90";

Output : "64590"


问:
Using functions with the same name from different classes; what pattern is this?
I would like to know what OOP technique this is so that I can gain a better understanding of how to use it, and what is does in a wider range of applications.

I have seen this technique used in a few programs. Yet I have tried researching it and I have not found any article anywhere that even makes mention of it.

in fileA.cpp when I have this member function of class A

```<code>   // an object of class B is instantiated in class B
   classB _classB

   void signup(int n){
        _classB.signup(n);
        // rest of the function
   };
</code>```

then in fileB we have this member function of class B

```<code>   void signup(int n){
        // rest of function
   };
</code>```

Is there definition for this technique where a function of a particular name calls a function of similar name from another class. Is there any articles I can read about this, so that I can further use it in my programming?

答:
I'm not aware of any particular name for what you're doing, because it's not a pattern nor anything really particularly special/magical.

That being said, in colloquial discussions I might say that these functions "forward" to the other functions. If I'm "forwarding" in this manner I'll usually have the same function names, because they do the same things.

But, again, this is just me.

Other terms (stolen from the comments section) may include façade or proxy.

When you start doing things like hiding implementations, or wrapping symbols for transport across ABI boundaries, you might be using techniques like marshalling or patterns like PIMPL. Again, these terms do not describe your function names at all, but you'll almost certainly find a degree of function name re-use when employing such techniques/patterns.

Body:
I would like to know what OOP technique this is so that I can gain a better understanding of how to use it, and what is does in a wider range of applications.

I have seen this technique used in a few programs. Yet I have tried researching it and I have not found any article anywhere that even makes mention of it.

in fileA.cpp when I have this member function of class A

   // an object of class B is instantiated in class B
   classB _classB

   void signup(int n){
        _classB.signup(n);
        // rest of the function
   };

then in fileB we have this member function of class B

   void signup(int n){
        // rest of function
   };

Is there definition for this technique where a function of a particular name calls a function of similar name from another class. Is there any articles I can read about this, so that I can further use it in my programming?


问:
Attaching a specific field/variable to the interface being implemented
I have an interface myInterface which defines two methods, method1, method2. This interface is being implemented by 100 other classes. My requirement is that I am able to to add a field to the interface which is unique to each class. Example: I want to add a field numberOfRequests, which is unique for all classes. So everytime I call method1, I can update numberOfRequests for that class. How do I achieve this by making changes at interface level?</p>

答:
It is not possible to define instance (non-static) fields in interfaces. You can only add a static field to the interface, which then only belongs directly to this interface.

To implement the required functionality, you have to add this field to every single class that implements the interface.

If you are not restricted to using an interface, you can make all implementing classes extending a new class which has the numberOfRequests field. This new class could then also implement this interface, if the behaviour all the methods accessing numberOfRequests is always the same in all implementing classes.


问:
StreamReader breaking on special character
I'm trying to read a file in a meteor-app on the server with fs.

My goal:

I want to process a very big file. Therefore I need to read it line by line to keep the memory usage flat.

My approach:

I'm creating a streamReader and processing the file for each character, saving it to a new string until I get a \n, then passing it to a processLine(line) function.

My test-file:

```<code>F1;F2
12;abäde
</code>```

My code:

I've commented everything out thats out of scope of the problem. Anyway posting it just in case someone has a complete different way for me.

```<code>const fs = require('fs');

// ...

let streamReader = fs.createReadStream(path, { highWaterMark: 1});

let line = "";
streamReader.on('data', function(chunk) {
    console.log(chunk)
    // line += chunk;
    // if (chunk == "\n") {
    //     processLine(line);
    //     line = "";
    // }
});

streamReader.on('end', function() {
    processLine(line);
});

processLine = (line) => {
    console.log(line);
}
</code>```

Output from the code above:

```<code>F
1
;
F
2

1
2
;
a
b
�
�
d
e
</code>```

Either tho the docs are saying the default encoding is utf8 the character ä prints out as �.

Output when specifying the encoding like below:

fs.createReadStream(path, { highWaterMark: 1, encoding: "utf8 }

```<code>F
1
;
F
2

1
2
;
a
b
</code>```

It is breaking when reaching the ä. I think this happens because it would need 2 chunks to represent that character.

I just dont know how to get around it. In general I just need to process it line by line. Maybe I've taken the wrong way?

答:
Tiny values of the high water mark don't save a significant amount of RAM; the default values are something like 32k anyway.  And, to try to use the highwater mark to enforce an old-timey getchar() operation is to misuse it.

There's a readline object in core node.js.  It accepts output from a stream and splits it into lines.  The documentation offers some samples. This is adapted from the samples not debugged.

```<code>const fs = require('fs')
const readline = require('readline')

const rl = readline.createInterface(
   {
          input: fs.createReadStream(path),
      crlfDelay: Infinity
   })

rl.on('line', function (line) {
  console.log(`A line: ${line}`);
})

rl.on('close', function () {
  /* file completely processed */
} )
</code>```

It is also handy for interactive commmand line input/output, but you don't care about that here.

Body:
I'm trying to read a file in a meteor-app on the server with fs.

My goal:

I want to process a very big file. Therefore I need to read it line by line to keep the memory usage flat.

My approach:

I'm creating a streamReader and processing the file for each character, saving it to a new string until I get a \n, then passing it to a processLine(line) function.

My test-file:

F1;F2
12;abäde

My code:

I've commented everything out thats out of scope of the problem. Anyway posting it just in case someone has a complete different way for me.

const fs = require('fs');

// ...

let streamReader = fs.createReadStream(path, { highWaterMark: 1});

let line = "";
streamReader.on('data', function(chunk) {
    console.log(chunk)
    // line += chunk;
    // if (chunk == "\n") {
    //     processLine(line);
    //     line = "";
    // }
});

streamReader.on('end', function() {
    processLine(line);
});

processLine = (line) => {
    console.log(line);
}

Output from the code above:

F
1
;
F
2

1
2
;
a
b
�
�
d
e

Either tho the docs are saying the default encoding is utf8 the character ä prints out as �.

Output when specifying the encoding like below:

fs.createReadStream(path, { highWaterMark: 1, encoding: "utf8 }

F
1
;
F
2

1
2
;
a
b

It is breaking when reaching the ä. I think this happens because it would need 2 chunks to represent that character.

I just dont know how to get around it. In general I just need to process it line by line. Maybe I've taken the wrong way?

Body:
Tiny values of the high water mark don't save a significant amount of RAM; the default values are something like 32k anyway.  And, to try to use the highwater mark to enforce an old-timey getchar() operation is to misuse it.

There's a readline object in core node.js.  It accepts output from a stream and splits it into lines.  The documentation offers some samples. This is adapted from the samples not debugged.

const fs = require('fs')
const readline = require('readline')

const rl = readline.createInterface(
   {
          input: fs.createReadStream(path),
      crlfDelay: Infinity
   })

rl.on('line', function (line) {
  console.log(`A line: ${line}`);
})

rl.on('close', function () {
  /* file completely processed */
} )

It is also handy for interactive commmand line input/output, but you don't care about that here.


问:
DescribeFunction Parameters With Variadic Template Types
I want to write a template function which takes in a function pointer and all but the last 2 arguments to that function. Something like this:

```<code>template <typename T, typename... ARGS>
void foo(void(*func)(ARGS..., T*, int*), ARGS... params);
</code>```

I'd like to do something like the following:

Given a function of the signature void bar(bool, char*, int*), I'd like to call: foo(bar, false)

Given a function of the signature void bar(bool, int*, int*), I'd like to call: foo(bar, false)

Given a function of the signature void bar(char*, int*), I'd like to call: foo(bar)

But when I try to define foo like this I get the error:

error C2672: foo: no matching overloaded function found

  error C2784: void foo(void (__cdecl *)(ARGS...,T* ,int *),ARGS...): could not deduce template argument for void (__cdecl* )(ARGS...,T *,int* ) from void (bool,char *,int* )

What can I do to help with the deduction?

答:
It seems to me that you're looking something as follows

```<code>template <std::size_t N, typename ...Ts>
using revType = std::tuple_element_t<sizeof...(Ts)-1u-N, std::tuple<Ts...>>;

template <typename ... As1, typename ... As2,
          typename T = revType<1u, As1...>,
          std::enable_if_t<std::is_same_v<
             std::tuple<As1...>, std::tuple<As2..., T, int*>>, int> = 0>
void foo(void(*f)(As1...), As2 ... as)
 {
 }
</code>```

As pointed by Bitwize (thanks) this solution has a great limits: require that the arguments of foo() (of types As2...) are deduced exactly as the corresponding types for As1.... So if As1... start with an std::string, you can't pass "abc" as first As2... parameter because "abc" is a char const [4] that is convertible but different to std::string.

As suggested by Bitwize itself, you can avoid this problem using std::is_convertible, instead std::is_same_v, over tuples taking advantage from std::tuple converting constructor, so

```<code>template <typename ... As1, typename ... As2,
          typename T = revType<1u, As1...>,
          std::enable_if_t<std::is_convertible_v<
             std::tuple<As1...>, std::tuple<As2..., T, int*>>, int> = 0>
void foo(void(*f)(As1...), As2 ... as)
 {
 }
</code>```

In this case, if you want to be sure that the last As1... type is exactly int * (and not only convertible), you can add the check

```<code>template <typename ... As1, typename ... As2,
          typename T = revType<1u, As1...>,
          typename U = revType<0u, As1...>,
          std::enable_if_t<
                std::is_convertible_v<std::tuple<As1...>,
                                      std::tuple<As2..., T, int*>>
             && std::is_same_v<int *, U>, int> = 0>
void foo(void(*f)(As1...), As2 ... as)
 {
 }
</code>```

Body:
I want to write a template function which takes in a function pointer and all but the last 2 arguments to that function. Something like this:

template <typename T, typename... ARGS>
void foo(void(*func)(ARGS..., T*, int*), ARGS... params);

I'd like to do something like the following:

Given a function of the signature void bar(bool, char*, int*), I'd like to call: foo(bar, false)

Given a function of the signature void bar(bool, int*, int*), I'd like to call: foo(bar, false)

Given a function of the signature void bar(char*, int*), I'd like to call: foo(bar)

But when I try to define foo like this I get the error:

error C2672: foo: no matching overloaded function found

  error C2784: void foo(void (__cdecl *)(ARGS...,T* ,int *),ARGS...): could not deduce template argument for void (__cdecl* )(ARGS...,T *,int* ) from void (bool,char *,int* )

What can I do to help with the deduction?

Body:
It seems to me that you're looking something as follows

template <std::size_t N, typename ...Ts>
using revType = std::tuple_element_t<sizeof...(Ts)-1u-N, std::tuple<Ts...>>;

template <typename ... As1, typename ... As2,
          typename T = revType<1u, As1...>,
          std::enable_if_t<std::is_same_v<
             std::tuple<As1...>, std::tuple<As2..., T, int*>>, int> = 0>
void foo(void(*f)(As1...), As2 ... as)
 {
 }

As pointed by Bitwize (thanks) this solution has a great limits: require that the arguments of foo() (of types As2...) are deduced exactly as the corresponding types for As1.... So if As1... start with an std::string, you can't pass "abc" as first As2... parameter because "abc" is a char const [4] that is convertible but different to std::string.

As suggested by Bitwize itself, you can avoid this problem using std::is_convertible, instead std::is_same_v, over tuples taking advantage from std::tuple converting constructor, so

template <typename ... As1, typename ... As2,
          typename T = revType<1u, As1...>,
          std::enable_if_t<std::is_convertible_v<
             std::tuple<As1...>, std::tuple<As2..., T, int*>>, int> = 0>
void foo(void(*f)(As1...), As2 ... as)
 {
 }

In this case, if you want to be sure that the last As1... type is exactly int * (and not only convertible), you can add the check

template <typename ... As1, typename ... As2,
          typename T = revType<1u, As1...>,
          typename U = revType<0u, As1...>,
          std::enable_if_t<
                std::is_convertible_v<std::tuple<As1...>,
                                      std::tuple<As2..., T, int*>>
             && std::is_same_v<int *, U>, int> = 0>
void foo(void(*f)(As1...), As2 ... as)
 {
 }


问:
soffice.exe to Convert odt to PDF/A
trying to convert ODT to PDF using soffice.exe, but it always give me only PDF and not PDF/A...
Is there a way to convert odt to PDF/A using soffice.exe ?

答:
I understand that whatever format you successfully used last, to export a document as a Pdf, will be the default. So export something as a Pdf/A and then try again from the command line.

I have tried the unoconv option:

```<code>unoconv -f pdf -eFormsType=1 -eSelectedPdfVersion=1 Some.odt
</code>```

and whilst it purports to work, the result give errors when tested as a Pdf/A file.

Whereas, the same file run through the:

```<code>soffice --headless --convert-to pdf Some.odt
</code>```

command does pass the test but only if the previous export was successfully made to a Pdf/A file.

Testing was performed using pdfa from http://www.pdftron.com/pdfamanager/downloads.html

Title: soffice.exe to Convert odt to PDF/A

Body:
I understand that whatever format you successfully used last, to export a document as a Pdf, will be the default. So export something as a Pdf/A and then try again from the command line.

I have tried the unoconv option:

unoconv -f pdf -eFormsType=1 -eSelectedPdfVersion=1 Some.odt

and whilst it purports to work, the result give errors when tested as a Pdf/A file.

Whereas, the same file run through the:

soffice --headless --convert-to pdf Some.odt

command does pass the test but only if the previous export was successfully made to a Pdf/A file.

Testing was performed using pdfa from http://www.pdftron.com/pdfamanager/downloads.html


问:
How to stop UITableViewCell flashing to white when deselecting?
I have the common pattern of a UITableView with a secondary view controller which gets pushed over the top when a row is selected. To give the user some context when they dismiss the second view controller and return to the tableview, that first view controller has this:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if let index = tableView.indexPathForSelectedRow {
        tableView.deselectRow(at: index, animated: animated)
    }
}
</code>```

That results in this unintended and jarring transition in which the cell being deselected fades it's background away, before snapping back to normal :

My expectation was that it would transition from the partially subdued state selection left it in directly back to the normal, dark state.

(The cell is very much a work-in-progress - it's far from finished)

Following the suggestions here isn't really an option as I do want to preserve the context hint and the cell as a whole should continue to have a white background.

In response to Rico's question, the cell is created as a .swift and .xib pair, the hierarchy of views being:

The Swift does very little - sets .textInsets on the two labels, draws the disclosure indicator in the button.

答:
Instead of deselecting the row in viewWillAppear(_:), call deselectRow(at:animated:) inside the tableView(_:didSelectRowAt:) method, i.e

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
    //Your rest of the code...
}
</code>```

Edit-1:

In viewWillAppear(_:), you need to deselect the cell in UIView.animate(withDuration:animations:) with animation set to true in deselectRow(at:animated:), i.e.

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    UIView.animate(withDuration: 0.2) {
        if let indexPath = self.tableView.indexPathForSelectedRow {
            self.tableView.deselectRow(at: indexPath, animated: true)
        }
    }
}
</code>```

Body:
I have the common pattern of a UITableView with a secondary view controller which gets pushed over the top when a row is selected. To give the user some context when they dismiss the second view controller and return to the tableview, that first view controller has this:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    if let index = tableView.indexPathForSelectedRow {
        tableView.deselectRow(at: index, animated: animated)
    }
}

That results in this unintended and jarring transition in which the cell being deselected fades it's background away, before snapping back to normal :

My expectation was that it would transition from the partially subdued state selection left it in directly back to the normal, dark state.

(The cell is very much a work-in-progress - it's far from finished)

Following the suggestions here isn't really an option as I do want to preserve the context hint and the cell as a whole should continue to have a white background.

In response to Rico's question, the cell is created as a .swift and .xib pair, the hierarchy of views being:

The Swift does very little - sets .textInsets on the two labels, draws the disclosure indicator in the button.

Body:
Instead of deselecting the row in viewWillAppear(_:), call deselectRow(at:animated:) inside the tableView(_:didSelectRowAt:) method, i.e

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
    //Your rest of the code...
}

Edit-1:

In viewWillAppear(_:), you need to deselect the cell in UIView.animate(withDuration:animations:) with animation set to true in deselectRow(at:animated:), i.e.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    UIView.animate(withDuration: 0.2) {
        if let indexPath = self.tableView.indexPathForSelectedRow {
            self.tableView.deselectRow(at: indexPath, animated: true)
        }
    }
}


问:
how to surround a word using System.Text.RegularExpressions.Regex
I've seen this topic:
How to surround text with brackets using regex?
but that's on ruby and I don't know the analog for C#
I tried

```<code>text = System.Text.RegularExpressions.Regex.Replace(text, ' '  + SpecialWord + ' ', " \"\0\" ", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
</code>```

but that didn't insert my matched word. So how do I surround my matched word with quotes?

答:
use $ instead of \ for the backreference. Also, put your special word in parenthesis and reference that sub group, otherwise, you will get the complete matched string:

```<code>text = System.Text.RegularExpressions.Regex.Replace(
                         text, "\\b("  + SpecialWord + ")\\b", " \"$1\" ",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
</code>```

Explanation:

\b is a word boundary, i.e. a space, the end of the string, a full stop etc.

$0 will match the whole match, i.e. including the word boundary, whereas $1 matches the first sub group, i.e. the part in the parenthesis.

Body:
I've seen this topic:
How to surround text with brackets using regex?
but that's on ruby and I don't know the analog for C#
I tried

text = System.Text.RegularExpressions.Regex.Replace(text, ' '  + SpecialWord + ' ', " \"\0\" ", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

but that didn't insert my matched word. So how do I surround my matched word with quotes?

Body:
use $ instead of \ for the backreference. Also, put your special word in parenthesis and reference that sub group, otherwise, you will get the complete matched string:

text = System.Text.RegularExpressions.Regex.Replace(
                         text, "\\b("  + SpecialWord + ")\\b", " \"$1\" ",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

Explanation:

\b is a word boundary, i.e. a space, the end of the string, a full stop etc.

$0 will match the whole match, i.e. including the word boundary, whereas $1 matches the first sub group, i.e. the part in the parenthesis.