问:
How to properly use the sheets.spreadsheets.values.GET in the Google Sheets API?
So I'm a first year programming student with near 0 experience so please forgive me if I'm going at this the wrong way.
I'm building a website that will take an array of strings and display them as well as run some code relating to those strings. For this assignment, I have to use an API, so I wanted to use the google sheets API in order to achieve my idea. I understand that I need to use the command

```<code>sheets.spreadsheets.values.GET
</code>```

to get my spreadsheet data as a JS array, which is perfect for what I want to do. Inside the Google dev console, I am able to test the command and receive my array, so I know that I have the API se t up correctly.
However when I go to my website, which has Jquery linked fyi, and I put in the get command into the console I get the error:

```<code>Uncaught SyntaxError: Unexpected identifier
</code>```

This is weird to me since I'm just copy-pasting from the Dev console into the early version of my website this command:

```<code>GET https://sheets.googleapis.com/v4/spreadsheets/MY_Spread_Sheet_ID/values/Sheet1!A1%3AA200?valueRenderOption=FORMATTED_VALUE&key={ApiKeyCode}
</code>```

I was under the impression that the console should have reported back the contents of my spreadsheet as an array, but instead I get the error.

At first I thought that I must have needed to link the google sheets API to my code like you would with JQuery but I can't find documentation on how to do that, so that might be my problem.

Sorry about my poor English skills.

答: Could you include your code in your post? FYI, the function spreadsheets.values.get() does not return directly a value, but instead it calls a callback function with the returned values.</p>

Body:
So I'm a first year programming student with near 0 experience so please forgive me if I'm going at this the wrong way.
I'm building a website that will take an array of strings and display them as well as run some code relating to those strings. For this assignment, I have to use an API, so I wanted to use the google sheets API in order to achieve my idea. I understand that I need to use the command

sheets.spreadsheets.values.GET

to get my spreadsheet data as a JS array, which is perfect for what I want to do. Inside the Google dev console, I am able to test the command and receive my array, so I know that I have the API se t up correctly.
However when I go to my website, which has Jquery linked fyi, and I put in the get command into the console I get the error:

Uncaught SyntaxError: Unexpected identifier

This is weird to me since I'm just copy-pasting from the Dev console into the early version of my website this command:

GET https://sheets.googleapis.com/v4/spreadsheets/MY_Spread_Sheet_ID/values/Sheet1!A1%3AA200?valueRenderOption=FORMATTED_VALUE&key={ApiKeyCode}

I was under the impression that the console should have reported back the contents of my spreadsheet as an array, but instead I get the error.

At first I thought that I must have needed to link the google sheets API to my code like you would with JQuery but I can't find documentation on how to do that, so that might be my problem.

Sorry about my poor English skills.


来源: stackexchange

问:
How to run an SQL query from JavaScript
This question is pretty much what I am trying to do, but I cannot understand how to use it in my context.

I have tried the marked answer and the answer submitted by xdazz. Both of these answers seem to send the variables from the client-side to the php script through POST. When I attempt this, it simply does not hit my alerts, which leads me to believe that the php script receiving the POST variables is never being executed.

Here is the function which runs when I click a button on my js canvas

```<code>function updateLeaderboard()
{
    alert("before");

$.post("process.php", { postantNum: antNum, postantRate: antRate },
    function(data)
    {
        alert(data);
    } );

    alert("after");
}
</code>```

Here is the process.php file

<?php

$antNum = $_POST['antNum'];
$antRate = $_POST['antRate'];
echo $antNum;
echo $antRate;
$con=mysqli_connect("localhost","root","pass","login");

mysqli_query($con,"UPDATE userdata SET `words`='$antNum' WHERE `player`='$antRate'");

?>
```

<p>HTML running the javascript:</p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>p5.js example</title>
    <style> body {padding: 0; margin: 0;} </style>
    <script src="../p5.min.js"></script>
    <script src="../addons/p5.dom.js"></script>
    <script src="../addons/p5.dom.min.js"></script>
    <script src="../addons/p5.sound.min.js"></script>
    <script src="antclicker.js"></script>
  </head>
  <body>
  </body>
</html>
</code>```

I wish to be able to send in antNum and antRate from the client-side js game I have created to the database for storage.
There are no error messages, I just know it never gets to the echos in the process.php and never hits the after alert, only the before alert is triggered.

EDIT:

Now since I have dipped my feet into chromes tools, I have discovered that on the line $.post("process.php", { postantNum: antNum, postantRate: antRate },
(yes I have changed the code a little bit) I get the error : ReferenceError: $ is not defined, how can it be singling out the "$". I'm guessing this probably means that there are some syntax errors nearby.

答:
First off in the HTML I did not know I needed to include

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</code>```

as I did not know I was using ajax, this is why the $ was undefined.

the updateLeaderboard function should look like this.

```<code>function updateLeaderboard()
{
    alert("before");

$.post("process.php", { antNum, antRate },
    function(data)
    {
        alert(data);
    } );

    alert("after");
}
</code>```

antNum and antRate are just vars which are previously defined.

and the process.php should look like

<?php

$antNum = $_POST['antNum'];
$antRate = $_POST['antRate'];

$con=mysqli_connect("localhost","root","pass","login");

mysqli_query($con,"UPDATE userdata SET `antNum`='$antNum' , `antRate`='$antRate' WHERE `player`='bob'");

?>
```

just swap bob out for the user in question.

PS. This was also a factor in helping me find the answer, by first allowing me to notice the $ was undefined.

ContentLicense: CC BY-SA 4.0

Title: How to run an SQL query from JavaScript

Body:
This question is pretty much what I am trying to do, but I cannot understand how to use it in my context.

I have tried the marked answer and the answer submitted by xdazz. Both of these answers seem to send the variables from the client-side to the php script through POST. When I attempt this, it simply does not hit my alerts, which leads me to believe that the php script receiving the POST variables is never being executed.

Here is the function which runs when I click a button on my js canvas

function updateLeaderboard()
{
    alert("before");

$.post("process.php", { postantNum: antNum, postantRate: antRate },
    function(data)
    {
        alert(data);
    } );

    alert("after");
}

Here is the process.php file

<?php

$antNum = $_POST['antNum'];
$antRate = $_POST['antRate'];
echo $antNum;
echo $antRate;
$con=mysqli_connect("localhost","root","pass","login");

mysqli_query($con,"UPDATE userdata SET `words`='$antNum' WHERE `player`='$antRate'");

?>

HTML running the javascript:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>p5.js example</title>

I wish to be able to send in antNum and antRate from the client-side js game I have created to the database for storage.
There are no error messages, I just know it never gets to the echos in the process.php and never hits the after alert, only the before alert is triggered.

EDIT:

Now since I have dipped my feet into chromes tools, I have discovered that on the line $.post("process.php", { postantNum: antNum, postantRate: antRate },
(yes I have changed the code a little bit) I get the error : ReferenceError: $ is not defined, how can it be singling out the "$". I'm guessing this probably means that there are some syntax errors nearby.

Body:
First off in the HTML I did not know I needed to include

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

as I did not know I was using ajax, this is why the $ was undefined.

the updateLeaderboard function should look like this.

function updateLeaderboard()
{
    alert("before");

$.post("process.php", { antNum, antRate },
    function(data)
    {
        alert(data);
    } );

    alert("after");
}

antNum and antRate are just vars which are previously defined.

and the process.php should look like

<?php

$antNum = $_POST['antNum'];
$antRate = $_POST['antRate'];

$con=mysqli_connect("localhost","root","pass","login");

mysqli_query($con,"UPDATE userdata SET `antNum`='$antNum' , `antRate`='$antRate' WHERE `player`='bob'");

?>

just swap bob out for the user in question.

PS. This was also a factor in helping me find the answer, by first allowing me to notice the $ was undefined.


问:
Multidimensional lookup (2 rows and 1 column) with row labels out-of-line
I need to create a function that will fill in cells Sheet2!G25:P25 according to three criteria: project type, criteria type, and date.  The problem is that the criteria in Sheet 1 aren't lined up to conveniently use a VLOOKUP or INDEX MATCH.  I know I'm supposed to list the formula that doesn't work but I honestly haven't even been able to get close.  I've been primarily working on variations of the SUMPRODUCT such as

```<code>=SUMPRODUCT((Sheet1!A3:A19=Sheet2!A25)*(Sheet1!D3:D19=Sheet2!B25)*(Sheet1!G2:P2=Sheet2!G23)*Sheet1!G3:P19)
</code>```

but that obviously won't work since the project type and criteria type aren't on the same row as the data I need.  A work around I've been trying is to OFFSET the location of the cell found in the SUMPRODUCT project type and criteria type arrays but restrictions within the OFFSET function has set me back.  For example, the reference section of the OFFSET function cannot be a function even if the function pulls a cell location (OFFSET(CELL("address",INDEX MATCH),0,0).  The goal of this was to trick the SUMPRODUCT function into thinking that the 2 row criteria were on the same row. You guys are geniuses when it comes to this stuff so I'm sure I'm missing something.

```<code>=SUMPRODUCT((Sheet1!A3:A19=Sheet2!A25)*(Sheet1!D3:D19=Sheet2!B25)*(Sheet1!G2:P2=Sheet2!G23)*Sheet1!G3:P19)
</code>```

答:
Well, the following works for me on the basis or your example.
The condition here is that the row separation between your project and the criteria is always 4 rows apart

The formula on Sheet 2 is

```<code>{=INDEX(Sheet1!$A$1:$U$19,MATCH(1,(Sheet1!$A$1:$A$15=$A$3)*(Sheet1!$D$4:$D$18=$B$3),0)+1,MATCH(H1,Sheet1!$A$1:$U$1,0))}
</code>```

This is an array formula, enter it by usind Ctrl+Shift+Enter

On sheet1 if positioned the data same as on your picture, that means the first date is in H1 on Sheet 1
The first formula entered on Sheet 2 is in cell H3

The "trick" I used is to simply offset the second search array:

Project uses A$1:$A$15

Criteria uses $D$4:$D$18

Body:
I need to create a function that will fill in cells Sheet2!G25:P25 according to three criteria: project type, criteria type, and date.  The problem is that the criteria in Sheet 1 aren't lined up to conveniently use a VLOOKUP or INDEX MATCH.  I know I'm supposed to list the formula that doesn't work but I honestly haven't even been able to get close.  I've been primarily working on variations of the SUMPRODUCT such as

=SUMPRODUCT((Sheet1!A3:A19=Sheet2!A25)*(Sheet1!D3:D19=Sheet2!B25)*(Sheet1!G2:P2=Sheet2!G23)*Sheet1!G3:P19)

but that obviously won't work since the project type and criteria type aren't on the same row as the data I need.  A work around I've been trying is to OFFSET the location of the cell found in the SUMPRODUCT project type and criteria type arrays but restrictions within the OFFSET function has set me back.  For example, the reference section of the OFFSET function cannot be a function even if the function pulls a cell location (OFFSET(CELL("address",INDEX MATCH),0,0).  The goal of this was to trick the SUMPRODUCT function into thinking that the 2 row criteria were on the same row. You guys are geniuses when it comes to this stuff so I'm sure I'm missing something.

=SUMPRODUCT((Sheet1!A3:A19=Sheet2!A25)*(Sheet1!D3:D19=Sheet2!B25)*(Sheet1!G2:P2=Sheet2!G23)*Sheet1!G3:P19)

Body:
Well, the following works for me on the basis or your example.
The condition here is that the row separation between your project and the criteria is always 4 rows apart

The formula on Sheet 2 is

{=INDEX(Sheet1!$A$1:$U$19,MATCH(1,(Sheet1!$A$1:$A$15=$A$3)*(Sheet1!$D$4:$D$18=$B$3),0)+1,MATCH(H1,Sheet1!$A$1:$U$1,0))}

This is an array formula, enter it by usind Ctrl+Shift+Enter

On sheet1 if positioned the data same as on your picture, that means the first date is in H1 on Sheet 1
The first formula entered on Sheet 2 is in cell H3

The "trick" I used is to simply offset the second search array:

Project uses A$1:$A$15

Criteria uses $D$4:$D$18


问:
difference between 2 dates in days saved into new column as float
I have a python dataframe with 2 columns that contain dates as strings e.g. start_date "2002-06-12" and end_date "2009-03-01". I would like to calculate the difference (days) between these 2 columns for each row and save the results into a new column called for example time_diff of type float.

I have tried:

```<code>df["time_diff"] = (pd.Timestamp(df.end_date) - pd.Timestamp(df.start_date )).astype("timedelta64[d]")
pd.to_numeric(df["time_diff"])
</code>```

based on some tutorials but this gives TypeError: Cannot convert input for the first line. What do I need to change to get this running?

答:
You can also do it by converting your columns into date and then computing the difference : </p>

```<code>from datetime import datetime

df = pd.DataFrame({'Start Date' : ['2002-06-12', '2002-06-12' ], 'End date' : ['2009-03-01', '2009-03-06']})

df['Start Date'] = [  datetime.strptime(x, "%Y-%m-%d").date() for x in df['Start Date'] ]
df['End date'] = [ datetime.strptime(x, "%Y-%m-%d").date() for x in df['End date'] ]

df['Diff'] = df['End date'] - df['Start Date']
</code>```

<p>Out : </p>

```<code>End date    Start Date  Diff
0   2009-03-01  2002-06-12  2454 days
1   2009-03-06  2002-06-12  2459 days
</code>```

Body:
I have a python dataframe with 2 columns that contain dates as strings e.g. start_date "2002-06-12" and end_date "2009-03-01". I would like to calculate the difference (days) between these 2 columns for each row and save the results into a new column called for example time_diff of type float.

I have tried:

df["time_diff"] = (pd.Timestamp(df.end_date) - pd.Timestamp(df.start_date )).astype("timedelta64[d]")
pd.to_numeric(df["time_diff"])

based on some tutorials but this gives TypeError: Cannot convert input for the first line. What do I need to change to get this running?

Body:
You can also do it by converting your columns into date and then computing the difference :

from datetime import datetime

df = pd.DataFrame({'Start Date' : ['2002-06-12', '2002-06-12' ], 'End date' : ['2009-03-01', '2009-03-06']})

df['Start Date'] = [  datetime.strptime(x, "%Y-%m-%d").date() for x in df['Start Date'] ]
df['End date'] = [ datetime.strptime(x, "%Y-%m-%d").date() for x in df['End date'] ]

df['Diff'] = df['End date'] - df['Start Date']

Out :

End date    Start Date  Diff
0   2009-03-01  2002-06-12  2454 days
1   2009-03-06  2002-06-12  2459 days


问:
How to write a result of a variable type list in logfile?
I'm setting a code in python 2.7 where I have to write the result of a list variable in logfile

I tried logFile.write(.format(var))

also logFile.write.print(var)

```<code>var = []
logFile.write(var)
</code>```

答:
This can be achieved using the python's join() method:

```<code>logFile.write("\n".join(var))
</code>```

Try this and tell me if this works.

Requesting old members to help me properly formulate the answer.

Body:
I'm setting a code in python 2.7 where I have to write the result of a list variable in logfile

I tried logFile.write(.format(var))

also logFile.write.print(var)

var = []
logFile.write(var)

Body:
This can be achieved using the python's join() method:

logFile.write("\n".join(var))

Try this and tell me if this works.

Requesting old members to help me properly formulate the answer.


问:
How to continue running a VBA macro when an SAP popup message tells us that there is no data found?
When the sap script searches for data via SAP and finds nothing, it sends us a pop-up message saying "that it has not found any data", how to keep the macro running because later there are other transactions.

```<code> Sub FOS()
 ...

On Error GoTo ConsoleAbs
Set Sapgui = GetObject("SAPGUI")
On Error GoTo 0

'transaction1
session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "S_ALR_87011964"
session.findById("wnd[0]/tbar[0]/btn[0]").press
session.findById("wnd[0]/usr/ctxtBUKRS-LOW").Text = "0092"
...

'transaction2

session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "S_ALR_87012039"
session.findById("wnd[0]/tbar[0]/btn[0]").press
...

End Sub
</code>```

I've been trying

```<code>On Error GoTo ConsoleAbs
Set Sapgui = GetObject("SAPGUI")
On Error GoTo 0
</code>```

but I'm not sure that's the right solution.

答:
You could try the following.

for example:

```<code>Sub FOS()
Set SapGuiAuto = GetObject("SAPGUI")
Set SAP_Application = SapGuiAuto.GetScriptingEngine
Set Connection = SAP_Application.Children(0)
Set session = Connection.Children(0)

session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "/nS_ALR_87011964"
session.findById("wnd[0]").sendVKey 0
...
session.findById("wnd[0]/tbar[1]/btn[8]").press
If session.ActiveWindow.Name = "wnd[1]" Then
   If session.findById("wnd[1]").Text = "Information" Then session.findById("wnd[1]/tbar[0]/btn[0]").press
else
  'do something
end if

session.findById("wnd[0]/tbar[0]/okcd").Text = "S_ALR_87012039"
session.findById("wnd[0]/tbar[0]/btn[0]").press
...
session.findById("wnd[0]/tbar[1]/btn[8]").press
If session.ActiveWindow.Name = "wnd[1]" Then
   If session.findById("wnd[1]").Text = "Information" Then session.findById("wnd[1]/tbar[0]/btn[0]").press
else
  'do something
end if
End Sub
</code>```

Regards, ScriptMan

Body:
When the sap script searches for data via SAP and finds nothing, it sends us a pop-up message saying "that it has not found any data", how to keep the macro running because later there are other transactions.

 Sub FOS()
 ...

On Error GoTo ConsoleAbs
Set Sapgui = GetObject("SAPGUI")
On Error GoTo 0

'transaction1
session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "S_ALR_87011964"
session.findById("wnd[0]/tbar[0]/btn[0]").press
session.findById("wnd[0]/usr/ctxtBUKRS-LOW").Text = "0092"
...

'transaction2

session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "S_ALR_87012039"
session.findById("wnd[0]/tbar[0]/btn[0]").press
...

End Sub

I've been trying

On Error GoTo ConsoleAbs
Set Sapgui = GetObject("SAPGUI")
On Error GoTo 0

but I'm not sure that's the right solution.

Body:
You could try the following.

for example:

Sub FOS()
Set SapGuiAuto = GetObject("SAPGUI")
Set SAP_Application = SapGuiAuto.GetScriptingEngine
Set Connection = SAP_Application.Children(0)
Set session = Connection.Children(0)

session.findById("wnd[0]").maximize
session.findById("wnd[0]/tbar[0]/okcd").Text = "/nS_ALR_87011964"
session.findById("wnd[0]").sendVKey 0
...
session.findById("wnd[0]/tbar[1]/btn[8]").press
If session.ActiveWindow.Name = "wnd[1]" Then
   If session.findById("wnd[1]").Text = "Information" Then session.findById("wnd[1]/tbar[0]/btn[0]").press
else
  'do something
end if

session.findById("wnd[0]/tbar[0]/okcd").Text = "S_ALR_87012039"
session.findById("wnd[0]/tbar[0]/btn[0]").press
...
session.findById("wnd[0]/tbar[1]/btn[8]").press
If session.ActiveWindow.Name = "wnd[1]" Then
   If session.findById("wnd[1]").Text = "Information" Then session.findById("wnd[1]/tbar[0]/btn[0]").press
else
  'do something
end if
End Sub

Regards, ScriptMan


问:
Remove the first and last lines properties in the paper Itext7
I need to remove property in Text (setRise) , if t.setRise(+-) gets out of fields paper.

```<code>    PdfDocument pdfDoc = new PdfDocument(pdfWriter);
    Document doc = new Document(pdfDoc, PageSize.A5);
    doc.setMargins(0,0,0,36);
    for (int i = 0; i <50 ; i++) {
        Text t = new Text("hello " + i);
        if(i ==0){
            t.setTextRise(7);
        }
        if(i==31){
            t.setTextRise(-35);
        }
    Paragraph p = new Paragraph(t);
    p.setNextRenderer(new ParagraphRen(p,doc));
    p.setFixedLeading(fixedLeading);

     doc.add(p);
    }
    doc.close();
}

class ParagraphRen extends ParagraphRenderer{
private float heightDoc;
private float marginTop;
private float marginBot;

public ParagraphRen(Paragraph modelElement, Document doc) {
    super(modelElement);
    this.heightDoc =doc.getPdfDocument().getDefaultPageSize().getHeight();
    this.marginTop = doc.getTopMargin();
   this.marginBot = doc.getBottomMargin();

}

@Override
public void drawChildren(DrawContext drawContext) {
    super.drawChildren(drawContext);
    Rectangle rect = this.getOccupiedAreaBBox();
    List<IRenderer> childRenderers = this.getChildRenderers();
    //check first line
    if(rect.getTop()<=heightDoc- marginTop) {
        for (IRenderer iRenderer : childRenderers) {
            if (iRenderer.getModelElement().hasProperty(72)) {
            Object property = iRenderer.getModelElement().getProperty(72);
            float v = (Float) property + rect.getTop();
            //check text  more AreaPage
            if(v >heightDoc){
                iRenderer.getModelElement().deleteOwnProperty(72);
            }

        }
    }
    }
    //check last line
      if(rect.getBottom()-marginBot-rect.getHeight()*2<0){
        for (IRenderer iRenderer : childRenderers) {

            if (iRenderer.getModelElement().hasProperty(72)) {
                Object property = iRenderer.getModelElement().getProperty(72);

                      //if setRise(-..) more margin bottom  setRise remove
                if(rect.getBottom()-marginBot-rect.getHeight()+(Float) property<0)
                    iRenderer.getModelElement().deleteOwnProperty(72);
                }

            }
        }

    }
</code>```

}

Here i check if first lines with setRise more the paper area I remove setRise property.

And if last lines with serRise(-35) more then margin bottom I remove it.

But it doesn't work. Properties don't remove.

答:
Your problem is as follows: drawChildren method gets called after rendering has been done. At this stage iText usually doesn't consider properties of any elements: it just places the element in its occupied area, which has been calculated before, at layout() stage.

You can overcome it with layout emulation.

Let's add all your paragraphs to a div rather than directly to the document. Then emulate adding this div to the document:

```<code>LayoutResult result = div.createRendererSubTree().setParent(doc.getRenderer()).layout(new LayoutContext(new LayoutArea(0, PageSize.A5)));
</code>```

In the snippet above I've tried to layout our div on a A5-sized document.

Now you can consider the result of layout and change some elements, which will be then processed for real with Document#add. For example, to get the 30th layouted paragraph one can use:

((DivRenderer)result.getSplitRenderer()).getChildRenderers().get(30);

Some more tips:
split renderer represent the part of the content which iText can place on the area, overflow - the content which overflows.

Body:
I need to remove property in Text (setRise) , if t.setRise(+-) gets out of fields paper.

    PdfDocument pdfDoc = new PdfDocument(pdfWriter);
    Document doc = new Document(pdfDoc, PageSize.A5);
    doc.setMargins(0,0,0,36);
    for (int i = 0; i <50 ; i++) {
        Text t = new Text("hello " + i);
        if(i ==0){
            t.setTextRise(7);
        }
        if(i==31){
            t.setTextRise(-35);
        }
    Paragraph p = new Paragraph(t);
    p.setNextRenderer(new ParagraphRen(p,doc));
    p.setFixedLeading(fixedLeading);

     doc.add(p);
    }
    doc.close();
}

class ParagraphRen extends ParagraphRenderer{
private float heightDoc;
private float marginTop;
private float marginBot;

public ParagraphRen(Paragraph modelElement, Document doc) {
    super(modelElement);
    this.heightDoc =doc.getPdfDocument().getDefaultPageSize().getHeight();
    this.marginTop = doc.getTopMargin();
   this.marginBot = doc.getBottomMargin();

}

@Override
public void drawChildren(DrawContext drawContext) {
    super.drawChildren(drawContext);
    Rectangle rect = this.getOccupiedAreaBBox();
    List<IRenderer> childRenderers = this.getChildRenderers();
    //check first line
    if(rect.getTop()<=heightDoc- marginTop) {
        for (IRenderer iRenderer : childRenderers) {
            if (iRenderer.getModelElement().hasProperty(72)) {
            Object property = iRenderer.getModelElement().getProperty(72);
            float v = (Float) property + rect.getTop();
            //check text  more AreaPage
            if(v >heightDoc){
                iRenderer.getModelElement().deleteOwnProperty(72);
            }

        }
    }
    }
    //check last line
      if(rect.getBottom()-marginBot-rect.getHeight()*2<0){
        for (IRenderer iRenderer : childRenderers) {

            if (iRenderer.getModelElement().hasProperty(72)) {
                Object property = iRenderer.getModelElement().getProperty(72);

                      //if setRise(-..) more margin bottom  setRise remove
                if(rect.getBottom()-marginBot-rect.getHeight()+(Float) property<0)
                    iRenderer.getModelElement().deleteOwnProperty(72);
                }

            }
        }

    }

}

Here i check if first lines with setRise more the paper area I remove setRise property.

And if last lines with serRise(-35) more then margin bottom I remove it.

But it doesn't work. Properties don't remove.

Body:
Your problem is as follows: drawChildren method gets called after rendering has been done. At this stage iText usually doesn't consider properties of any elements: it just places the element in its occupied area, which has been calculated before, at layout() stage.

You can overcome it with layout emulation.

Let's add all your paragraphs to a div rather than directly to the document. Then emulate adding this div to the document:

LayoutResult result = div.createRendererSubTree().setParent(doc.getRenderer()).layout(new LayoutContext(new LayoutArea(0, PageSize.A5)));

In the snippet above I've tried to layout our div on a A5-sized document.

Now you can consider the result of layout and change some elements, which will be then processed for real with Document#add. For example, to get the 30th layouted paragraph one can use:

((DivRenderer)result.getSplitRenderer()).getChildRenderers().get(30);

Some more tips:
split renderer represent the part of the content which iText can place on the area, overflow - the content which overflows.


问:
AirFlow scheduler - run date
I have a DAG that runs weekly on every Monday at 11am. It ran on 13/05, it was turned off on 20/05 and was turned on again on 27/05.

```<code>dag = DAG(
    'my_dag',
    description='my_desc',
    default_args=args,
    schedule_interval='0 11 * * 1',
    max_active_runs=1,
    catchup=False)
</code>```

My question is: on 27/05 DAG ran but "run date" was set to 20/05 and I don't know why. Is it because it was turned off on 20/05 and DAG got the "last scheduled date"? In this case, next week (June 3) it will run with "run date" set to 27/05 or 03/06?

What will be execution_date and next_execution_date in this case on June 3?

Thanks!

答:
If you watch on all running tasks of current dag, you will see that at Run show datetime of previous running task defined in schedule_interval. Started and Ended show running real datetime of current task.
In the next week (June 3) you will see in Run this date `2019-05-27T11:00:00'

Title: AirFlow scheduler - run date

Body:
I have a DAG that runs weekly on every Monday at 11am. It ran on 13/05, it was turned off on 20/05 and was turned on again on 27/05.

dag = DAG(
    'my_dag',
    description='my_desc',
    default_args=args,
    schedule_interval='0 11 * * 1',
    max_active_runs=1,
    catchup=False)

My question is: on 27/05 DAG ran but "run date" was set to 20/05 and I don't know why. Is it because it was turned off on 20/05 and DAG got the "last scheduled date"? In this case, next week (June 3) it will run with "run date" set to 27/05 or 03/06?

What will be execution_date and next_execution_date in this case on June 3?

Thanks!


问:
Bundle install could not find compatible versions for gem "bundler"
When I type bundle install I got this error. I tried to find solution but nothing solve my case. Please help me.</p>

```<code> Bundler could not find compatible versions for gem "bundler":
      In Gemfile:
        rails (= 4.1.8) was resolved to 4.1.8, which depends on
          bundler (< 2.0, >= 1.3.0)

      Current Bundler version:
        bundler (2.0.1)
    This Gemfile requires a different version of Bundler.
    Perhaps you need to update Bundler by running `gem install bundler`?

    Could not find gem 'bundler (< 2.0, >= 1.3.0)', which is required by gem 'rails
    (= 4.1.8)', in any of the sources.

    Bundler could not find compatible versions for gem "rails":
      In Gemfile:
        rails (= 4.1.8)

        animate-rails was resolved to 1.0.10, which depends on
          rails
</code>```

答:
Try to use

gem install bundler -v 1.17.3
bundle _1.17.3_ install
```

Body:
When I type bundle install I got this error. I tried to find solution but nothing solve my case. Please help me.

 Bundler could not find compatible versions for gem "bundler":
      In Gemfile:
        rails (= 4.1.8) was resolved to 4.1.8, which depends on
          bundler (< 2.0, >= 1.3.0)

      Current Bundler version:
        bundler (2.0.1)
    This Gemfile requires a different version of Bundler.
    Perhaps you need to update Bundler by running `gem install bundler`?

    Could not find gem 'bundler (< 2.0, >= 1.3.0)', which is required by gem 'rails
    (= 4.1.8)', in any of the sources.

    Bundler could not find compatible versions for gem "rails":
      In Gemfile:
        rails (= 4.1.8)

        animate-rails was resolved to 1.0.10, which depends on
          rails


问:
How can i condition ng-readonly inside textarea
I'm looking for a way to condition a ng-readonly inside an ng-if statement.. i tried it in a few way, this is my latest vesion..

```<code>ng-if="note.owner_image === user.image "  ng-readonly="false"
</code>```

need some assistant..

```<code><textarea
                  class="wm-textarea-notes"
                  ng-model="noteEdit.note_value"
                  columns="1"
                  placeholder="Add a note"
                  ng-readonly="true"
              ng-if="note.owner_image === user.image "  ng-readonly="false"
              ng-if="note.owner_image === "" "  ng-readonly="false

                  ></textarea>
</code>```

答:
In latest angular (6/7), you can simply set it using readonly

```<code><mat-form-field>
    <input matInput readonly="true" placeholder="{{placeholder}}" value="{{value}}">
</mat-form-field>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm looking for a way to condition a ng-readonly inside an ng-if statement.. i tried it in a few way, this is my latest vesion..

ng-if="note.owner_image === user.image "  ng-readonly="false"

need some assistant..

<textarea
                  class="wm-textarea-notes"
                  ng-model="noteEdit.note_value"
                  columns="1"
                  placeholder="Add a note"
                  ng-readonly="true"
              ng-if="note.owner_image === user.image "  ng-readonly="false"
              ng-if="note.owner_image === "" "  ng-readonly="false

                  ></textarea>

Body:
In latest angular (6/7), you can simply set it using readonly

<mat-form-field>
    <input matInput readonly="true" placeholder="{{placeholder}}" value="{{value}}">
</mat-form-field>


问:
How to set the cursor in a specific location in CKEditor?
Can I possibly set the cursor at a specific location in CKEditor? Probably, it would be based on index or text searching etc? Thanks a lot !!!</p>

答: I'm not 100% sure but I think you want to use selectRanges I found in javascript API</p>


问:
How to order tr based on td value in Jquery
I'm setting up a table with data which always orders the rows based on the highest value in a td.

I've tried using this function which does sort the rows but then appends new rows into my table so I get replicated rows.

I have my table set up like this and I need to check the TOT column which need to order by highest score.

$(document).ready(function() {
  sortTable($('#table'), 'asc');
});

function sortTable(table, order) {
  var asc = order === 'asc',
    tbody = table.find('tbody');

  tbody.find('tr').sort(function(a, b) {
    if (asc) {
      return $('td:first', a).text().localeCompare($('td:first', b).text());
    } else {
      return $('td:first', b).text().localeCompare($('td:first', a).text());
    }
  }).appendTo(tbody);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <table id="table">
    <tr>
      <th></th>
      <th>POS</th>
      <th>TEAM</th>
      <th>DRIVER</th>
      <th>TOT</th>
    </tr>
    <tbody>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>85</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>100</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>34</td>
      </tr>
    </tbody>
  </table>
</div></code>```

答:
This is a HTML issue. The problem is because your first tr isn't contained within a thead or tbody, so it breaks the table content. To fix the problem put that tr in a thead:

$(document).ready(function() {
  sortTable($('#table'), 'desc');
});

function sortTable($table, order) {
  var asc = order === 'asc',
    $tbody = $table.find('tbody');

  $tbody.find('tr').sort(function(a, b) {
    if (asc) {
      return $('td:first', a).text().localeCompare($('td:first', b).text());
    } else {
      return $('td:first', b).text().localeCompare($('td:first', a).text());
    }
  }).appendTo($tbody);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <table id="table">
    <thead>
      <tr>
        <th></th>
        <th>POS</th>
        <th>TEAM</th>
        <th>DRIVER</th>
        <th>TOT</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>85</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>100</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>34</td>
      </tr>
    </tbody>
  </table>
</div></code>```

Also note that you're sorting by string values which may not give the result you require. It may be worth using parseInt() on the value of the td to improve the sorting reliability.

Body:
I'm setting up a table with data which always orders the rows based on the highest value in a td.

I've tried using this function which does sort the rows but then appends new rows into my table so I get replicated rows.

I have my table set up like this and I need to check the TOT column which need to order by highest score.

$(document).ready(function() {
  sortTable($('#table'), 'asc');
});

function sortTable(table, order) {
  var asc = order === 'asc',
    tbody = table.find('tbody');

  tbody.find('tr').sort(function(a, b) {
    if (asc) {
      return $('td:first', a).text().localeCompare($('td:first', b).text());
    } else {
      return $('td:first', b).text().localeCompare($('td:first', a).text());
    }
  }).appendTo(tbody);
}

      POS
      TEAM
      DRIVER
      TOT

        1ST
        PROSPORT PERFORMANCE (85)
        ROBERT RENAUER
        85

        1ST
        PROSPORT PERFORMANCE (85)
        ROBERT RENAUER
        100

        1ST
        PROSPORT PERFORMANCE (85)
        ROBERT RENAUER
        34

Body:
This is a HTML issue. The problem is because your first tr isn't contained within a thead or tbody, so it breaks the table content. To fix the problem put that tr in a thead:

$(document).ready(function() {
  sortTable($('#table'), 'desc');
});

function sortTable($table, order) {
  var asc = order === 'asc',
    $tbody = $table.find('tbody');

  $tbody.find('tr').sort(function(a, b) {
    if (asc) {
      return $('td:first', a).text().localeCompare($('td:first', b).text());
    } else {
      return $('td:first', b).text().localeCompare($('td:first', a).text());
    }
  }).appendTo($tbody);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <table id="table">
    <thead>
      <tr>
        <th></th>
        <th>POS</th>
        <th>TEAM</th>
        <th>DRIVER</th>
        <th>TOT</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>85</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>100</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>34</td>
      </tr>
    </tbody>
  </table>
</div>

Also note that you're sorting by string values which may not give the result you require. It may be worth using parseInt() on the value of the td to improve the sorting reliability.


问:
how many words end in certain character in function calling to different file?
So I'm trying to make a small function that takes the name of a file as an argument and returns how many WORDS in the file end in "!", "?" or ".".

So far I've tried the following:

```<code>def count_possible_sentences(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
    count = 0
    for ch in word_list:
        if ch in "!?.":
            count += 1
    return count
</code>```

but this isn't working and is not counting how many individual WORDS end with those specified characters in the separate called file. I thought of splitting every word and looping through each character and if it contains one of the character it adds a +1 to the count but I am unsure of how to do that.

edit: also thought of just using .count? would that work? cheers

edit2:
here are my doctests I'm trying to make them pass:

```<code>def count_possible_sentences(file_name):
    """
    >>> count_possible_sentences("frances_oldham_kelsey.txt")
    45
    >>> count_possible_sentences("ernest_rutherford.txt")
    32
    >>> count_possible_sentences("marie_curie.txt")
    24
    """
</code>```

and here is a link to the .txt that is failing:
https://pastebin.com/raw/1NYPeY29

it's saying expected: 45 got: 52

答:
I would suggest something like this using regex. I think this is what you want to do.

import re
pattern = "[a-zA-Z]+(!|\?|\.)"
string = "This! sent contains? 3 of those! words !!"
a = len(re.findall(pattern, string))
print(a) # 3
```

Body:
So I'm trying to make a small function that takes the name of a file as an argument and returns how many WORDS in the file end in "!", "?" or ".".

So far I've tried the following:

def count_possible_sentences(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
    count = 0
    for ch in word_list:
        if ch in "!?.":
            count += 1
    return count

but this isn't working and is not counting how many individual WORDS end with those specified characters in the separate called file. I thought of splitting every word and looping through each character and if it contains one of the character it adds a +1 to the count but I am unsure of how to do that.

edit: also thought of just using .count? would that work? cheers

edit2:
here are my doctests I'm trying to make them pass:

def count_possible_sentences(file_name):
    """
    >>> count_possible_sentences("frances_oldham_kelsey.txt")
    45
    >>> count_possible_sentences("ernest_rutherford.txt")
    32
    >>> count_possible_sentences("marie_curie.txt")
    24
    """

and here is a link to the .txt that is failing:
https://pastebin.com/raw/1NYPeY29

it's saying expected: 45 got: 52


问:
How can I can make the new structure compatible with the old one?
I need to read files saved in a directory with an old structure (the first one posted below) and convert them in a new structure (the second one).

struct char_file_u
{
    int iClass;
    struct char_skill_data skills[MAX_SKILLS];
}

struct char_fileNew_u
{
    int iClass;
    struct char_skill_data skills[MAX_SKILLS_NEW];
    char name[20];
    char authcode[7];
}
```

答:
You can developp a new function that has to take your struct char_file_u and add the fields in your struct char_fileNew_u.

The only tricky point is that you have to be careful with the values of MAX_SKILLS and MAX_SKILLS_NEW, that can be different.


问:
Idris not properly installing/finding packages
I'm currently trying to use Blodwen, the prototype of Idris 2, as a backend for a language I'm writing. So I'm trying to import its ttimp package for my project.

I go into the Blodwen directory and do idris --install ttimp.ipkg

Then in my project's .ipkg I have:

```<code>opts = "--cg-opt -O2 -i ~/GitHub/Blodwen/"

pkgs = ttimp
</code>```

However, when I run idris --build myproject.ipkg I get the error

```<code>Entering directory `./src'
The following packages were specified but cannot be found:
- ttimp
</code>```

If I remove ttimp from pkgs, then I get Can't find import Core/Binary
 i.e. it can't find the modules from the package.

If I try to build ttimp with TARGET=~/.idris-libs

```<code> idris --install ttimp.ipkg
Entering directory `./src'
 Can't find import Builtins
 Can't find import Prelude
 Can't find import Data/List
</code>```

My Question: How can I make sure ttimp is being installed properly? Where does Idris install packages by default? Why isn't Idris finding the library after I've installed it?

答: I am not sure what your current goal is, but when you install blodwen it is using idris to a) install ttimp and to compile blodwen, which is available as the executable blodwen afterwards. So if you want to work with blodwen, you should also use blodwen to compile your files and install additional libraries.

Body:
I'm currently trying to use Blodwen, the prototype of Idris 2, as a backend for a language I'm writing. So I'm trying to import its ttimp package for my project.

I go into the Blodwen directory and do idris --install ttimp.ipkg

Then in my project's .ipkg I have:

opts = "--cg-opt -O2 -i ~/GitHub/Blodwen/"

pkgs = ttimp

However, when I run idris --build myproject.ipkg I get the error

Entering directory `./src'
The following packages were specified but cannot be found:
- ttimp

If I remove ttimp from pkgs, then I get Can't find import Core/Binary
 i.e. it can't find the modules from the package.

If I try to build ttimp with TARGET=~/.idris-libs

 idris --install ttimp.ipkg
Entering directory `./src'
 Can't find import Builtins
 Can't find import Prelude
 Can't find import Data/List

My Question: How can I make sure ttimp is being installed properly? Where does Idris install packages by default? Why isn't Idris finding the library after I've installed it?


问:
How to auto redirect after X seconds in AngularJS?
What is the right way to do this in AngularJS? I didn't find any simple answer to this.

I'd like to :

Load a page

Wait for X seconds

Being automatically redirected to another page after these seconds.

Note: I'm using ui-routing (states) to perform redirections

Thanks.

答:
If someone is looking for the same feature in angular 2 +.</p>

```<code>import { Router } from '@angular/router';

constructor(private router: Router) {}

ngOnInit() {
    // do init at here for current route.

    setTimeout(() => {
        this.router.navigate(['nextRoute']);
    }, 5000);  //5s
}
</code>```

Body:
If someone is looking for the same feature in angular 2 +.

import { Router } from '@angular/router';

constructor(private router: Router) {}

ngOnInit() {
    // do init at here for current route.

    setTimeout(() => {
        this.router.navigate(['nextRoute']);
    }, 5000);  //5s
}


问:
Redirect complete website to https with www
A classic question about redirecting my complete website to https with www and without trailing slash and valid when client is behind a proxy-server or not. I find 101 partial solutions but they are so confusing for me because the comments on each proposed solution always indicate conditions where the redirect could not function. I would be very pleased with a complete solution

I recently bought a SSL certificate for my domain example.com. According to my information the SSL certificate is only valid for example.com and not for www.example.com but I'm not completely sure.

I want a permanent redirect to https://www. in all cases without a trailing slash and valid behind proxy-server or not:

http://www.example.com to https://www.example.com

http://www.example.com/ to https://www.example.com

http://example.com to https://www.example.com

http://example.com/ to https://www.example.com

http://www.example.com/any-url to https://www.example.com/any-url

http://www.example.com/any-url/ to https://www.example.com/any-url

http://example.com/any-url to https://www.example.com/any-url

http://example.com/any-url/ to https://www.example.com/any-url

At this moment I only have the redirect from non www to www for my former http:// website in my htaccess file (which was correctly functioning for the website without https:// ):

```<code># SEO URL Settings
RewriteEngine On
# redirect rules first
# Without www to www
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
</code>```

What do I have to add or what would be the replacing code?

Any help is greatly appreciated!
Regards,
Sabine

....

I received no suggestions yet after the first day, so I will probably implement and test the following code this evenin, although I think it is not complete:

```<code>RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

Sabine

答:
Can you try with this configuration in your .htaccess:

```<code>RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
</code>```

Body:
A classic question about redirecting my complete website to https with www and without trailing slash and valid when client is behind a proxy-server or not. I find 101 partial solutions but they are so confusing for me because the comments on each proposed solution always indicate conditions where the redirect could not function. I would be very pleased with a complete solution

I recently bought a SSL certificate for my domain example.com. According to my information the SSL certificate is only valid for example.com and not for www.example.com but I'm not completely sure.

I want a permanent redirect to https://www. in all cases without a trailing slash and valid behind proxy-server or not:

http://www.example.com to https://www.example.com

http://www.example.com/ to https://www.example.com

http://example.com to https://www.example.com

http://example.com/ to https://www.example.com

http://www.example.com/any-url to https://www.example.com/any-url

http://www.example.com/any-url/ to https://www.example.com/any-url

http://example.com/any-url to https://www.example.com/any-url

http://example.com/any-url/ to https://www.example.com/any-url

At this moment I only have the redirect from non www to www for my former http:// website in my htaccess file (which was correctly functioning for the website without https:// ):

# SEO URL Settings
RewriteEngine On
# redirect rules first
# Without www to www
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

What do I have to add or what would be the replacing code?

Any help is greatly appreciated!
Regards,
Sabine

....

I received no suggestions yet after the first day, so I will probably implement and test the following code this evenin, although I think it is not complete:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Sabine

Body:
Can you try with this configuration in your .htaccess:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]


问:
Tomcat SSO Kerberos Realm
I managed to enable SSO in my web application using keytab.
I had to update following files to make it work:

Jass.conf

Krb5.conf

Server.xml  (Realm)

web.xml

Its working fine.My question is why I need to use Realm to search user again with Active Directory when user has already been authenticated using keytab?

Our application is open to all people in organization so I just want to get user principal from keytab and don't want to use Realm.

If I remove the Realm section from server xml, it doesn't work.

Any suggestions?

答:
The Realm is a user database. The realm enable the  and .
If you declare security constraint wihtout Realm you will end up with a 401 error. It might be your case.

I always had used a Realm but I think that if you remove all your security constraint it might work.

Title: Tomcat SSO Kerberos Realm


问:
Modeless MsgBox, Error trapping, .Find
I have a subroutine that searches for an occurrence of a string in another workbook. I'm trying to get an error message to pop up if the string can't be found (it's most likely due to spelling mistakes), as vbModeless, and allows to user to click on the cell in the searched sheet with the correct value. Then I'd like to resume the search with the new value.

I'm at the moment stuck on making my simple MsgBox to be modeless.
Can anyone help? So far I have (simplified):

```<code>With ...
    On Error GoTo UserSelect
    celladdress = .Range("a1:bb100").Find("searchstring").Address
</code>```

And my error label:

```<code>UserSelect:
    MsgBox("Select the cell with the correct spelling") vbModeless
    newstring = ActiveCell.Value
    searchstring = newstring
    Resume
</code>```

I think it's the Modeless MsgBox giving me grief.

答:
I'm not 100% sure on the requirements here. Given a search string of dgo and a worksheet with cells containing bird, cat and dog. Do you want the user to:

(a) edit the cell containing dog and change it to say dgo instead

This would use the modal form and RefEdit control outlined by andynormancx. Like a MsgBox, the modal form pauses the macro until the form is closed

(b) allow the user to click on the cell containg dog and then re-run the search with dog as the search term

This is more complicated. I think that you would need to look at events here. This is fine if your subroutine is pretty much standalone but if it is part of a larger program then this could require substantial rewriting

OwnerDisplayName: Chris Gunner

ContentLicense: CC BY-SA 2.5

Title: Modeless MsgBox, Error trapping, .Find

Body:
I have a subroutine that searches for an occurrence of a string in another workbook. I'm trying to get an error message to pop up if the string can't be found (it's most likely due to spelling mistakes), as vbModeless, and allows to user to click on the cell in the searched sheet with the correct value. Then I'd like to resume the search with the new value.

I'm at the moment stuck on making my simple MsgBox to be modeless.
Can anyone help? So far I have (simplified):

With ...
    On Error GoTo UserSelect
    celladdress = .Range("a1:bb100").Find("searchstring").Address

And my error label:

UserSelect:
    MsgBox("Select the cell with the correct spelling") vbModeless
    newstring = ActiveCell.Value
    searchstring = newstring
    Resume

I think it's the Modeless MsgBox giving me grief.

OwnerDisplayName: barrowc


问:
PLSQL-Parametric definition of group function
I have a table where i want to apply some aggregation functions having as criteria the grouping of spesific element of specific column. Assume the example below:

```<code>TIMESTAMP   SITE    VALUE

10:00            A  100
10:00            B  50
10:00            C  25
10:00            D  25
10:05            A  25
10:05            B  15
10:05            C  5
10:05            D  10
</code>```

i want to find the average value grouping by SITE, TIMESTAMP but the site A,B i want it to be estimated as one, meaning that i wanted to REPLACE B WITH A have AND THEN find the average:

```<code>TIMESTAMP   SITE    VALUE
10:00            A  75
10:00            A  75
10:00            C  25
10:00            D  25
10:05            A  20
10:05            A  20
10:05            C  5
10:05            D  10
</code>```

One way is to update the table setting B=A, but this is not such a sophisticated solution if i want in future to group more SITES

答:
You don't need to update the table.</p>

```<code>SELECT CASE site WHEN 'B' THEN 'A' ELSE site END as site
      ,timestamp
      ,AVG(value)
FROM sites
GROUP BY CASE site WHEN 'B' THEN 'A' ELSE site END
        ,timestamp
;
</code>```

Body:
I have a table where i want to apply some aggregation functions having as criteria the grouping of spesific element of specific column. Assume the example below:

TIMESTAMP   SITE    VALUE

10:00            A  100
10:00            B  50
10:00            C  25
10:00            D  25
10:05            A  25
10:05            B  15
10:05            C  5
10:05            D  10

i want to find the average value grouping by SITE, TIMESTAMP but the site A,B i want it to be estimated as one, meaning that i wanted to REPLACE B WITH A have AND THEN find the average:

TIMESTAMP   SITE    VALUE
10:00            A  75
10:00            A  75
10:00            C  25
10:00            D  25
10:05            A  20
10:05            A  20
10:05            C  5
10:05            D  10

One way is to update the table setting B=A, but this is not such a sophisticated solution if i want in future to group more SITES

Body:
You don't need to update the table.

SELECT CASE site WHEN 'B' THEN 'A' ELSE site END as site
      ,timestamp
      ,AVG(value)
FROM sites
GROUP BY CASE site WHEN 'B' THEN 'A' ELSE site END
        ,timestamp
;


问:
Want the difference between POCO and DTO in C#
Anybody can explain about the difference between the
POCO and DTO objects in c# with example
and also go through the below link
in the below link having four types to transfer data from one layer to another layer
i cant under the link explanations

Four ways of passing data between layers[^]

What I have tried:

please help me out from the confusion

答:
learn to love the POCO, and make sure you don’t spread any misinformation about it being the same thing as a DTO. DTOs are simple data containers used for moving data between the layers of an application. POCOs are full-fledged business objects with the one requirement that they are Persistence Ignorant (no get or save methods)
BTW, Patrick, I read the POCO as a Lifestyle article, and I completely agree, that is a fantastic article.

YOu can check more details form here http://rlacovara.blogspot.com/2009/03/what-is-difference-between-dto-and-poco.html


问:
Application/octet-stream filling last row of file with NULL after downloading
I'm trying to download a .hex file from server and save it on the user machine. The file size is a little above 2.4 MB. After the download on the user machine, it gets to 4 MB. The additional size comes from that the last line gets filled with NULL. The NULL count is exactly as the rows in the file - 50 rows => 50 NULLs at the end (in my case 32898 rows(lines) => 32898 NULLs at the end).

I tried removing them but with no luck. Is there a way to do this in the current method? Alternative ways of the method with FileResult are also welcomed.

```<code>public FileResult Download(string documentID) {

    byte[] buffer = null;

    using (FileStream fs = new FileStream("C:\\Temp\\temp\\" + documentID + ".hex", FileMode.Open, FileAccess.Read)) {
        buffer = new byte[fs.Length - fs.Position];
        fs.Read(buffer, 0, (int)fs.Length);
    }

    var cd = new System.Net.Mime.ContentDisposition {
        FileName = "HEX_FILE_NAME.hex",
        Inline = false,
    };
    Response.AppendHeader("Content-Disposition", cd.ToString());
    return File(buffer, "application/octet-stream");
}
</code>```

答:
After a lot of headbanging I managed to find solution to my problem. The file gets downloaded and there is no additional NULL row anymore. Tested it on a live server also. Works for other file extentions as well. I'll leave the solution here in case it helps someone in the future.</p>

```<code>public FileResult Download(string documentID) {

            string fileName = @"C:\\Temp\\temp\\" + documentID + ".hex";
            FileInfo fileInfo = new FileInfo(fileName);

            if (fileInfo.Exists) {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
                Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                Response.Flush();
                Response.TransmitFile(fileInfo.FullName);
                Response.End();
            }

            return File(fileName, "application/octet-stream");
        }
</code>```

Body:
I'm trying to download a .hex file from server and save it on the user machine. The file size is a little above 2.4 MB. After the download on the user machine, it gets to 4 MB. The additional size comes from that the last line gets filled with NULL. The NULL count is exactly as the rows in the file - 50 rows => 50 NULLs at the end (in my case 32898 rows(lines) => 32898 NULLs at the end).

I tried removing them but with no luck. Is there a way to do this in the current method? Alternative ways of the method with FileResult are also welcomed.

public FileResult Download(string documentID) {

    byte[] buffer = null;

    using (FileStream fs = new FileStream("C:\\Temp\\temp\\" + documentID + ".hex", FileMode.Open, FileAccess.Read)) {
        buffer = new byte[fs.Length - fs.Position];
        fs.Read(buffer, 0, (int)fs.Length);
    }

    var cd = new System.Net.Mime.ContentDisposition {
        FileName = "HEX_FILE_NAME.hex",
        Inline = false,
    };
    Response.AppendHeader("Content-Disposition", cd.ToString());
    return File(buffer, "application/octet-stream");
}

Body:
After a lot of headbanging I managed to find solution to my problem. The file gets downloaded and there is no additional NULL row anymore. Tested it on a live server also. Works for other file extentions as well. I'll leave the solution here in case it helps someone in the future.

public FileResult Download(string documentID) {

            string fileName = @"C:\\Temp\\temp\\" + documentID + ".hex";
            FileInfo fileInfo = new FileInfo(fileName);

            if (fileInfo.Exists) {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
                Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                Response.Flush();
                Response.TransmitFile(fileInfo.FullName);
                Response.End();
            }

            return File(fileName, "application/octet-stream");
        }


问:
Gitea Docker windows - Fatal: Authentication failed
I am new to Gitea and Git and thought to install Gitea through docker on a Windows 10 computer to test it out before deploying it elsewhere, but I kind of got stuck right at the end. I can open Gitea inside the browser and create repositories and so on, the problem occurs when I want to execute git push -u origin master

The error is :
remote: invalid credentials
fatal: Authentication failed for ‘http://localhost:3000/user/test.git/’

This is my docker-compose.yml file (I followed the instructions on the Gitea website) :

```<code>version: "2"

networks:
  gitea:
    external: false

volumes:
  gitea:
    driver: local

services:
  server:
    image: gitea/gitea:latest
    environment:
      - USER_UID=1000
      - USER_GID=1000
      - DB_TYPE=mysql
      - DB_HOST=db:3306
      - DB_NAME=gitea
      - DB_USER=gitea
      - DB_PASSWD=gitea
    restart: always
    networks:
      - gitea
    volumes:
      #- ./gitea:/data
       - gitea:/data
    ports:
       - "3000:3000"
       - "222:22"
    depends_on:
      - db

  db:
    image: mysql:5.7
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=gitea
      - MYSQL_USER=gitea
      - MYSQL_PASSWORD=gitea
      - MYSQL_DATABASE=gitea
    networks:
      - gitea
    volumes:
      - ./mysql:/var/lib/mysql
</code>```

答: I will answer my own question here, it may help someone else with the same problem. I solved it with the help of the answer to this question on Stack overflow. The problem was solved after setting the correct username and password in the Windows credential manager.</p>

Body:
I am new to Gitea and Git and thought to install Gitea through docker on a Windows 10 computer to test it out before deploying it elsewhere, but I kind of got stuck right at the end. I can open Gitea inside the browser and create repositories and so on, the problem occurs when I want to execute git push -u origin master

The error is :
remote: invalid credentials
fatal: Authentication failed for ‘http://localhost:3000/user/test.git/’

This is my docker-compose.yml file (I followed the instructions on the Gitea website) :

version: "2"

networks:
  gitea:
    external: false

volumes:
  gitea:
    driver: local

services:
  server:
    image: gitea/gitea:latest
    environment:
      - USER_UID=1000
      - USER_GID=1000
      - DB_TYPE=mysql
      - DB_HOST=db:3306
      - DB_NAME=gitea
      - DB_USER=gitea
      - DB_PASSWD=gitea
    restart: always
    networks:
      - gitea
    volumes:
      #- ./gitea:/data
       - gitea:/data
    ports:
       - "3000:3000"
       - "222:22"
    depends_on:
      - db

  db:
    image: mysql:5.7
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=gitea
      - MYSQL_USER=gitea
      - MYSQL_PASSWORD=gitea
      - MYSQL_DATABASE=gitea
    networks:
      - gitea
    volumes:
      - ./mysql:/var/lib/mysql


问:
What do I need to do to accomplish "fire a job/alarm once at the beginning of next month to call an API" in Kotlin?
I'm new to Kotlin and Android, and as I try to research about job scheduler in Kotlin/Android, I'm overwhelmed with lots of ways, but all seems complicated in their own ways.

I'm developing a simple app that recording customer's feedback, that's mostly offline. But it has one feature that's online, and that is for sending report to some email addresses, via the help of an API, at the beginning of every month.

I need the simplest way to implement this, which:

Can execute whether the app is active or destroyed -- so as a service?

Does not have to be exact (inexact time is okay).

I just need to fire once, because the app will set for next fire when the user interact with the app. Doesn't need to be repeated.

Fire it at the beginning of next month.

I can replace the existing job with the new job, if the previous job hasn't fired yet but the user already does another interaction with the app, as the report summarizes the whole month of activity. I read that alarm / job with the "same intent" can replace one another, although I'm not sure what that actually looks like in implementation.

Because the data is in database, and I think I probably can't access the database when the app is inactive, I think I can put the data to be sent in the user shared preferences each time I set the job/alarm. I read somewhere that background service can read from shared preferences.

Need to do network call.

So, if, for example, the needed data to sent is already on the shared preferences, what is the simplest / most basic way to accomplish this?

```<code>fun userDoInteractionWithApp (data: Data) {
    this.process (data)
    val report = this.generateThisMonthReport()
    this.scheduleNextReport(report, Date())
}

fun scheduleNextReport(report: String, curDate: Date) {
    this.saveToSharedPreferences ("report", report)
    val c = Calendar.getInstance()
    c.time = curDate
    c.add(Calendar.MONTH, 1)
    c.set(Calendar.DAY_OF_MONTH, 1)
    c.set(Calendar.HOUR_OF_DAY, 10)
    val targetDate = c.time

    // and then?
}

fun sendReport() { // I want to fire this function, for example
    val report = this.loadFromSharedPreferences ("report") as String
    Network.sendReport(senderEmail, destinationEmail, "This is the report", report) // will run synchronously
}
</code>```

答:
If you don't have to start app at exact time the best way to do that is with the

WorkManager

You call it:

```<code>val uploadWorkRequest = OneTimeWorkRequestBuilder<YourWorker>()
        .build()
WorkManager.getInstance().enqueue(uploadWorkRequest)
</code>```

You can set a delay chaining this:

.setInitialDelay(duration, TimeUnit)

Body:
I'm new to Kotlin and Android, and as I try to research about job scheduler in Kotlin/Android, I'm overwhelmed with lots of ways, but all seems complicated in their own ways.

I'm developing a simple app that recording customer's feedback, that's mostly offline. But it has one feature that's online, and that is for sending report to some email addresses, via the help of an API, at the beginning of every month.

I need the simplest way to implement this, which:

Can execute whether the app is active or destroyed -- so as a service?

Does not have to be exact (inexact time is okay).

I just need to fire once, because the app will set for next fire when the user interact with the app. Doesn't need to be repeated.

Fire it at the beginning of next month.

I can replace the existing job with the new job, if the previous job hasn't fired yet but the user already does another interaction with the app, as the report summarizes the whole month of activity. I read that alarm / job with the "same intent" can replace one another, although I'm not sure what that actually looks like in implementation.

Because the data is in database, and I think I probably can't access the database when the app is inactive, I think I can put the data to be sent in the user shared preferences each time I set the job/alarm. I read somewhere that background service can read from shared preferences.

Need to do network call.

So, if, for example, the needed data to sent is already on the shared preferences, what is the simplest / most basic way to accomplish this?

fun userDoInteractionWithApp (data: Data) {
    this.process (data)
    val report = this.generateThisMonthReport()
    this.scheduleNextReport(report, Date())
}

fun scheduleNextReport(report: String, curDate: Date) {
    this.saveToSharedPreferences ("report", report)
    val c = Calendar.getInstance()
    c.time = curDate
    c.add(Calendar.MONTH, 1)
    c.set(Calendar.DAY_OF_MONTH, 1)
    c.set(Calendar.HOUR_OF_DAY, 10)
    val targetDate = c.time

    // and then?
}

fun sendReport() { // I want to fire this function, for example
    val report = this.loadFromSharedPreferences ("report") as String
    Network.sendReport(senderEmail, destinationEmail, "This is the report", report) // will run synchronously
}

Body:
If you don't have to start app at exact time the best way to do that is with the

WorkManager

You call it:

val uploadWorkRequest = OneTimeWorkRequestBuilder<YourWorker>()
        .build()
WorkManager.getInstance().enqueue(uploadWorkRequest)

You can set a delay chaining this:

.setInitialDelay(duration, TimeUnit)


问:
How to use python code remove txt line before string?
I have Sample.txt file as below:

```<code>back
bold
yellow
green
country
code
bold
hello
yellow
country
code
bold
country
</code>```

I wish to delete the first few line before country,so expected outcome is

```<code>country
code
bold
hello
yellow
country
code
bold
country
</code>```

Anyone have ideas on this?

答:
you can use list.index() to find out the position of country in the list, and then use slicing to get everything after it.

could you please try this, and let me know how it works for you?

content = []
with open('Sample.txt') as f:
    content = f.readlines()

content = content[content.index('country\n'):]

with open('Sample.txt', 'w+') as f:
    f.writelines(content)

```

Body:
I have Sample.txt file as below:

back
bold
yellow
green
country
code
bold
hello
yellow
country
code
bold
country

I wish to delete the first few line before country,so expected outcome is

country
code
bold
hello
yellow
country
code
bold
country

Anyone have ideas on this?


问:
difference between 2 dates in days saved into new column as float
I have a python dataframe with 2 columns that contain dates as strings e.g. start_date "2002-06-12" and end_date "2009-03-01". I would like to calculate the difference (days) between these 2 columns for each row and save the results into a new column called for example time_diff of type float.

I have tried:

```<code>df["time_diff"] = (pd.Timestamp(df.end_date) - pd.Timestamp(df.start_date )).astype("timedelta64[d]")
pd.to_numeric(df["time_diff"])
</code>```

based on some tutorials but this gives TypeError: Cannot convert input for the first line. What do I need to change to get this running?

答:
Here is a working example of converting a string column of a dataframe to datetime type and saving the time difference between the datetime columns in a new column as a float data type( number of seconds)

```<code>import pandas as pd
from datetime import timedelta
tmp = [("2002-06-12","2009-03-01"),("2016-04-28","2022-03-14")]
df = pd.DataFrame(tmp,columns=["col1","col2"])

df["col1"]=pd.to_datetime(df["col1"])
df["col2"]=pd.to_datetime(df["col2"])

df["time_diff"]=df["col2"]-df["col1"]
df["time_diff"]=df["time_diff"].apply(timedelta.total_seconds)
</code>```

Time difference in seconds can be converted to minutes or days by using simple math.

Body:
I have a python dataframe with 2 columns that contain dates as strings e.g. start_date "2002-06-12" and end_date "2009-03-01". I would like to calculate the difference (days) between these 2 columns for each row and save the results into a new column called for example time_diff of type float.

I have tried:

df["time_diff"] = (pd.Timestamp(df.end_date) - pd.Timestamp(df.start_date )).astype("timedelta64[d]")
pd.to_numeric(df["time_diff"])

based on some tutorials but this gives TypeError: Cannot convert input for the first line. What do I need to change to get this running?

Body:
Here is a working example of converting a string column of a dataframe to datetime type and saving the time difference between the datetime columns in a new column as a float data type( number of seconds)

import pandas as pd
from datetime import timedelta
tmp = [("2002-06-12","2009-03-01"),("2016-04-28","2022-03-14")]
df = pd.DataFrame(tmp,columns=["col1","col2"])

df["col1"]=pd.to_datetime(df["col1"])
df["col2"]=pd.to_datetime(df["col2"])

df["time_diff"]=df["col2"]-df["col1"]
df["time_diff"]=df["time_diff"].apply(timedelta.total_seconds)

Time difference in seconds can be converted to minutes or days by using simple math.


答:
You could get the list of lines in the file, use index to get the first occurrence of 'country' and then slice the list.

```<code>with open('Sample.txt') as inpfile:
    lines = list(map(str.strip, inpfile.readlines()))
    print(len(lines))
    print(lines[lines.index('country'):])
</code>```

Or you could loop over the file and only start storing the lines after you encounter country (this would avoid loading everything into a list first):

```<code>with open('Sample.txt') as inpfile:
    is_storing = False
    lines = []
    for l in inpfile:
        if not is_storing and l.strip() == 'country':
            is_storing = True

        if is_storing:
            lines.append(l.strip())

    print(lines)
</code>```

Title: How to use python code remove txt line before string?

Body:
You could get the list of lines in the file, use index to get the first occurrence of 'country' and then slice the list.

with open('Sample.txt') as inpfile:
    lines = list(map(str.strip, inpfile.readlines()))
    print(len(lines))
    print(lines[lines.index('country'):])

Or you could loop over the file and only start storing the lines after you encounter country (this would avoid loading everything into a list first):

with open('Sample.txt') as inpfile:
    is_storing = False
    lines = []
    for l in inpfile:
        if not is_storing and l.strip() == 'country':
            is_storing = True

        if is_storing:
            lines.append(l.strip())

    print(lines)


问:
docker-compose not overriding dockerfile environment variables
I am trying to set basic postgres info from my docker-compose. The container starts but the variables from the Dockerfile are not overridden when I run docker-compose up. Please help.

```<code>FROM mine/debian7

## START: UPDATES & INSTALLS ###########################################################################################
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ wheezy-pgdg main" >> /etc/apt/sources.list.d/pgdg.list && \
    wget --quiet -O - http://apt.postgresql.org/pub/repos/apt/ACCC4CF8.asc | apt-key add -  && \
    apt-get update && \
    apt-get upgrade && \
    apt-get install -y python-software-properties software-properties-common postgresql-9.4 postgresql-client-9.4 postgresql-contrib-9.4 && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
## END: UPDATES & INSTALLS #############################################################################################

ENV DB_USER_NAME test
ENV DB_PASSWORD test
ENV DB_NAME test

## START: CONCFIGURATION ###############################################################################################
# start postgres at boot
#RUN     echo "/etc/init.d/postgresql start" >> ~/.bashrc
USER    postgres
RUN /etc/init.d/postgresql start && \
    psql --command "CREATE USER $DB_USER_NAME WITH SUPERUSER PASSWORD '$DB_PASSWORD';" && \
    createdb -O $DB_NAME $DB_NAME
RUN     echo "host all  all    0.0.0.0/0  md5" >> /etc/postgresql/9.4/main/pg_hba.conf
RUN     echo "listen_addresses='*'" >> /etc/postgresql/9.4/main/postgresql.conf
VOLUME  ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
#USER root
#RUN update-rc.d postgresql defaults
## END: CONCFIGURATION #################################################################################################

EXPOSE 5432

CMD service postgresql start && tail -f /var/log/postgresql/postgresql-9.4-main.log
</code>```

And my docker-compose file:

```<code>tomcat:
  image: clegge/tomcat
  ports:
    - "8080:8080"
  volumes:
    - sample.war:/opt/tomcat7/webapps/sample.war

postgres:
  build: /Users/clegge/Dockers/docker-postgres-base/
  ports:
    - "5432:5432"
  stdin_open: true
  tty: true
  environment:
   - DB_USER_NAME=legge_crud
   - DB_PASSWORD=legge_crud
   - DB_NAME=test
</code>```

What am I missing?

答:
In the Dockerfile you should have :

```<code>ENV DB_USER_NAME=${DB_USER_NAME}
ENV DB_PASSWORD=${DB_PASSWORD}
ENV DB_NAME=${DB_NAME}
</code>```

Then values from docker-compose.yml will be used
and as you want some default value in your Dockerfile you can do this trick

Dockerfile :

```<code>ARG DB_USER_NAME=test
ARG DB_PASSWORD=test
ARG DB_NAME=test

ENV DB_USER_NAME=${DB_USER_NAME}
ENV DB_PASSWORD=${DB_PASSWORD}
ENV DB_NAME=${DB_NAME}
</code>```

And your docker-compose.yml should have these values (the current docker-compose.yml in the question is then right) :

```<code>environment:
    - DB_USER_NAME=legge_crud
    - DB_PASSWORD=legge_crud
    - DB_NAME=test
</code>```

Body:
I am trying to set basic postgres info from my docker-compose. The container starts but the variables from the Dockerfile are not overridden when I run docker-compose up. Please help.

FROM mine/debian7

## START: UPDATES & INSTALLS ###########################################################################################
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ wheezy-pgdg main" >> /etc/apt/sources.list.d/pgdg.list && \
    wget --quiet -O - http://apt.postgresql.org/pub/repos/apt/ACCC4CF8.asc | apt-key add -  && \
    apt-get update && \
    apt-get upgrade && \
    apt-get install -y python-software-properties software-properties-common postgresql-9.4 postgresql-client-9.4 postgresql-contrib-9.4 && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
## END: UPDATES & INSTALLS #############################################################################################

ENV DB_USER_NAME test
ENV DB_PASSWORD test
ENV DB_NAME test

## START: CONCFIGURATION ###############################################################################################
# start postgres at boot
#RUN     echo "/etc/init.d/postgresql start" >> ~/.bashrc
USER    postgres
RUN /etc/init.d/postgresql start && \
    psql --command "CREATE USER $DB_USER_NAME WITH SUPERUSER PASSWORD '$DB_PASSWORD';" && \
    createdb -O $DB_NAME $DB_NAME
RUN     echo "host all  all    0.0.0.0/0  md5" >> /etc/postgresql/9.4/main/pg_hba.conf
RUN     echo "listen_addresses='*'" >> /etc/postgresql/9.4/main/postgresql.conf
VOLUME  ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"]
#USER root
#RUN update-rc.d postgresql defaults
## END: CONCFIGURATION #################################################################################################

EXPOSE 5432

CMD service postgresql start && tail -f /var/log/postgresql/postgresql-9.4-main.log

And my docker-compose file:

tomcat:
  image: clegge/tomcat
  ports:
    - "8080:8080"
  volumes:
    - sample.war:/opt/tomcat7/webapps/sample.war

postgres:
  build: /Users/clegge/Dockers/docker-postgres-base/
  ports:
    - "5432:5432"
  stdin_open: true
  tty: true
  environment:
   - DB_USER_NAME=legge_crud
   - DB_PASSWORD=legge_crud
   - DB_NAME=test

What am I missing?

Body:
In the Dockerfile you should have :

ENV DB_USER_NAME=${DB_USER_NAME}
ENV DB_PASSWORD=${DB_PASSWORD}
ENV DB_NAME=${DB_NAME}

Then values from docker-compose.yml will be used
and as you want some default value in your Dockerfile you can do this trick

Dockerfile :

ARG DB_USER_NAME=test
ARG DB_PASSWORD=test
ARG DB_NAME=test

ENV DB_USER_NAME=${DB_USER_NAME}
ENV DB_PASSWORD=${DB_PASSWORD}
ENV DB_NAME=${DB_NAME}

And your docker-compose.yml should have these values (the current docker-compose.yml in the question is then right) :

environment:
    - DB_USER_NAME=legge_crud
    - DB_PASSWORD=legge_crud
    - DB_NAME=test


答:
You need to change if statement:</p>

```<code>def count_possible_sentences(file_name):
    with open(file_name) as word_file:
        text_str = word_file.read()
        word_list = text_str.split()
    count = 0
    for item in word_list:
        if '!' in item or '?' in item or '.' in item:
             count += 1
    return count
</code>```

Title: how many words end in certain character in function calling to different file?

Body:
So I'm trying to make a small function that takes the name of a file as an argument and returns how many WORDS in the file end in "!", "?" or ".".

So far I've tried the following:

def count_possible_sentences(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
    count = 0
    for ch in word_list:
        if ch in "!?.":
            count += 1
    return count

but this isn't working and is not counting how many individual WORDS end with those specified characters in the separate called file. I thought of splitting every word and looping through each character and if it contains one of the character it adds a +1 to the count but I am unsure of how to do that.

edit: also thought of just using .count? would that work? cheers

edit2:
here are my doctests I'm trying to make them pass:

def count_possible_sentences(file_name):
    """
    >>> count_possible_sentences("frances_oldham_kelsey.txt")
    45
    >>> count_possible_sentences("ernest_rutherford.txt")
    32
    >>> count_possible_sentences("marie_curie.txt")
    24
    """

and here is a link to the .txt that is failing:
https://pastebin.com/raw/1NYPeY29

it's saying expected: 45 got: 52

Body:
You need to change if statement:

def count_possible_sentences(file_name):
    with open(file_name) as word_file:
        text_str = word_file.read()
        word_list = text_str.split()
    count = 0
    for item in word_list:
        if '!' in item or '?' in item or '.' in item:
             count += 1
    return count


问:
Postgres DB upload error "No server supplied!"
So, I have to import a database in postgres and I get the following error: "No server supplied!"
I searched a bit and I understood that this is because of the PHP file size limit, post size or memory size.
I'm using a LAMP installation on Linux Ubuntu and I've edited the php.ini file from lampstack/php/etc
I've tried everything I've found until now, most people claiming to solve the problem but apparently not mine.
The settings now are these:

```<code>upload_max_filesize = 5000M
post_max_size = 5000M
max_execution_time = 120
max_input_time = 300
memory_limit = 2G
</code>```

I tried changing anything people talked about, yes I did restart LAMP, the browser, even the computer, I've cleared the cache, nothing...
Any idea what I'm doing wrong? Thank you!

Update: The error log looks like this:
PHP Warning:  POST Content-Length of 84394850 bytes exceeds the limit of 83886080 bytes in Unknown on line 0, referer: http://localhost:8080/phppgadmin/redirect.php?subject=database&server=localhost%3A5432%3Aallow&database=ss_dev

答:
Error : No server supplied

Steps:

```<code>sudo gedit /etc/php/7.0/apache2/php.ini
</code>```

Just change your php.ini (xampp/php/php.ini) file:

```<code>memory_limit = 1000M
post_max_size = 750M
upload_max_filesize = 750M
</code>```

And, don't forget to restart Apache Module from XAMPP Control Panel

```<code>sudo service apache2 restart.
</code>```

Body:
So, I have to import a database in postgres and I get the following error: "No server supplied!"
I searched a bit and I understood that this is because of the PHP file size limit, post size or memory size.
I'm using a LAMP installation on Linux Ubuntu and I've edited the php.ini file from lampstack/php/etc
I've tried everything I've found until now, most people claiming to solve the problem but apparently not mine.
The settings now are these:

upload_max_filesize = 5000M
post_max_size = 5000M
max_execution_time = 120
max_input_time = 300
memory_limit = 2G

I tried changing anything people talked about, yes I did restart LAMP, the browser, even the computer, I've cleared the cache, nothing...
Any idea what I'm doing wrong? Thank you!

Update: The error log looks like this:
PHP Warning:  POST Content-Length of 84394850 bytes exceeds the limit of 83886080 bytes in Unknown on line 0, referer: http://localhost:8080/phppgadmin/redirect.php?subject=database&server=localhost%3A5432%3Aallow&database=ss_dev

Body:
Error : No server supplied

Steps:

sudo gedit /etc/php/7.0/apache2/php.ini

Just change your php.ini (xampp/php/php.ini) file:

memory_limit = 1000M
post_max_size = 750M
upload_max_filesize = 750M

And, don't forget to restart Apache Module from XAMPP Control Panel

sudo service apache2 restart.


问:
Get-ADGroup where there are more than 500 members (including nested)
I'm trying to run a PowerShell query to bring back groups with more than 500 members in it.

I've tried to run a measure statement & count -gt 500

Get-ADGroup  -Filter {name -like "Distribution*"} -Properties * |
    measure |
    where count -gt 100 |
    select name
```

I'd like this to bring back just group names that have > 500 members in it.

答:
Try this way:</p>

```<code>Get-ADGroup  -Filter {name -like "Distribution*"} -Properties * | where {$($_.members.count) -GE 500} | select Name
</code>```

Body:
I'm trying to run a PowerShell query to bring back groups with more than 500 members in it.

I've tried to run a measure statement & count -gt 500

Get-ADGroup  -Filter {name -like "Distribution*"} -Properties * |
    measure |
    where count -gt 100 |
    select name

I'd like this to bring back just group names that have > 500 members in it.

Body:
Try this way:

Get-ADGroup  -Filter {name -like "Distribution*"} -Properties * | where {$($_.members.count) -GE 500} | select Name


问:
Margin-Top < 0 leads to wrong zooming
I want a child element to be zoomable and centered. If you change the zoom of the child to 200% you can see that the element's top is violet, but you can't zoom up. How can I fix this? I think it's because the margin-top is below zero.

Zoom 100% :

#child {
  background-image: linear-gradient(red, violet, yellow, green, pink);
  width:50px;
  height:400px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    zoom: 100%;
}

#parent {
  background-color:blue;
  width:500px;
  height:500px;
  position: relative;
  transform: scale();
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <div id="child"></div>
</div></code>```

Zoom 200% :

#child {
  background-image: linear-gradient(red, violet, yellow, green, pink);
  width:50px;
  height:400px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    zoom: 200%;
}

#parent {
  background-color:blue;
  width:500px;
  height:500px;
  position: relative;
  transform: scale();
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <div id="child"></div>
</div></code>```

答:
Solved this by adding 'display: flex; align-items: center;' to the parent and removing the position absolute (incl. positions)

#child {
  background-image: linear-gradient(red, violet, yellow, green, pink);
  width: 50px;
  height: 400px;
  margin: auto;
  zoom: 200%;
}

#parent {
  background-color:blue;
  width: 500px;
  height: 500px;
  overflow: auto;
  display: flex;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <div id="child"></div>
</div></code>```

Title: Margin-Top < 0 leads to wrong zooming

Body:
I want a child element to be zoomable and centered. If you change the zoom of the child to 200% you can see that the element's top is violet, but you can't zoom up. How can I fix this? I think it's because the margin-top is below zero.

Zoom 100% :

#child {
  background-image: linear-gradient(red, violet, yellow, green, pink);
  width:50px;
  height:400px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    zoom: 100%;
}

#parent {
  background-color:blue;
  width:500px;
  height:500px;
  position: relative;
  transform: scale();
  overflow: auto;
}

Zoom 200% :

#child {
  background-image: linear-gradient(red, violet, yellow, green, pink);
  width:50px;
  height:400px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    zoom: 200%;
}

#parent {
  background-color:blue;
  width:500px;
  height:500px;
  position: relative;
  transform: scale();
  overflow: auto;
}

Body:
Solved this by adding 'display: flex; align-items: center;' to the parent and removing the position absolute (incl. positions)

#child {
  background-image: linear-gradient(red, violet, yellow, green, pink);
  width: 50px;
  height: 400px;
  margin: auto;
  zoom: 200%;
}

#parent {
  background-color:blue;
  width: 500px;
  height: 500px;
  overflow: auto;
  display: flex;
  align-items: center;
}

<div id="parent">
  <div id="child"></div>
</div>


问:
vue 3 + electron simple example not working
I tried to build an example electron app, using vuejs 3. I am on Debian Buster, running node version v10.15.1.

I followed more or less the description given in https://github.com/nklayman/vue-cli-plugin-electron-builder:

vue --version
3.6.3

vue create frontend
cd frontend/
npm run serve //everything is fine

vue add electron-builder
npx vue-cli-service electron:serve
```

<p><code>dist_electron/index.js</code> was successfully compiled, but after the message <code>INFO Launching Electron...</code>, nothing did happen.</p>

<p>Maybe I think that my <code>electron</code> installation is broken:</p>

<pre class="lang-bash prettyprint-override"><code>./node_modules/electron/dist/electron --version
[29769:0426/003034.548566:FATAL:setuid_sandbox_host.cc(157)] The SUID sandbox helper binary was found, but is not configured correctly. Rather than run without sandboxing I'm aborting now. You need to make sure that /home/info/frontend/node_modules/electron/dist/chrome-sandbox is owned by root and has mode 4755.
</code>```

As Cloud Soh Jun Fu suggested, I tried to change permission and ownership:

```<code>sudo chown root:root chrome-sandbox
sudo chmod 4755 chrome-sandbox
</code>```

Now it works as expected, but somehow I do not have a good feeling about it... I mean, I only did some elementary things, for that, I expected to run electron out of the box...

Any other suggestions?

答:
There is a recent Electron bug report with this same issue: #17972.

Downgrading to Electron 4.x is one possible solution.

Another workaround is mentioned, which enables "user namespace sandboxing" instead of the "SUID sandbox":

```<code>sudo sysctl kernel.unprivileged_userns_clone=1
</code>```

Supposedly this option is enabled on Ubuntu by default, but not on Arch Linux, and apparently also not on your Debian system. To make the change permanent, you can create /etc/sysctl.d/electron.conf with the following content:

```<code>kernel.unprivileged_userns_clone = 1
</code>```

Body:
I tried to build an example electron app, using vuejs 3. I am on Debian Buster, running node version v10.15.1.

I followed more or less the description given in https://github.com/nklayman/vue-cli-plugin-electron-builder:

vue --version
3.6.3

vue create frontend
cd frontend/
npm run serve //everything is fine

vue add electron-builder
npx vue-cli-service electron:serve

dist_electron/index.js was successfully compiled, but after the message INFO Launching Electron..., nothing did happen.

Maybe I think that my electron installation is broken:

./node_modules/electron/dist/electron --version
[29769:0426/003034.548566:FATAL:setuid_sandbox_host.cc(157)] The SUID sandbox helper binary was found, but is not configured correctly. Rather than run without sandboxing I'm aborting now. You need to make sure that /home/info/frontend/node_modules/electron/dist/chrome-sandbox is owned by root and has mode 4755.

As Cloud Soh Jun Fu suggested, I tried to change permission and ownership:

sudo chown root:root chrome-sandbox
sudo chmod 4755 chrome-sandbox

Now it works as expected, but somehow I do not have a good feeling about it... I mean, I only did some elementary things, for that, I expected to run electron out of the box...

Any other suggestions?

Body:
There is a recent Electron bug report with this same issue: #17972.

Downgrading to Electron 4.x is one possible solution.

Another workaround is mentioned, which enables "user namespace sandboxing" instead of the "SUID sandbox":

sudo sysctl kernel.unprivileged_userns_clone=1

Supposedly this option is enabled on Ubuntu by default, but not on Arch Linux, and apparently also not on your Debian system. To make the change permanent, you can create /etc/sysctl.d/electron.conf with the following content:

kernel.unprivileged_userns_clone = 1


问:
How to save ckeditor script in my Angular project instead of calling it dynamically?
I'm using ckeditor in my Angular project. I load it dynamically every time the app is opened by adding it in a script tag in index.html file. However, it's taking a lot of time to load for some reason. Can I save the script in my project folder so that it can be accessed directly from there?

This is how I'm accessing it correctly in my index.html file.

```<code><script src="https://cdn.ckeditor.com/4.9.2/full-all/ckeditor.js"></script>
</code>```

I'm able to use ckeditor properly and all the functionality works fine. However, since it takes too long to load, I wanted to know if I can download it in one of my project folders and use it from there?

答:
CKEditor 4 offers a native Angular integration through the CKEditor 4 Angular component. In your Angular project, install the ckeditor4-angular npm package.

npm install --save ckeditor4-angular

Then import CKEditorModule to your application.

```<code>import { CKEditorModule } from 'ckeditor4-angular';

@NgModule( {
    imports: [
        ...
        CKEditorModule,
        ...
    ],
    …
} )
</code>```

You can check out this documentation for reference: https://ckeditor.com/docs/ckeditor4/latest/guide/dev_angular.html

Body:
I'm using ckeditor in my Angular project. I load it dynamically every time the app is opened by adding it in a script tag in index.html file. However, it's taking a lot of time to load for some reason. Can I save the script in my project folder so that it can be accessed directly from there?

This is how I'm accessing it correctly in my index.html file.

I'm able to use ckeditor properly and all the functionality works fine. However, since it takes too long to load, I wanted to know if I can download it in one of my project folders and use it from there?

Body:
CKEditor 4 offers a native Angular integration through the CKEditor 4 Angular component. In your Angular project, install the ckeditor4-angular npm package.

npm install --save ckeditor4-angular

Then import CKEditorModule to your application.

import { CKEditorModule } from 'ckeditor4-angular';

@NgModule( {
    imports: [
        ...
        CKEditorModule,
        ...
    ],
    …
} )

You can check out this documentation for reference: https://ckeditor.com/docs/ckeditor4/latest/guide/dev_angular.html