问:
Indexing by ROW on a Column and finding partial matches in a string
I am having issues developing a for loop that incorporates a partial match feature.

To breakdown the problem:

I have two sheets that are going to be compared - one exists on sheet1 column b and the other sheet2 column c.

The for loop will iterate through column B on Sheet1 and then extract the current string at each row - this current string is then passed I tried vlookup and compared to the ENTIRE column C on sheet 2 to find a match: if there is a match it will then return the ADJACENT column to the right of Column C and then Deposit this value to the ADJACENT Column to the right of Column B.

I have currently tried implementing a for if statement that iterates through Column b and if the current string of Column B is equal to a Vlookup of Column C for the match on Current string then return the value.

```<code>Sub JoinGroupOnPN()
Dim PartGroupSheet As Worksheet
Dim OEEPartSheet As Worksheet
Dim OEERowRange As Long
Dim OEEColumnRange As Long
Dim PGRowRange As Long
Dim PGColumnRange As Long
Dim OEEArray As Variant
Dim PGArray As Variant
Dim i As Long, j As Long

Set PartGroupSheet = ActiveWorkbook.Worksheets("PartGroup")
Set OEEPartSheet = ActiveWorkbook.Worksheets("OEE Report")
OEERowRange = OEEPartSheet.Cells(Rows.Count, 1).End(xlUp).Row
OEEColumnRange = OEEPartSheet.Cells(1,Columns.Count).End(xlToLeft).Row
PGRowRange = PartGroupSheet.Cells(Columns.Count, 1).End(xlUp).Row
PGColumnRange = PartGroupSheet.Cells(1,Columns.Count).End(xlToLeft).Row
ReDim OEEArray(OEERowRange, OEEColumnRange)
ReDim PGArray(PGRowRange, PGColumnRange)
Dim StringToMatch As String
Dim MatchingString As String

For i = 2 To OEERowRange
StringToMatch = OEEPartSheet.Cells(i, 1).Text
MatchingString = Application.WorksheetFunction.VLookup(Arg1:=StringToMatch, Arg2:=PartGroupSheet.Range(Cell1:=2, Cell2:=1), Arg3:=2, Arg4:=True)

    For j = 2 To PGRowRange

        If StringToMatch = MatchingString Then

            Debug.Print StringToMatch

        End If
    Next j
Next i

End Sub
</code>```

I keep getting an error that says the range object failed and I have tried converting it to a range type but still same error.

The Error happens at

```<code>MatchingString = Application.WorksheetFunction.VLookup(Arg1:=StringToMatch, Arg2:=PartGroupSheet.Range(Cell1:=2, Cell2:=1), Arg3:=2, Arg4:=True)
</code>```

and the error message is Method 'Range' of 'Object'_WorkSheet Failed

I cant post any pictures yet

Sheet 1
Sheet 2

Any help would be appreciated thanks !!

答:
Something like this should work:</p>

```<code>Sub JoinGroupOnPN()
    Dim PartGroupSheet As Worksheet
    Dim v, c As Range, rngSrch As Range

    Set PartGroupSheet = ActiveWorkbook.Worksheets("PartGroup")

    With ActiveWorkbook.Worksheets("OEE Report")
        Set rngSrch = .Range(.Range("B2"), .Cells(.Rows.Count, "B").End(xlUp))
    End With

    For Each c In rngSrch.Cells
        If Len(c.Value) > 0 Then
            'do not use WorksheetFunction here
            v = Application.VLookup(c.Value, PartGroupSheet.Range("B:C"), 2, False)
            c.Offset(0, 1).Value = IIf(IsError(v), "No match", v)
        End If
    Next c
End Sub
</code>```

Body:
I am having issues developing a for loop that incorporates a partial match feature.

To breakdown the problem:

I have two sheets that are going to be compared - one exists on sheet1 column b and the other sheet2 column c.

The for loop will iterate through column B on Sheet1 and then extract the current string at each row - this current string is then passed I tried vlookup and compared to the ENTIRE column C on sheet 2 to find a match: if there is a match it will then return the ADJACENT column to the right of Column C and then Deposit this value to the ADJACENT Column to the right of Column B.

I have currently tried implementing a for if statement that iterates through Column b and if the current string of Column B is equal to a Vlookup of Column C for the match on Current string then return the value.

Sub JoinGroupOnPN()
Dim PartGroupSheet As Worksheet
Dim OEEPartSheet As Worksheet
Dim OEERowRange As Long
Dim OEEColumnRange As Long
Dim PGRowRange As Long
Dim PGColumnRange As Long
Dim OEEArray As Variant
Dim PGArray As Variant
Dim i As Long, j As Long

Set PartGroupSheet = ActiveWorkbook.Worksheets("PartGroup")
Set OEEPartSheet = ActiveWorkbook.Worksheets("OEE Report")
OEERowRange = OEEPartSheet.Cells(Rows.Count, 1).End(xlUp).Row
OEEColumnRange = OEEPartSheet.Cells(1,Columns.Count).End(xlToLeft).Row
PGRowRange = PartGroupSheet.Cells(Columns.Count, 1).End(xlUp).Row
PGColumnRange = PartGroupSheet.Cells(1,Columns.Count).End(xlToLeft).Row
ReDim OEEArray(OEERowRange, OEEColumnRange)
ReDim PGArray(PGRowRange, PGColumnRange)
Dim StringToMatch As String
Dim MatchingString As String

For i = 2 To OEERowRange
StringToMatch = OEEPartSheet.Cells(i, 1).Text
MatchingString = Application.WorksheetFunction.VLookup(Arg1:=StringToMatch, Arg2:=PartGroupSheet.Range(Cell1:=2, Cell2:=1), Arg3:=2, Arg4:=True)

    For j = 2 To PGRowRange

        If StringToMatch = MatchingString Then

            Debug.Print StringToMatch

        End If
    Next j
Next i

End Sub

I keep getting an error that says the range object failed and I have tried converting it to a range type but still same error.

The Error happens at

MatchingString = Application.WorksheetFunction.VLookup(Arg1:=StringToMatch, Arg2:=PartGroupSheet.Range(Cell1:=2, Cell2:=1), Arg3:=2, Arg4:=True)

and the error message is Method 'Range' of 'Object'_WorkSheet Failed

I cant post any pictures yet

Sheet 1
Sheet 2

Any help would be appreciated thanks !!

Body:
Something like this should work:

Sub JoinGroupOnPN()
    Dim PartGroupSheet As Worksheet
    Dim v, c As Range, rngSrch As Range

    Set PartGroupSheet = ActiveWorkbook.Worksheets("PartGroup")

    With ActiveWorkbook.Worksheets("OEE Report")
        Set rngSrch = .Range(.Range("B2"), .Cells(.Rows.Count, "B").End(xlUp))
    End With

    For Each c In rngSrch.Cells
        If Len(c.Value) > 0 Then
            'do not use WorksheetFunction here
            v = Application.VLookup(c.Value, PartGroupSheet.Range("B:C"), 2, False)
            c.Offset(0, 1).Value = IIf(IsError(v), "No match", v)
        End If
    Next c
End Sub


来源: stackexchange

问:
A better way to extract some strings from a string
Is there a better way to extract substring from a string ?

I want to extract characters that are surrounded with " and " in a string. I used substring() and indexOf() methods but I sure there is a better way.

For example, for this input:

I "learn" java "and" python.

The desired output would be:

learn

and

Here is what I tried:

```<code>public static void main(String[] args) {
    Scanner putIn = new Scanner(System.in);
    String input = putIn.nextLine();
    String subInput = input.substring(input.indexOf("\"") + 1);
    System.out.println(subInput);
    String strOne= subInput.substring(0, subInput.indexOf("\""));
    System.out.println(strOne);
    String strTwo = subInput.substring(strOne.length() + 4, subInput.length() - 2);
    System.out.println(strTwo);
}
</code>```

答:
I think regular expressions are perfect for your cause here. With the Pattern class, you can compile a regular expression and return the matches. Here are the details:

https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

For the specific regex you want for extracting between quotes, you can reference the discussion here:

RegEx: Grabbing values between quotation marks

The regex solution is nice, because you can easily generalize it beyond your current use case.

ContentLicense: CC BY-SA 4.0

Body:
Is there a better way to extract substring from a string ?

I want to extract characters that are surrounded with " and " in a string. I used substring() and indexOf() methods but I sure there is a better way.

For example, for this input:

I "learn" java "and" python.

The desired output would be:

learn

and

Here is what I tried:

public static void main(String[] args) {
    Scanner putIn = new Scanner(System.in);
    String input = putIn.nextLine();
    String subInput = input.substring(input.indexOf("\"") + 1);
    System.out.println(subInput);
    String strOne= subInput.substring(0, subInput.indexOf("\""));
    System.out.println(strOne);
    String strTwo = subInput.substring(strOne.length() + 4, subInput.length() - 2);
    System.out.println(strTwo);
}


问:
Is there a way to tick the "Use global Veracode user credentials" checkbox using a DSL groovy script?
I am creating a Jenkins job with a DSL Groovy script to add the Veracode plugin. I am looking for a way to tick the "Use global Veracode user credentials" check box.

It works fine with the code I have and adds the checkbox but doesn't check it for me and is looking for credentials. I would like to use global credentials. I have added it under the publishers block. As you can see in my code, under the credentials section, I leave the  credentials blank as I don't want to specify any of those. Clicking the "Use global Veracode user credentials" check box, omits these params and uses the global params specified under manage jenkins.

My problem is how to get this checkbox ticked using the script.

```<code>    publishers {
            //extendedEmail Utilities.getExtendedEmail("Scan_Services", false, false)
            extendedEmail Utilities.getExtendedEmailRequester("Scan_Services", false, false)

            veracodeNotifier {
                // Enter the name of the application.
                appname("xDistributor")
                // Enter the business criticality for the application.
                criticality("Very High")
                // Enter a name for the static scan you want to submit to the Veracode Platform for this application.
                version("$BUILD_TIMESTAMP" + " Services_Scan")
                // Enter the filepaths of the files to upload for scanning, represented as a comma-separated list of    ant-style include patterns relative to the job's workspace root directory.
                uploadincludespattern("**/Services/webapps/services.war")
                createprofile(false)
                sandboxname("")
                createsandbox(false)
                filenamepattern("")
                replacementpattern("")
                uploadexcludespattern("")
                scanincludespattern("")
                scanexcludespattern("")
                waitForScan(false)
                timeout("")
                credentials {
                    vapicredential("")
                    vuser("")
                    vpassword("")
                }

            }
        }
</code>```

答:
I wasn't able to find any documentation from Veracode on this, so I ended up having to decompile the plugin to figure it out. This can be accomplished by setting the credentials object to a null value.

```<code>job('job-name') {
    publishers {
        veracodeNotifier {
            credentials(null)
        }
    }
}
</code>```

The way this works, is the configuration settings for the Veracode plugin is not checking for a value of a field, it is checking that the credentials object is null, and that the global credentials are set.

Body:
I am creating a Jenkins job with a DSL Groovy script to add the Veracode plugin. I am looking for a way to tick the "Use global Veracode user credentials" check box.

It works fine with the code I have and adds the checkbox but doesn't check it for me and is looking for credentials. I would like to use global credentials. I have added it under the publishers block. As you can see in my code, under the credentials section, I leave the  credentials blank as I don't want to specify any of those. Clicking the "Use global Veracode user credentials" check box, omits these params and uses the global params specified under manage jenkins.

My problem is how to get this checkbox ticked using the script.

    publishers {
            //extendedEmail Utilities.getExtendedEmail("Scan_Services", false, false)
            extendedEmail Utilities.getExtendedEmailRequester("Scan_Services", false, false)

            veracodeNotifier {
                // Enter the name of the application.
                appname("xDistributor")
                // Enter the business criticality for the application.
                criticality("Very High")
                // Enter a name for the static scan you want to submit to the Veracode Platform for this application.
                version("$BUILD_TIMESTAMP" + " Services_Scan")
                // Enter the filepaths of the files to upload for scanning, represented as a comma-separated list of    ant-style include patterns relative to the job's workspace root directory.
                uploadincludespattern("**/Services/webapps/services.war")
                createprofile(false)
                sandboxname("")
                createsandbox(false)
                filenamepattern("")
                replacementpattern("")
                uploadexcludespattern("")
                scanincludespattern("")
                scanexcludespattern("")
                waitForScan(false)
                timeout("")
                credentials {
                    vapicredential("")
                    vuser("")
                    vpassword("")
                }

            }
        }

Body:
I wasn't able to find any documentation from Veracode on this, so I ended up having to decompile the plugin to figure it out. This can be accomplished by setting the credentials object to a null value.

job('job-name') {
    publishers {
        veracodeNotifier {
            credentials(null)
        }
    }
}

The way this works, is the configuration settings for the Veracode plugin is not checking for a value of a field, it is checking that the credentials object is null, and that the global credentials are set.


问:
While using sed command i receive the following error : Function cannot be parsed. Any Solutions or reason for this?
I need to replace a particular character in a text file with another character. For example, replacing "E" with "A":

Apple ice → ApplA Ica

While executing sed 's/E/A' < apple.txt > app.txt I receive the error

function cannot be parsed

Please help! I need to automate this using Antscript.

答:
You should terminate your sed command with a slash (/) and I guess you want to exchange all occurences of E with A? Then you have to add a g for a global substitution:

```<code>sed 's/E/A/g' app.txt
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You should terminate your sed command with a slash (/) and I guess you want to exchange all occurences of E with A? Then you have to add a g for a global substitution:

sed 's/E/A/g' app.txt


问:
Can AMIs be combined?
Is it possible to combine AMIs? If yes, what are the ways to do so?
Working with DL on Cloud and want to know if the above scenario is possible.</p>

答:
No.

An Amazon Machine Image (AMI) is a copy of a disk that was attached to an Amazon EC2 instance. AMIs cannot be edited.

You could launch an EC2 instance from an AMI, make changes and then create a new AMI.

Title: Can AMIs be combined?


问:
What does a constant with linear trend (‘ct’) line look like?
In the SARIMA model, the trend parameter can be specified:

'n' indicates no trend;

'c' indicates constant;

't' indicates a linear trend with time;

'ct' indicates a constant with linear trend.

The first three are very straightforward, but what does a constant with linear trend look like?

答:
Basically it's a linear trend where the intercept is nonzero. Here are some examples of the trends:

c: trend = constant, where the "constant" value is like "10" or "1.2345"

t: trend = t, where t is the observation number, t = 1, 2, 3, ...

ct: trend = constant + t, where the "constant" value is like "10" or "1.2345" and t is the observation number, t = 1, 2, 3, ...

Finally, in the nc case, trend = 0


问:
Need C# client to connect to server with low latency bi-direction communication
I'm in the process of learning C# and just need a pointing in the right direction. I want to build a client in C# that communicates with a server running PHP/mySQL. There will need to be almost constant communication between the two. It will be for a game, so low-latency and bi-directional communication. I'm not looking for an exact how-to, but rather what method I need to use to connect the two for the fastest and most reliable connection. I have read others use XML, but that seems like it would be slower if used near-constantly, like once or more a second, but I could be totally wrong. Thanks in advance!</p>

答:
Normally communication with those characteristics is made over a persistent TCP connection. C# offers lots of ready-to-use functionality in the System.Net.Sockets namespace (start looking from TcpClient and TcpListener; there are also more low-level interfaces if you need them).

The important question here is: what do you mean exactly "server running PHP"? If the server offers only an HTTP interface, then you would find it more natural to communicate not with sockets but with the WebClient or the more low-level HttpWebRequest classes instead.


问:
Build request with IP address
I would like to know how to build a request with server's IP address (not URL).

Actually I start with a given URL and then with the help of lenses rebuild the request:

```<code>   connect = do
        request' <- parseRequest "http://localhost"
        let request = setRequestMethod "POST"
                    $ setRequestHost (S8.pack ("xx.xxx.xxx.xxx"))
                    $ ...
</code>```

It works fine but it's inelegant, clumsy code.

答:
This is more or less what you're supposed to do when you create a Request from scratch, except there's a predefined defaultRequest equivalent to http://localhost.  So, use:

```<code>request = setRequestMethod "POST"
        $ setRequestHost (S8.pack "xx.xxx.xxx.xxx")
        $ ...
        $ defaultRequest
</code>```

and I think you're doing it right.

Title: Build request with IP address

Body:
I would like to know how to build a request with server's IP address (not URL).

Actually I start with a given URL and then with the help of lenses rebuild the request:

   connect = do
        request' <- parseRequest "http://localhost"
        let request = setRequestMethod "POST"
                    $ setRequestHost (S8.pack ("xx.xxx.xxx.xxx"))
                    $ ...

It works fine but it's inelegant, clumsy code.

Body:
This is more or less what you're supposed to do when you create a Request from scratch, except there's a predefined defaultRequest equivalent to http://localhost.  So, use:

request = setRequestMethod "POST"
        $ setRequestHost (S8.pack "xx.xxx.xxx.xxx")
        $ ...
        $ defaultRequest

and I think you're doing it right.


问:
I have a DF with 2 columns. I wanna do a boolean check on it
I have a DF that has 3 columns and i wanna perform a Boolean check. The code is shown below.

```<code>import pandas as pd
df = pd.DataFrame({
    'Col1':[A,A,A,B,B,C,C,C],
    'Col2':[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5], [1, 2, 3, 4, 5,6,7] ,[1, 2, 3, 4, 5,6,7],[1, 2, 3, 4, 5,6,7] ]
    'Col3': [[1, 2, 3, 4],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9],[1, 2, 3, 4, 5],[1, 2, 3], [1, 2, 3, 4, 5,6,7] ,[1, 2, 3],[1, 2, 3, 4] ]
})
</code>```

I want a DF that gives me for a unique value of Col1 and if one row of Col2, Col3 are equal, print True, else False.  The result i would like to see is:

```<code>'Col1' 'Col2'                         'Col3'          'Col4'
  A    [1,2,3,4,5,6,7,8,9,10,11,12]  [1,2,3,4]         False

print(map(type, df['Col2']) == map(type,df['Col3']))
</code>```

This returned me value true, but I want it as a new column Col4 in the df

For multiple codes i tried , I always found errors as unhashable type: 'list'

Body:
I have a DF that has 3 columns and i wanna perform a Boolean check. The code is shown below.

import pandas as pd
df = pd.DataFrame({
    'Col1':[A,A,A,B,B,C,C,C],
    'Col2':[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5], [1, 2, 3, 4, 5,6,7] ,[1, 2, 3, 4, 5,6,7],[1, 2, 3, 4, 5,6,7] ]
    'Col3': [[1, 2, 3, 4],[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],[1, 2, 3, 4, 5, 6, 7, 8, 9],[1, 2, 3, 4, 5],[1, 2, 3], [1, 2, 3, 4, 5,6,7] ,[1, 2, 3],[1, 2, 3, 4] ]
})

I want a DF that gives me for a unique value of Col1 and if one row of Col2, Col3 are equal, print True, else False.  The result i would like to see is:

'Col1' 'Col2'                         'Col3'          'Col4'
  A    [1,2,3,4,5,6,7,8,9,10,11,12]  [1,2,3,4]         False

print(map(type, df['Col2']) == map(type,df['Col3']))

This returned me value true, but I want it as a new column Col4 in the df

For multiple codes i tried , I always found errors as unhashable type: 'list'

Body:
If you want to apply this logic per group of Col1, use groupby.apply:

df['Col4'] = df.groupby('Col1').apply(lambda x: x['Col2'].eq(x['Col3'])).values

  Col1                                     Col2                                     Col3   Col4
0    A  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]                             [1, 2, 3, 4]  False
1    A  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]   True
2    A  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]              [1, 2, 3, 4, 5, 6, 7, 8, 9]  False
3    B                          [1, 2, 3, 4, 5]                          [1, 2, 3, 4, 5]   True
4    B                          [1, 2, 3, 4, 5]                                [1, 2, 3]  False
5    C                    [1, 2, 3, 4, 5, 6, 7]                    [1, 2, 3, 4, 5, 6, 7]   True
6    C                    [1, 2, 3, 4, 5, 6, 7]                                [1, 2, 3]  False
7    C                    [1, 2, 3, 4, 5, 6, 7]                             [1, 2, 3, 4]  False

Not taking the groups into account, gives same output in this case, using eq

df['Col4'] = df['Col2'].eq(df['Col3'])

  Col1                                     Col2                                     Col3   Col4
0    A  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]                             [1, 2, 3, 4]  False
1    A  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]   True
2    A  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]              [1, 2, 3, 4, 5, 6, 7, 8, 9]  False
3    B                          [1, 2, 3, 4, 5]                          [1, 2, 3, 4, 5]   True
4    B                          [1, 2, 3, 4, 5]                                [1, 2, 3]  False
5    C                    [1, 2, 3, 4, 5, 6, 7]                    [1, 2, 3, 4, 5, 6, 7]   True
6    C                    [1, 2, 3, 4, 5, 6, 7]                                [1, 2, 3]  False
7    C                    [1, 2, 3, 4, 5, 6, 7]                             [1, 2, 3, 4]  False


问:
How to style a echo function with multiple variables
I would like my code to display two variables on the same echo function, however, I want them to style them differently. Making the 'id' smaller and a different color. I do not know how to separate the two variables so I can add some code in-between.

I tried to use a second echo function, but then the 'id' displays at the bottom, separate from the 'quote' function.

```<code>echo "<p class='dash'>---------</p>","<p class='center' style='color:white' align='center'>" .$row['quote'] .$row['id'];
</code>```

The  output will just display like this (bold text for output):
--------
 "This is the quote variable"1

 However, I need is displayed like this:

-------
"This is the quote variable"
1

So basically what is needed is some way to add style to the second one. (I already styled the first one)

答:
Another way which eliminates use of dot concatenation operator:

```<code><?php
$row["quote"] = "This is the quote";
$row["id"] = 1;
$p = [];
$p[0] = "<p class='dash'>---------</p>\n";
$p[1] = "<p class='center' style='color:white' align='center'>$row[quote]<br>\n$row[id]</p>\n";
echo $p[0],$p[1];
</code>```

live code here

Example HTML implementation:

.dash {
  color: blue;
  font-weight: 300;
}

.center {
  text-algin: center font-weight:900;
}

body {
background:navy
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class='dash'>---------</p>
<p class='center' style='color:white' align='center'>This is the quote<br> 1
</p></code>```

Body:
I would like my code to display two variables on the same echo function, however, I want them to style them differently. Making the 'id' smaller and a different color. I do not know how to separate the two variables so I can add some code in-between.

I tried to use a second echo function, but then the 'id' displays at the bottom, separate from the 'quote' function.

echo "
---------
","
" .$row['quote'] .$row['id'];

The  output will just display like this (bold text for output):
--------
 "This is the quote variable"1

 However, I need is displayed like this:

-------
"This is the quote variable"
1

So basically what is needed is some way to add style to the second one. (I already styled the first one)

Body:
Another way which eliminates use of dot concatenation operator:

<?php
$row["quote"] = "This is the quote";
$row["id"] = 1;
$p = [];
$p[0] = "<p class='dash'>---------</p>\n";
$p[1] = "<p class='center' style='color:white' align='center'>$row[quote]<br>\n$row[id]</p>\n";
echo $p[0],$p[1];

live code here

Example HTML implementation:

.dash {
  color: blue;
  font-weight: 300;
}

.center {
  text-algin: center font-weight:900;
}

body {
background:navy
}

<p class='dash'>---------</p>
<p class='center' style='color:white' align='center'>This is the quote<br> 1
</p>


问:
SVG filter not showing up in Firefox, working fine in Chrome
I want a piece of dark text on dark background to have a white glow outside of it. Although the default drop shadow filter in CSS (like filter: drop-shadow(2px 2px 2px black)) officially should support a 'spread-radius' fourth attribute, support for this attribute is basically non-existent. Without this extra spread, the drop shadow will not be big enough to allow the text to be read.

So, I decided to define my own filter in an SVG tag, including a dilation operation to implement the extra spread, and apply that to the text instead. This filter works fine in Chrome, but causes the text to become entirely invisible in Firefox (both tested under Ubuntu 14.04). According to caniuse.com (usually very reliable, I've found), Firefox should support the filter perfectly fine.

The HTML code with SVG filter:

```<code><svg xmlns="http://www.w3.org/2000/svg">
<defs>

<filter id="my-drop-shadow" x="0" y="0" width="200%" height="200%">

    <feColorMatrix type="matrix" values=
                "0 0 0 0   1
                 0 0 0 0   1
                 0 0 0 0   1
                 0 0 0 1   0"/>
    <feMorphology operator="dilate" radius="2" />
    <feGaussianBlur stdDeviation="2" in="coloredOut" result="coloredBlur"/>
    <feMerge>
        <feMergeNode in="coloredBlur"/>
        <feMergeNode in="SourceGraphic"/>
    </feMerge>

</filter>

</defs>
</svg>

<p>Hello there.</p>
</code>```

The CSS:

```<code>body {
    color: #000; background: #002;
    font-family: serif; font-size: 30px;
    font-weight: bold;
}

p {
    -webkit-filter: url(#my-drop-shadow);
    filter: url(#my-drop-shadow);
}
</code>```

Result on Chrome (version 46.0.2490.80 (64-bit)):

Result on Firefox (version 42.0):

I've put the code above in a working CodePen (edit: note that I've now updated the CodePen to reflect @RobertLongson's answer and it works; see below though for why this was not the full answer).

Any ideas? Typo I haven't spotted in my SVG code?

答: For me, it was that I had a display:none on the parent <svg> tag which I think causes Firefox to completely ignore the filter tags inside. So changing <svg style="display:none"> to <svg style="position:absolute; height:0"> did the trick.

Body:
I want a piece of dark text on dark background to have a white glow outside of it. Although the default drop shadow filter in CSS (like filter: drop-shadow(2px 2px 2px black)) officially should support a 'spread-radius' fourth attribute, support for this attribute is basically non-existent. Without this extra spread, the drop shadow will not be big enough to allow the text to be read.

So, I decided to define my own filter in an SVG tag, including a dilation operation to implement the extra spread, and apply that to the text instead. This filter works fine in Chrome, but causes the text to become entirely invisible in Firefox (both tested under Ubuntu 14.04). According to caniuse.com (usually very reliable, I've found), Firefox should support the filter perfectly fine.

The HTML code with SVG filter:

<svg xmlns="http://www.w3.org/2000/svg">
<defs>

<filter id="my-drop-shadow" x="0" y="0" width="200%" height="200%">

    <feColorMatrix type="matrix" values=
                "0 0 0 0   1
                 0 0 0 0   1
                 0 0 0 0   1
                 0 0 0 1   0"/>
    <feMorphology operator="dilate" radius="2" />
    <feGaussianBlur stdDeviation="2" in="coloredOut" result="coloredBlur"/>
    <feMerge>
        <feMergeNode in="coloredBlur"/>
        <feMergeNode in="SourceGraphic"/>
    </feMerge>

</filter>

</defs>
</svg>

Hello there.

The CSS:

body {
    color: #000; background: #002;
    font-family: serif; font-size: 30px;
    font-weight: bold;
}

p {
    -webkit-filter: url(#my-drop-shadow);
    filter: url(#my-drop-shadow);
}

Result on Chrome (version 46.0.2490.80 (64-bit)):

Result on Firefox (version 42.0):

I've put the code above in a working CodePen (edit: note that I've now updated the CodePen to reflect @RobertLongson's answer and it works; see below though for why this was not the full answer).

Any ideas? Typo I haven't spotted in my SVG code?


问:
How to test if Apostrophe is in "editor mode" in a twig template
I am wanting to apply conditional CSS and template code while my Apostrophe CMS installation in "editor mode." However I have not been able to find anything in the documentation.

I have attempted to use the data.global object and the data.page object with no luck.

I am hoping to use something like

```<code>{% if data.global.edit %}
<br>
<br>
{% endif %}
</code>```

答: You can check for data.page._edit or data.piece._edit, depending on whether it's a page template or a show.html template for a piece, to see if a user has editing privileges. If you're using apostrophe-workflow and you want to see if the user is in draft mode (edit mode) vs live mode you can check data.workflowMode as well.

Body:
I am wanting to apply conditional CSS and template code while my Apostrophe CMS installation in "editor mode." However I have not been able to find anything in the documentation.

I have attempted to use the data.global object and the data.page object with no luck.

I am hoping to use something like

{% if data.global.edit %}

{% endif %}


问:
Appending a string
I am building a chart and need to have all of the days of a given month represented for applications submitted.  On some days, there may be 5 and on others there may be 0.  I am getting my data from an applications table but I need append the string for dates that do not have a value. For example today is 05/29 and 3 people applied. On 05/21, 2 people applied. In between (and before that) no others applied. So I need to get those dates and store a 0 value for them.

Below is what I am using to bring back and group the data:

```<code>SELECT DISTINCT to_char ("applicationdate",'mm') AS applicationmonth
      , to_char ("applicationdate",'dd') AS applicationdate
      , to_char ("applicationdate", 'yyyy') AS applicationyear
      , term
      , COUNT(*) AS count
FROM  campapplications.basketball
WHERE term = 'SU'
GROUP BY applicationdate, term
ORDER BY applicationdate, term
</code>```

At the end of the day, I am doing an insert.

I have looked other places but could not really get any input outside of using the listAppend() function.

答:
It's not clear how "appending a string" relates to charting or inserts... However, just focusing on the query, either a calendar table or CTE could be used generate all dates within a specific date range. (For larger data sets, a calendar table is usually better). Once you have the dates, outer join them back to your application table to get the counts for each date.

You didn't mention which DBMS you are using, but from the syntax I'm guessing Oracle. Assuming the "applicationDate" column ONLY contains a date (no time), the query below would return a count for all dates within the given range: #startDate# and #endDate#. Adjust the dates as needed.

SQL: http://sqlfiddle.com/#!4/c09877/2

```<code>WITH CTE(TheDate) AS
(
    SELECT FromDate+level-1
    FROM (
        SELECT <cfqueryparam value="#startDate#" cfsqltype="cf_sql_date"> AS FromDate
               , <cfqueryparam value="#endDate#" cfsqltype="cf_sql_date">  AS ToDate
        FROM   dual
     ) d
     CONNECT BY LEVEL <=  ToDate - FromDate + 1
)
SELECT TheDate
      , COUNT(b.applicationDate) AS count
FROM   cte LEFT JOIN basketball b ON b.applicationDate = cte.TheDate
GROUP BY TheDate
ORDER BY TheDate
;
</code>```

Sample Results:

```<code>|              THEDATE | COUNT |
|----------------------|-------|
| 2019-05-21T00:00:00Z |     2 |
| 2019-05-22T00:00:00Z |     0 |
| 2019-05-23T00:00:00Z |     0 |
| 2019-05-24T00:00:00Z |     0 |
| 2019-05-25T00:00:00Z |     0 |
| 2019-05-26T00:00:00Z |     0 |
| 2019-05-27T00:00:00Z |     0 |
| 2019-05-28T00:00:00Z |     0 |
| 2019-05-29T00:00:00Z |     3 |
</code>```

Update:

I'm not great with PostgreSQL, but this thread shows how to generate a date range. Just replace the hard coded dates with cfqueryparam.

SQL: http://sqlfiddle.com/#!15/2a0a7/4

```<code>SELECT TheDate
      , COUNT(b.applicationDate) AS count
FROM  generate_series
        ( '2019-05-21'::date
        , '2019-05-29'::date
        , '1 day'::interval) TheDate
       LEFT JOIN basketball b ON b.applicationDate = TheDate
GROUP BY TheDate
ORDER BY TheDate
</code>```

Title: Appending a string

Body:
I am building a chart and need to have all of the days of a given month represented for applications submitted.  On some days, there may be 5 and on others there may be 0.  I am getting my data from an applications table but I need append the string for dates that do not have a value. For example today is 05/29 and 3 people applied. On 05/21, 2 people applied. In between (and before that) no others applied. So I need to get those dates and store a 0 value for them.

Below is what I am using to bring back and group the data:

SELECT DISTINCT to_char ("applicationdate",'mm') AS applicationmonth
      , to_char ("applicationdate",'dd') AS applicationdate
      , to_char ("applicationdate", 'yyyy') AS applicationyear
      , term
      , COUNT(*) AS count
FROM  campapplications.basketball
WHERE term = 'SU'
GROUP BY applicationdate, term
ORDER BY applicationdate, term

At the end of the day, I am doing an insert.

I have looked other places but could not really get any input outside of using the listAppend() function.

Body:
It's not clear how "appending a string" relates to charting or inserts... However, just focusing on the query, either a calendar table or CTE could be used generate all dates within a specific date range. (For larger data sets, a calendar table is usually better). Once you have the dates, outer join them back to your application table to get the counts for each date.

You didn't mention which DBMS you are using, but from the syntax I'm guessing Oracle. Assuming the "applicationDate" column ONLY contains a date (no time), the query below would return a count for all dates within the given range: #startDate# and #endDate#. Adjust the dates as needed.

SQL: http://sqlfiddle.com/#!4/c09877/2

WITH CTE(TheDate) AS
(
    SELECT FromDate+level-1
    FROM (
        SELECT <cfqueryparam value="#startDate#" cfsqltype="cf_sql_date"> AS FromDate
               , <cfqueryparam value="#endDate#" cfsqltype="cf_sql_date">  AS ToDate
        FROM   dual
     ) d
     CONNECT BY LEVEL <=  ToDate - FromDate + 1
)
SELECT TheDate
      , COUNT(b.applicationDate) AS count
FROM   cte LEFT JOIN basketball b ON b.applicationDate = cte.TheDate
GROUP BY TheDate
ORDER BY TheDate
;

Sample Results:

|              THEDATE | COUNT |
|----------------------|-------|
| 2019-05-21T00:00:00Z |     2 |
| 2019-05-22T00:00:00Z |     0 |
| 2019-05-23T00:00:00Z |     0 |
| 2019-05-24T00:00:00Z |     0 |
| 2019-05-25T00:00:00Z |     0 |
| 2019-05-26T00:00:00Z |     0 |
| 2019-05-27T00:00:00Z |     0 |
| 2019-05-28T00:00:00Z |     0 |
| 2019-05-29T00:00:00Z |     3 |

Update:

I'm not great with PostgreSQL, but this thread shows how to generate a date range. Just replace the hard coded dates with cfqueryparam.

SQL: http://sqlfiddle.com/#!15/2a0a7/4

SELECT TheDate
      , COUNT(b.applicationDate) AS count
FROM  generate_series
        ( '2019-05-21'::date
        , '2019-05-29'::date
        , '1 day'::interval) TheDate
       LEFT JOIN basketball b ON b.applicationDate = TheDate
GROUP BY TheDate
ORDER BY TheDate


问:
write python script to run the shell script?
I run the svn status got the modified files :

```<code>  svn status
  ?       .settings
  ?       .buildpath
  ?       .directory
  A       A.php
  M       B.php
  D       html/C.html
  M       html/D.fr
  M       api/E.api
  M       F.php
  ..
</code>```

After I want to keep all of these files

zcvf MY.tar.gz all files that svn stat display
(not include ? just M,A,D)

My idea is to create the python script can run the shell,because right now to do this I just copy the file name one by one.

zcvf MY.tar.gz all the files that we run svn stat

Anybody could guide how to do this or some related tutorial? But if you think it difficult than copy && paste I will ignore my trying?

thanks

答:
subprocess is the Pythonic way, but using a small bash one-liner could be a shorter idea.

Bash one-liner

```<code>svn status | egrep "^  M" | awk '{s=s $2 " "} END {print "tar cvfz MY.tar "s}'
</code>```

Subprocess

```<code>import subprocess as sp
p=sp.Popen('svn status', shell=True, stdout=sp.PIPE,
                                     stderr=sp.PIPE).communicate()[0]
files=[]
for line in p:
     if line.strip().find('M')==0:
          files.append(line.split(' ')[1].strip())

files=' '.join(files)
sp.Popen('tar cvfz MY.tar.gz '+files, shell=True).communicate()
</code>```

Body:
I run the svn status got the modified files :

  svn status
  ?       .settings
  ?       .buildpath
  ?       .directory
  A       A.php
  M       B.php
  D       html/C.html
  M       html/D.fr
  M       api/E.api
  M       F.php
  ..

After I want to keep all of these files

zcvf MY.tar.gz all files that svn stat display
(not include ? just M,A,D)

My idea is to create the python script can run the shell,because right now to do this I just copy the file name one by one.

zcvf MY.tar.gz all the files that we run svn stat

Anybody could guide how to do this or some related tutorial? But if you think it difficult than copy && paste I will ignore my trying?

thanks

Body:
subprocess is the Pythonic way, but using a small bash one-liner could be a shorter idea.

Bash one-liner

svn status | egrep "^  M" | awk '{s=s $2 " "} END {print "tar cvfz MY.tar "s}'

Subprocess

import subprocess as sp
p=sp.Popen('svn status', shell=True, stdout=sp.PIPE,
                                     stderr=sp.PIPE).communicate()[0]
files=[]
for line in p:
     if line.strip().find('M')==0:
          files.append(line.split(' ')[1].strip())

files=' '.join(files)
sp.Popen('tar cvfz MY.tar.gz '+files, shell=True).communicate()


问:
Centre a Navigation Bar with HTML/CSS
I have no formal training in HTML and CSS, but web development is a hobby of mine, and I have a problem that I am really struggling to get for my personal website.  Here:

You can see that the elements of my unordered list are not centred on the black unordered list background; in the body tag:

```<code>        <ul>
            <li><a href="homepage.html">Home</a></li>
            <li><a href="resume.html">Bio</a></li>
            <li><a href="projects.html">Projects</a></li>
            <li><a href="blog.html">Blog</a></li>
            <li><a href="store.html">Store</a></li>
            <li><a href="contact.html">Contact</a></li>
        </ul>
</code>```

Previously, in the head tag, I declare the style for each of these elements in the document, and what to do if the cursor hovers over it:

```<code>    <style>
        ul {
            list-style-type: none;
            background-color: black;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        li {
            float: left;
        }
        li a {
            display: block;
            color: white;
            text-align: center;
            border-width: thick;
            padding: 14px 16px;
            text-decoration: none;
        }
        li a:hover {
            background-color: darkgray;
        }
    </style>
</code>```

The concept I've tried more times than not is if you have a div tag around li and you centre that.  But, I am going in circles.  So how do you centre the white lettering while keeping an equal amount of black space on either side?  Thank you very much!

For reference, I have branched out from this tutorial.

答:
Add a div wrapper to ul element:

```<code><div class="ul-wrapper">
    <ul>
        <li><a href="homepage.html">Home</a></li>
        <li><a href="resume.html">Bio</a></li>
        <li><a href="projects.html">Projects</a></li>
        <li><a href="blog.html">Blog</a></li>
        <li><a href="store.html">Store</a></li>
        <li><a href="contact.html">Contact</a></li>
    </ul>
 </div>
</code>```

And then set styles for div like this:

```<code>.ul-wrapper {
    text-align: center;
    background-color: black;
}
</code>```

And add display: inline-block; to ul styles.

```<code>ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
            overflow: hidden;
            display: inline-block;
        }
</code>```

Title: Centre a Navigation Bar with HTML/CSS

Body:
I have no formal training in HTML and CSS, but web development is a hobby of mine, and I have a problem that I am really struggling to get for my personal website.  Here:

You can see that the elements of my unordered list are not centred on the black unordered list background; in the body tag:

Home

Bio

Projects

Blog

Store

Contact

Previously, in the head tag, I declare the style for each of these elements in the document, and what to do if the cursor hovers over it:

The concept I've tried more times than not is if you have a div tag around li and you centre that.  But, I am going in circles.  So how do you centre the white lettering while keeping an equal amount of black space on either side?  Thank you very much!

For reference, I have branched out from this tutorial.

Body:
Add a div wrapper to ul element:

<div class="ul-wrapper">
    <ul>
        <li><a href="homepage.html">Home</a></li>
        <li><a href="resume.html">Bio</a></li>
        <li><a href="projects.html">Projects</a></li>
        <li><a href="blog.html">Blog</a></li>
        <li><a href="store.html">Store</a></li>
        <li><a href="contact.html">Contact</a></li>
    </ul>
 </div>

And then set styles for div like this:

.ul-wrapper {
    text-align: center;
    background-color: black;
}

And add display: inline-block; to ul styles.

ul {
            list-style-type: none;
            margin: 0;
            padding: 0;
            overflow: hidden;
            display: inline-block;
        }


问:
How to make parsedatetime ignore the colon after date?
I am reading a date string from a log file and converting it to date using parsedatetime:

```<code>c = parsedatetime.Calendar()
d = c.parse("29/May/2019:00:00:00 +0000")
</code>```

which gives

```<code>(time.struct_time(tm_year=2019, tm_mon=5, tm_mday=29, tm_hour=17, tm_min=12, tm_sec=45, tm_wday=2, tm_yday=149, tm_isdst=1), 0)
</code>```

where tm_hour, tm_min, tm_sec correspond to the current time, rather than being 0 as in the date string passed to parse.  If I remove the : after the year, I get the right output:

```<code>d = c.parse("29/May/2019 00:00:00 +0000")
</code>```

which gives

```<code>(time.struct_time(tm_year=2019, tm_mon=5, tm_mday=29, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=149, tm_isdst=1), 2)
</code>```

I don't like to modify my date string because that forces me to assume the date format.

Is there a way to make parse ignore the : after the year?

答:
Yes, there is. You can do this using by the .replace method, like so:

c = parsedatetime.Calendar()
e = "29/May/2019:00:00:00 +0000"
e.replace(":", " ", 1)
d = c.parse(e)
```

The first line that I added first defines what you want to parse as a variable in order to make handling it much easier. The next line first finds all instances of a ":" in the string, as specified by the first argument. The second argument specifies what to replace it with, in this case, a space. The third (optional) argument specifies how many times to replace, starting from the left of the string. The default value for this argument is all, which replaces all instances of that character in the string.

You can find more information on the .replace() method here.

Body:
I am reading a date string from a log file and converting it to date using parsedatetime:

c = parsedatetime.Calendar()
d = c.parse("29/May/2019:00:00:00 +0000")

which gives

(time.struct_time(tm_year=2019, tm_mon=5, tm_mday=29, tm_hour=17, tm_min=12, tm_sec=45, tm_wday=2, tm_yday=149, tm_isdst=1), 0)

where tm_hour, tm_min, tm_sec correspond to the current time, rather than being 0 as in the date string passed to parse.  If I remove the : after the year, I get the right output:

d = c.parse("29/May/2019 00:00:00 +0000")

which gives

(time.struct_time(tm_year=2019, tm_mon=5, tm_mday=29, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=149, tm_isdst=1), 2)

I don't like to modify my date string because that forces me to assume the date format.

Is there a way to make parse ignore the : after the year?

Body:
Yes, there is. You can do this using by the .replace method, like so:

c = parsedatetime.Calendar()
e = "29/May/2019:00:00:00 +0000"
e.replace(":", " ", 1)
d = c.parse(e)

The first line that I added first defines what you want to parse as a variable in order to make handling it much easier. The next line first finds all instances of a ":" in the string, as specified by the first argument. The second argument specifies what to replace it with, in this case, a space. The third (optional) argument specifies how many times to replace, starting from the left of the string. The default value for this argument is all, which replaces all instances of that character in the string.

You can find more information on the .replace() method here.


问:
Unable to change table height
I have a table and i want to change its height but when i add the hieght element in the css, nothing changes, i also tried a solution on stackoverflow (Not able to set table height) but none seem to be working. What am i doing wrong?

HTML -

```<code> <div class="tableDiv">
       <table class="table table-bordered table-condensed" id="StoreData">
         <thead>
             <tr>
                <th>County / Admin district</th>
                <th>Postcode</th>
                <th>Longitude</th>
                <th>Latitude</th>
             </tr>
           </thead>
           {% for Postcode, LongLat in LocationData.items() %}
           <tr>
             <td>{{ LongLat[0] }}</td>
             <td>{{ Postcode }}</td>
             <td>{{ LongLat[1] }}</td>
             <td>{{ LongLat[2] }}</td>
           </tr>
          {% endfor %}
        </table>
      </div>
</code>```

CSS -

```<code>   <style media="screen">
      html, body, table {
      height: 100%;
      }
      .tableDiv {
      height: 50%;
      }
      table thead {
      position: sticky;
      position: -webkit-sticky;
      top: 0;
      z-index: 999;
      background-color: white;
      color: black;
      }
      #storeform {
      margin-left: 700px;
      margin-top: 50px;
      margin-bottom: 50px;
      }
      #StoreData {
      margin: 10px auto;
      padding: 10;
      width: 1250px;
      overflow-y: scroll;
      }
   </style>
</code>```

Any help would be appreciated.

答:
Fixed Layout

Tables by nature conform to their content. Whatever is within a  influences the s width and height and in turn affects the
 and then the
, and finally the
. This default behavior is set by table-layout:auto which is only applicable to either
 or a container element with display: table or display: inline-table. The only other value for table-layout is fixed. A "fixed" table gives the developer more control over the table's behavior by honoring any specified widths given to any  (if there are no  then the  in the top tr>). Since BootStrap is used, we can assign .table-fixed class to
 the equivalent to table {table-layout: fixed}`.

Now to control the content within a  place a
 or any similar block-level element in each . If you wish to have a min-width or width of any row just apply it to just one of the
. Note there are extra rows added and each actually has content: #  or non-breaking space which prevents an empty cell from collapsing -- an alternative is to assign each
 a min-height.

The
 containing the table has the BS class .table-responsive and is at 50% of the  height (also at 100% by BS default). This layout facilitates control on the table externally.

Now we have control of the table width and indirectly the table height. When content is added, and the column width is set explicitly, the content will wrap to the next line instead of stretching the cell. In turn as the cell gains each line so does the row, etc.

Not everything is 100% due to the many unknown factors your real layout may or may not have so when commenting please do not say "It doesn't work". First establish any details that we have missed and then what you observe what's not working and how it should work/appear.

Demo

html,
body {
  height: 100%;
}

.table-responsive {
  height: 50%;
}

table {
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

<div class="table-responsive">
  <table class="table table-bordered table-condensed table-fixed" id="StoreData">
    <thead>
      <tr>
        <th class="col-xs-4">County / District</th>
        <th class="col-xs-2">Zip Code</th>
        <th class="col-xs-3">Longitude</th>
        <th class="col-xs-3">Latitude</th>
      </tr>
    </thead>
    <tr>
      <td>
        <div>Bermuda Triangle</div>
      </td>
      <td>
        <div>33036</div>
      </td>
      <td>
        <div>25.0000</div>
      </td>
      <td>
        <div>-71.0000</div>
      </td>
    </tr>
    <tr>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
    </tr>
    <tr>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
    </tr>
    <tr>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
    </tr>
    <tr>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
    </tr>
    <tr>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
    </tr>
    <tr>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
      <td>
        <div> </div>
      </td>
    </tr>
  </table>
</div>

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script></code>```

Title: Unable to change table height

Body:
I have a table and i want to change its height but when i add the hieght element in the css, nothing changes, i also tried a solution on stackoverflow (Not able to set table height) but none seem to be working. What am i doing wrong?

HTML -

                County / Admin district
                Postcode
                Longitude
                Latitude

           {% for Postcode, LongLat in LocationData.items() %}

             {{ LongLat[0] }}
             {{ Postcode }}
             {{ LongLat[1] }}
             {{ LongLat[2] }}

          {% endfor %}

CSS -

Any help would be appreciated.

Body:
Fixed Layout

Tables by nature conform to their content. Whatever is within a <td> influences the <td>s width and height and in turn affects the <tr> and then the <tbody>, and finally the <table>. This default behavior is set by table-layout:auto which is only applicable to either <table> or a container element with display: table or display: inline-table. The only other value for table-layout is fixed. A "fixed" table gives the developer more control over the table's behavior by honoring any specified widths given to any <th> (if there are no <th> then the <td> in the top tr>). Since BootStrap is used, we can assign .table-fixed class to <table> the equivalent to table {table-layout: fixed}`.

Now to control the content within a <td> place a <div> or any similar block-level element in each <td>. If you wish to have a min-width or width of any row just apply it to just one of the <div>. Note there are extra rows added and each actually has content: #&nbsp; or non-breaking space which prevents an empty cell from collapsing -- an alternative is to assign each <div> a min-height.

The <div> containing the table has the BS class .table-responsive and is at 50% of the <body> height (also at 100% by BS default). This layout facilitates control on the table externally.

Now we have control of the table width and indirectly the table height. When content is added, and the column width is set explicitly, the content will wrap to the next line instead of stretching the cell. In turn as the cell gains each line so does the row, etc.

Not everything is 100% due to the many unknown factors your real layout may or may not have so when commenting please do not say "It doesn't work". First establish any details that we have missed and then what you observe what's not working and how it should work/appear.

Demo

html,
body {
  height: 100%;
}

.table-responsive {
  height: 50%;
}

table {
  height: 100%;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

<div class="table-responsive">
  <table class="table table-bordered table-condensed table-fixed" id="StoreData">
    <thead>
      <tr>
        <th class="col-xs-4">County / District</th>
        <th class="col-xs-2">Zip Code</th>
        <th class="col-xs-3">Longitude</th>
        <th class="col-xs-3">Latitude</th>
      </tr>
    </thead>
    <tr>
      <td>
        <div>Bermuda Triangle</div>
      </td>
      <td>
        <div>33036</div>
      </td>
      <td>
        <div>25.0000</div>
      </td>
      <td>
        <div>-71.0000</div>
      </td>
    </tr>
    <tr>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
    </tr>
    <tr>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
    </tr>
    <tr>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
    </tr>
    <tr>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
    </tr>
    <tr>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
    </tr>
    <tr>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
      <td>
        <div>&nbsp;</div>
      </td>
    </tr>
  </table>
</div>

<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>


问:
SVG renders but gets cut off in Firefox only - why?
I am using d3js, which uses SVG, to create a chart.  View it at www.uscfstats.com/deltas (use 12842311 as the input value; right now it's VERY hacked together).

On Chrome, Safari, and Firefox 10 this rendered a full chart as expected, which took up the whole white box.  On later versions of Firefox, however (specifically, 15) the top 200 or so px of the SVG render, but then the rest gets cut off.

When I open up the page in Firebug, I can highlight over HTML elements and it seems like they're all there, it's as though some big white box is covering up the bottom 75% of my chart (there isn't any such HTML element, though).  I have click events on the dots, and the ones that are rendered I can click on, but the ones that aren't I can find but clicking on them does nothing.

I fixed the problem by writing

var svg = d3.select("#scatterplot").append("svg").attr("width", "100%").attr("height", "100%");

Why does this work and what happened?

答:
Insert svg in flex container and add property flex: auto; to svg.
It works for me</p>


问:
as for 'replace' usage, does it support to replace the placeholder with value in place (I mean "over-write"))?
I need to upload a file to the server side, however, before doing that I need to replace a placeholder in the file with a dynamic value.  does it support to get the placeholder replaced in place dynamically?

I noticed that I can replace the placeholder with ease using the 'replace' keyword.  The following is my script:

Given path 'common/upload'
    And multipart fields read('classpath:mainFlow/labresultUpload.json')

```<code>* def filename = 'PKU.A22backup'
* def someString = read('PKU.A22backup')
* print someString
* replace someString
  |token|value|
  |labsampleid|'123456'|
* print someString

* multipart file file = { read: "#(filename)", filename: "#(filename)"}

When method post
Then status 200
* def result = response[0].result
</code>```

However, I need to replace the placeholder in place (here, I mean over-write) dynamically and then upload the file to the server side.

答:
You have the option to supply a value instead of the file-name: https://github.com/intuit/karate#multipart-file</p>

```<code>* multipart file file = { value: "#(someString)", filename: "#(filename)" }
</code>```

Body:
I need to upload a file to the server side, however, before doing that I need to replace a placeholder in the file with a dynamic value.  does it support to get the placeholder replaced in place dynamically?

I noticed that I can replace the placeholder with ease using the 'replace' keyword.  The following is my script:

Given path 'common/upload'
    And multipart fields read('classpath:mainFlow/labresultUpload.json')

* def filename = 'PKU.A22backup'
* def someString = read('PKU.A22backup')
* print someString
* replace someString
  |token|value|
  |labsampleid|'123456'|
* print someString

* multipart file file = { read: "#(filename)", filename: "#(filename)"}

When method post
Then status 200
* def result = response[0].result

However, I need to replace the placeholder in place (here, I mean over-write) dynamically and then upload the file to the server side.

Body:
You have the option to supply a value instead of the file-name: https://github.com/intuit/karate#multipart-file

* multipart file file = { value: "#(someString)", filename: "#(filename)" }


问:
passing javascript value between php pages
I am working on my semester project and I want to pass the variable "value" on the next page (order.php). It is a value retrieved from a dropdown box that is based on another dropdown box populated by database. I have confirmed that the value is stored but I can't retrieve it on the next page.

I tried localstorage (turns NULL), session variables(undefined index "value") and putting it in the url but nothing seems to work and is very frustrating. Can someone please help me with an example? Thank you

```<code>session_start();

$conn = new mysqli("localhost", "root", "", "restaurant_ordering");
mysqli_set_charset($conn,"utf8mb4");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "select * from sector ";
$result = $conn->query($sql);

  while($row = $result->fetch_assoc()){
    $categories[] = array("id" => $row['id'], "val" => $row['name']);
  }

  $sql = "SELECT * FROM booth";
  $result = $conn->query($sql);

  while($row = $result->fetch_assoc()){
    $subcats[$row['sector_id']][] = array("id" => $row['id'], "val" => $row['name']);
  }

  $jsonCats = json_encode($categories);
  $jsonSubCats = json_encode($subcats);

?>

<!doctype html>
<html>

  <head>
    <script type='text/javascript'>
      <?php
        echo "var categories = $jsonCats; \n";
        echo "var subcats = $jsonSubCats; \n";
      ?>
      function loadCategories(){
        var select = document.getElementById("categoriesSelect");
        select.onchange = updateSubCats;
        for(var i = 0; i < categories.length; i++){
          select.options[i] = new Option(categories[i].val,categories[i].id);
        }
      }
      function updateSubCats(){
        var catSelect = this;
        var catid = this.value;
        var subcatSelect = document.getElementById("subcatsSelect");
        subcatSelect.options.length = 0;
        for(var i = 0; i < subcats[catid].length; i++){
          subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
        }
      }

    function handleSelectChange(event) {

    var selectElement = event.target;
    var value = selectElement.value;

}

    </script>
<meta charset="utf-8">
<title>New Order</title>
<link rel="stylesheet" href="server.css" />
  </head>

  <body onload='loadCategories()'>

  <p><a href="server.html"style="color:#ffcc00">Home</a>

| <a href="../login.html"style="color:#ffcc00">Logout</a></p>
    <h2>New Order</h2>
<strong>Sector:</strong>

    <form name="form" method="post" action="order.php" >
    <select id='categoriesSelect'>
    </select>

    <select  id='subcatsSelect' onchange="handleSelectChange(event)">
    </select>

    <input type="hidden" name="new" value="1" />
<input type="hidden" name="select" id="total" value="">

</div>
</div>

<div id="button">
<p><input name="submit" type="submit" value="Submit" onclick= </p>
</div>

    </form>
  </body>
</html>```
```

答:
well if i understood you want get a value from this first php page and pass to another php page.
so just do it in the first php
do

$_SESSION['mything'] = $value_that_want_pass;

on the second php page
do

session_start();

echo $_SESSION['mything'];

Body:
I am working on my semester project and I want to pass the variable "value" on the next page (order.php). It is a value retrieved from a dropdown box that is based on another dropdown box populated by database. I have confirmed that the value is stored but I can't retrieve it on the next page.

I tried localstorage (turns NULL), session variables(undefined index "value") and putting it in the url but nothing seems to work and is very frustrating. Can someone please help me with an example? Thank you

session_start();

$conn = new mysqli("localhost", "root", "", "restaurant_ordering");
mysqli_set_charset($conn,"utf8mb4");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "select * from sector ";
$result = $conn->query($sql);

  while($row = $result->fetch_assoc()){
    $categories[] = array("id" => $row['id'], "val" => $row['name']);
  }

  $sql = "SELECT * FROM booth";
  $result = $conn->query($sql);

  while($row = $result->fetch_assoc()){
    $subcats[$row['sector_id']][] = array("id" => $row['id'], "val" => $row['name']);
  }

  $jsonCats = json_encode($categories);
  $jsonSubCats = json_encode($subcats);

?>

<!doctype html>

<meta charset="utf-8">
<title>New Order</title>
<link rel="stylesheet" href="server.css" />

Home

| Logout

New Order

Sector:

    <form name="form" method="post" action="order.php" >
    <select id='categoriesSelect'>
    </select>

    <select  id='subcatsSelect' onchange="handleSelectChange(event)">
    </select>

    <input type="hidden" name="new" value="1" />
<input type="hidden" name="select" id="total" value="">

<input name="submit" type="submit" value="Submit" onclick=

    </form>

```


问:
Why does my C# debugger skip breakpoints?
My C# debugger is not working properly.  It skips break points and line of codes sometimes. I have checked the configuration manager.  I have even tried adding my projects to new solution files. Can someone please help me?</p>

答: Also make sure that the code you're trying to debug is running in the same process as the main executable. I just wasted a half hour figuring that one out - the breakpoint wasn't hitting because the code of interest had been spun up in a child process instead of being called directly (the program in question has two different modes of operation).</p>

OwnerDisplayName: Yasar

LastEditorDisplayName: Yasar

ContentLicense: CC BY-SA 2.5


问:
TypeError: Cannot handle this data type - Wrong mode for `PIL.Image.fromarray`?
I'm trying to use PIL.Image.fromarray:

```<code>import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]])
im = Image.fromarray(a, mode="RGB")
im.save("test.png")
plt.imshow(im)
plt.show()
</code>```

I expected to see 3 pixels red, green and blue.

However, if I omit mode keyword parameter as shown in the docs example, I get:

TypeError: Cannot handle this data type

And if I set mode="RGB", the saved image file test.png and the matplotlib window both look like this:

答:
Stack your three arrays and convert them to uint8 type based on this and this answer.

```<code>import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

a = (np.dstack(([255, 0, 0],[0, 255, 0],[0, 0, 255]))).astype(np.uint8)

im = Image.fromarray(a, mode="RGB")
im.save("test.png")
plt.imshow(im)
plt.show()
</code>```

Alternate option is to add extra dimension to your input array making it of shape (1, 3, 3)

```<code>a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]], dtype=np.uint8)
im = Image.fromarray(a, mode="RGB")
</code>```

Body:
I'm trying to use PIL.Image.fromarray:

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]])
im = Image.fromarray(a, mode="RGB")
im.save("test.png")
plt.imshow(im)
plt.show()

I expected to see 3 pixels red, green and blue.

However, if I omit mode keyword parameter as shown in the docs example, I get:

TypeError: Cannot handle this data type

And if I set mode="RGB", the saved image file test.png and the matplotlib window both look like this:

Body:
Stack your three arrays and convert them to uint8 type based on this and this answer.

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

a = (np.dstack(([255, 0, 0],[0, 255, 0],[0, 0, 255]))).astype(np.uint8)

im = Image.fromarray(a, mode="RGB")
im.save("test.png")
plt.imshow(im)
plt.show()

Alternate option is to add extra dimension to your input array making it of shape (1, 3, 3)

a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]], dtype=np.uint8)
im = Image.fromarray(a, mode="RGB")


问:
Multiply every third element of a list by two
Input data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Output data: [1, 2, 6, 4, 5, 12, 7, 8, 18, 10]

I have read many answers where were suggested to use slice notation with including first element. But in my case I should take each 3rd element of the list.

Is it possible to improve my realization?

for index in range(len(data)):
    if (index + 1) % 3 == 0:
        data[index] = data[index] * 2
```

答:
... and the winner is:

Calculation time in seconds and results validation test.
1.150 question_by_akrapovich
0.331 answer_by_Tom_Karzes_and_Prune
0.333 answer_2_by_Manuel_Montoya
0.373 answer_by_Blorgbeard
0.816 answer_1_by_Alain_T
2.850 answer_2_by_Alain_T
```

<p>Combined code for time testing and results validation:</p>

```import time

def question_by_akrapovich(data):
    for index in range(len(data)):
        if (index + 1) % 3 == 0:
            data[index] = data[index] * 2
    return data

def answer_by_Tom_Karzes_and_Prune(data):
    for index in range(2, len(data), 3):
        data[index] *= 2
    return data

def answer_by_Blorgbeard(data):
    data[2::3] = [x*2 for x in data[2::3]]
    return data

def answer_1_by_Alain_T(data):
    from itertools import cycle
    return [n * m for n, m in zip(data, cycle([1, 1, 2]))]

def answer_2_by_Alain_T(data):
    return [ n*max(1,i%3) for i,n in enumerate(data) ]

def answer_2_by_Manuel_Montoya(data):
    for index in range(2, len(data), 3):
        data[index] = data[index]*2
    return  data

def test(f):
    n = 10_000_000
    data = [i + 1 for i in range(n)]
    start_time = time.perf_counter()
    data = f(data)
    run_time = time.perf_counter() - start_time
    if n != len(data):
        print('error in list length', n, len(data))
        exit(1)
    for i in range(n):
        j = i + 1
        m = j * 2 if j % 3 == 0 else j
        if data[i] != m:
            print('error in data', i, m, data[i])
            exit(1)
    print('%.3f %s' % (run_time, f.__name__))

print('Calculation time in seconds and results validation test.')
for f in [question_by_akrapovich, answer_by_Tom_Karzes_and_Prune,
          answer_2_by_Manuel_Montoya, answer_by_Blorgbeard,
          answer_1_by_Alain_T, answer_2_by_Alain_T]:
    test(f)
```

Body:
... and the winner is:

Calculation time in seconds and results validation test.
1.150 question_by_akrapovich
0.331 answer_by_Tom_Karzes_and_Prune
0.333 answer_2_by_Manuel_Montoya
0.373 answer_by_Blorgbeard
0.816 answer_1_by_Alain_T
2.850 answer_2_by_Alain_T

Combined code for time testing and results validation:

import time

def question_by_akrapovich(data):
    for index in range(len(data)):
        if (index + 1) % 3 == 0:
            data[index] = data[index] * 2
    return data

def answer_by_Tom_Karzes_and_Prune(data):
    for index in range(2, len(data), 3):
        data[index] *= 2
    return data

def answer_by_Blorgbeard(data):
    data[2::3] = [x*2 for x in data[2::3]]
    return data

def answer_1_by_Alain_T(data):
    from itertools import cycle
    return [n * m for n, m in zip(data, cycle([1, 1, 2]))]

def answer_2_by_Alain_T(data):
    return [ n*max(1,i%3) for i,n in enumerate(data) ]

def answer_2_by_Manuel_Montoya(data):
    for index in range(2, len(data), 3):
        data[index] = data[index]*2
    return  data

def test(f):
    n = 10_000_000
    data = [i + 1 for i in range(n)]
    start_time = time.perf_counter()
    data = f(data)
    run_time = time.perf_counter() - start_time
    if n != len(data):
        print('error in list length', n, len(data))
        exit(1)
    for i in range(n):
        j = i + 1
        m = j * 2 if j % 3 == 0 else j
        if data[i] != m:
            print('error in data', i, m, data[i])
            exit(1)
    print('%.3f %s' % (run_time, f.__name__))

print('Calculation time in seconds and results validation test.')
for f in [question_by_akrapovich, answer_by_Tom_Karzes_and_Prune,
          answer_2_by_Manuel_Montoya, answer_by_Blorgbeard,
          answer_1_by_Alain_T, answer_2_by_Alain_T]:
    test(f)


答: The form values in the submitted form will be available in the $_POST variable in 'order.php'. Find the values by using the HTML 'name' attribute of the form input you want the value for. So if you want the value of the hidden "new" form element, get the value in 'order.php' by using $_POST['new'].

Title: passing javascript value between php pages


问:
Keycloak Applications vs Client authentication
Hi i am a bit confused as to how to secure applications through keycloak, the website shows how to secure clients. The application which i need to secure in my setup is a desktop application which uses keycloak + keycloak-gatekeeper protected endpoints.

i managed to get it working using the following library in python

https://bitbucket.org/agriness/python-keycloak/src/master/

however, it requires me to enter the client-secret and i am wondering if this is safe?

also, when i use the browser login instead, the browser doesnt need the client secret, but goes though gatekeeper, this tells me that i am doing something wrong here.

thanks

答:
in your case, I would use Access type as confidential
and Authorization Enabled > on

and you should use the secrecy key to authorize your call to keylock when you want to interact with keycloak API

```<code>Keycloak keycloak = KeycloakBuilder.builder()
                .serverUrl("localhost")
                .realm("myRealm")
                .grantType(OAuth2Constants.PASSWORD)
                .clientId("myclient")
                .clientSecret("xxxx-xxxxx-xxxx-xxx")
                .username("foo")//the admin user
                .password("password")
                .build();
keycloak.realm("myRealm").users().list();
</code>```

Body:
in your case, I would use Access type as confidential
and Authorization Enabled > on

and you should use the secrecy key to authorize your call to keylock when you want to interact with keycloak API

Keycloak keycloak = KeycloakBuilder.builder()
                .serverUrl("localhost")
                .realm("myRealm")
                .grantType(OAuth2Constants.PASSWORD)
                .clientId("myclient")
                .clientSecret("xxxx-xxxxx-xxxx-xxx")
                .username("foo")//the admin user
                .password("password")
                .build();
keycloak.realm("myRealm").users().list();


问:
How does Laravel's ORM specify the sorted values for the data?
E.g:
There is a field in the table called name,
Name contains some user names, for example:

```<code>| name |
---------
| Asal |
| Codaya |
| Ostily |
| Queen |
| Qta |
| Zoo |

</code>```

What do you want to achieve, for example, I am passing a value now, for example, passing Q, then the returned data, that is, all the first letters Q are in front, like this:

```<code>| name |
-------------
| Queen |
| Qta |
| Asal |
| Codaya |
| Ostily |
| Zoo |

</code>```

If you pass in a Z, it becomes like this:

```<code>| name |
------------
| Zoo |
| Asal |
| Codaya |
| Ostily |
| Queen |
| Qta |

</code>```

How is this requirement implemented in mysql?

答:
I think your best option would be this in SQL:

```<code>SELECT
    name
FROM
    user
ORDER BY
CASE
    WHEN name LIKE 'E%' THEN 1
    ELSE 2
END
</code>```

If you are using Doctrine as ORM, I believe CASE is not supported natively in ORDER BY (in DQL), so you would have to go with raw SQL, I guess.

Body:
E.g:
There is a field in the table called name,
Name contains some user names, for example:

| name |
---------
| Asal |
| Codaya |
| Ostily |
| Queen |
| Qta |
| Zoo |

What do you want to achieve, for example, I am passing a value now, for example, passing Q, then the returned data, that is, all the first letters Q are in front, like this:

| name |
-------------
| Queen |
| Qta |
| Asal |
| Codaya |
| Ostily |
| Zoo |

If you pass in a Z, it becomes like this:

| name |
------------
| Zoo |
| Asal |
| Codaya |
| Ostily |
| Queen |
| Qta |

How is this requirement implemented in mysql?

Body:
I think your best option would be this in SQL:

SELECT
    name
FROM
    user
ORDER BY
CASE
    WHEN name LIKE 'E%' THEN 1
    ELSE 2
END

If you are using Doctrine as ORM, I believe CASE is not supported natively in ORDER BY (in DQL), so you would have to go with raw SQL, I guess.


问:
my viewcontroller does not fall in the viewdidLoad method
I have a question, I am learning about programming in swift, I have learned to handle tables and collections without problems, including the cosumo of services with alamofire, but I face a problem, I have a collection within a personalized table view cell, the managed to do the event click inside the collection and I communicate it to the ViewController with a protocol passing information that I need, but when I load the following ViewController (TabsDetailProductViewController) it does not fall into the method on viewDidLoad if it does not jump to the ContentView that has added which is connected with the DetailProductContentViewController. That is, as I understood when using the method.

```<code>func ItemClick(position: Int, model: Product) {
        let Storyboard = UIStoryboard(name: "Main", bundle: nil)
        let tabsViewController = Storyboard.instantiateViewController(withIdentifier: "TabsDetailProductViewController") as! TabsDetailProductViewController
        tabsViewController.productModel = model
        self.navigationController?.pushViewController(tabsViewController, animated: true)
    }
</code>```

I had to fall into the viewLoaded of the TabsDetailProductViewController but instead it jumps to the viewLoaded of the DetailProductContentViewController and then returns to the viewload of the TabsDetailProductViewController. I need to know what I'm doing wrong or maybe this is the life cycle.

This is my storyboard.

答:
Short answer

I need to know what I'm doing wrong?

Nothing

or maybe this is the life cycle.

Yes

Explanation

According to Apple official documentation of viewdidload

This method is called after the view controller has loaded its view hierarchy into memory.

In your case in order to completely load the view hierarchy of the TabsDetailProductViewController the DetailProductContentViewController has to be loaded first, as it is in the view hierarchy of TabsDetailProductViewController as a result of containment

Hence the viewdidload of DetailProductContentViewController will be called before  TabsDetailProductViewController's viewdidload

Body:
I have a question, I am learning about programming in swift, I have learned to handle tables and collections without problems, including the cosumo of services with alamofire, but I face a problem, I have a collection within a personalized table view cell, the managed to do the event click inside the collection and I communicate it to the ViewController with a protocol passing information that I need, but when I load the following ViewController (TabsDetailProductViewController) it does not fall into the method on viewDidLoad if it does not jump to the ContentView that has added which is connected with the DetailProductContentViewController. That is, as I understood when using the method.

func ItemClick(position: Int, model: Product) {
        let Storyboard = UIStoryboard(name: "Main", bundle: nil)
        let tabsViewController = Storyboard.instantiateViewController(withIdentifier: "TabsDetailProductViewController") as! TabsDetailProductViewController
        tabsViewController.productModel = model
        self.navigationController?.pushViewController(tabsViewController, animated: true)
    }

I had to fall into the viewLoaded of the TabsDetailProductViewController but instead it jumps to the viewLoaded of the DetailProductContentViewController and then returns to the viewload of the TabsDetailProductViewController. I need to know what I'm doing wrong or maybe this is the life cycle.

This is my storyboard.


问:
Returning the index of an empty element inside an array
So I have an array let's say :

```<code>var arr = ['apples' , 'cherries' , 'strawberries']
</code>```

and after so much coding, I get hungry so I eat the 'cherries'
so now I have

```<code>arr = ['apples',null,'strawberries']
</code>```

So I was wondering if there is some sort of JavaScript function that can return the first null element inside an array ?

Let's say for instance my grandma gives me 'potatoes' and I want to add them inside the null space I have like a good boy I am, and I need the index of that null element so I may know where to place my sweet goods from grandma.

答:
try removing the element using below code :

```<code>var arr = ['apples' , 'cherries' , 'strawberries'];

arr.splice(1,1);
</code>```

and remove and add try :

```<code>var arr = ['apples' , 'cherries' , 'strawberries'];

arr.splice(1,1, 'potatoes');
</code>```

Body:
So I have an array let's say :

var arr = ['apples' , 'cherries' , 'strawberries']

and after so much coding, I get hungry so I eat the 'cherries'
so now I have

arr = ['apples',null,'strawberries']

So I was wondering if there is some sort of JavaScript function that can return the first null element inside an array ?

Let's say for instance my grandma gives me 'potatoes' and I want to add them inside the null space I have like a good boy I am, and I need the index of that null element so I may know where to place my sweet goods from grandma.

Body:
try removing the element using below code :

var arr = ['apples' , 'cherries' , 'strawberries'];

arr.splice(1,1);

and remove and add try :

var arr = ['apples' , 'cherries' , 'strawberries'];

arr.splice(1,1, 'potatoes');


问:
Using linq to get nth word from each line in a list in C#
Hi I have a list of multi word strings.

```<code>List<string> myList = new List<string>();
myList.Add("Robert is a bank manager");
myList.Add("Alice is a cashier");
myList.Add("Andrew is bank customer");
</code>```

Now for each string line in myList, I wanted to get nth word. So let's say I want to retrieve even number positioned word from each string, I want to get output as:

```<code>var[] output = {"is", "bank", "is", "cashier", "is", "customer"};
</code>```

I can simply use a for loop and store every nth word in the output array, but curious how to do the same using linq.

答:
I am curious how to do the same using LINQ

Give someone a fish and you feed them for a day; teach them to catch fish, blah blah blah.

What you need is a thought process for LINQ-ifying code. Here's the process I use.

The first thing I do is look at the description of the problem and think "where are the operations that are done to every element of a sequence?"

for each string line in myList, I wanted to get nth word.

Ooh, there's one.

The next question is: Suppose I wanted to do that to an individual element of the sequence; how would I do that?  Can I write a method that does that?

This problem seems to break down nicely into two sub-problems:

1) Given a string, get back a sequence of words.
2) Given a sequence of things, produce a sequence of every nth thing.

We know how to do the first one: that's Split().

What's the second one? Once again we have an operation where we are doing something to every element of a sequence. This time we're filtering, so it seems likely that we'd want to use a Where.

As others have noted, you can use the Where that takes an index for this. Let's write a helper method:

```<code>public static IEnumerable<T> TakeEveryNth(
    this IEnumerable<T> items,
    int n,
    int offset = 0) =>
  items.Where((item, i) => (i - offset) % n == 0);
</code>```

(Notice something about this solution: there's nothing in there that is specific to sequences of strings, so I made it generic. Now we have a useful tool for more than just words.)

Super. Let's put the last two together:

```<code>public static IEnumerable<string> EveryNthWord(
    this string sentence,
    int n,
    int offset = 0) =>
  sentence.Split(" ").TakeEveryNth(n, offset);
</code>```

OK, we want to do this to every element in a list, and then concatenate the results all together. That's SelectMany. So the solution to your problem is:

```<code>public static IEnumerable<string> EveryNthWord(
    this IEnumerable<string> sentences,
    int n,
    int offset = 0) =>
sentences.SelectMany(sentence => sentence.EveryNthWord(n, offset));
</code>```

And now we have a solution to your problem:

```<code>var result = sentences.EveryNthWord(2, 1).ToList();
</code>```

And we're done.

That's how you reason through the problem when you're trying to come up with a LINQ solution: break everything up into tiny pieces and write a method for each piece that solves one problem well.  Then combine them together with query operators.

What if we wanted to then make this all into one expression? It is much easier to do that if you already have it broken up.  Just combine them together:

```<code>var n = 2;
var offset = 1;
var result = sentences
  .SelectMany(sentence => sentence
    .Split(" ")
    .Where((item, i) => (i - offset) % n == 0))
  .ToList();
</code>```

But frankly the code is more useful and readable if you keep it split up. Each helper method is useful in its own right, so keep them!

Body:
Hi I have a list of multi word strings.

List<string> myList = new List<string>();
myList.Add("Robert is a bank manager");
myList.Add("Alice is a cashier");
myList.Add("Andrew is bank customer");

Now for each string line in myList, I wanted to get nth word. So let's say I want to retrieve even number positioned word from each string, I want to get output as:

var[] output = {"is", "bank", "is", "cashier", "is", "customer"};

I can simply use a for loop and store every nth word in the output array, but curious how to do the same using linq.

Body:
I am curious how to do the same using LINQ

Give someone a fish and you feed them for a day; teach them to catch fish, blah blah blah.

What you need is a thought process for LINQ-ifying code. Here's the process I use.

The first thing I do is look at the description of the problem and think "where are the operations that are done to every element of a sequence?"

for each string line in myList, I wanted to get nth word.

Ooh, there's one.

The next question is: Suppose I wanted to do that to an individual element of the sequence; how would I do that?  Can I write a method that does that?

This problem seems to break down nicely into two sub-problems:

1) Given a string, get back a sequence of words.
2) Given a sequence of things, produce a sequence of every nth thing.

We know how to do the first one: that's Split().

What's the second one? Once again we have an operation where we are doing something to every element of a sequence. This time we're filtering, so it seems likely that we'd want to use a Where.

As others have noted, you can use the Where that takes an index for this. Let's write a helper method:

public static IEnumerable<T> TakeEveryNth(
    this IEnumerable<T> items,
    int n,
    int offset = 0) =>
  items.Where((item, i) => (i - offset) % n == 0);

(Notice something about this solution: there's nothing in there that is specific to sequences of strings, so I made it generic. Now we have a useful tool for more than just words.)

Super. Let's put the last two together:

public static IEnumerable<string> EveryNthWord(
    this string sentence,
    int n,
    int offset = 0) =>
  sentence.Split(" ").TakeEveryNth(n, offset);

OK, we want to do this to every element in a list, and then concatenate the results all together. That's SelectMany. So the solution to your problem is:

public static IEnumerable<string> EveryNthWord(
    this IEnumerable<string> sentences,
    int n,
    int offset = 0) =>
sentences.SelectMany(sentence => sentence.EveryNthWord(n, offset));

And now we have a solution to your problem:

var result = sentences.EveryNthWord(2, 1).ToList();

And we're done.

That's how you reason through the problem when you're trying to come up with a LINQ solution: break everything up into tiny pieces and write a method for each piece that solves one problem well.  Then combine them together with query operators.

What if we wanted to then make this all into one expression? It is much easier to do that if you already have it broken up.  Just combine them together:

var n = 2;
var offset = 1;
var result = sentences
  .SelectMany(sentence => sentence
    .Split(" ")
    .Where((item, i) => (i - offset) % n == 0))
  .ToList();

But frankly the code is more useful and readable if you keep it split up. Each helper method is useful in its own right, so keep them!


问:
Why am I unable to access props from vue root inside components template?
I am trying to access job_execs from the stage-execs component in the template...

job_execs is created in the vue root and I am trying to access it by calling it in the props of the stage-execs component.

```<code><div id="vue-job">
<div class="column">
    <div class="row">
        <h3>test</h3>
        <stage-execs></stage-execs>
    <br><br>
</div>
</div>

<script>
    Vue.component('stage-execs', {
        delimiters: [ '[[', ']]' ],
        props: ['job_execs'],
        data: function() {
                return {
                    job_execs: job_execs
                }
            },
        template: `
        <ul id="example-1">
          <li v-for="item in job_execs">
            [[ item.build_id ]]
          </li>
        </ul>
        `,
    });

    var v_root = new Vue({
        delimiters: [ '[[', ']]' ],
        el: '#vue-job',
        data: {
            job_execs: []
        },
        created() {
            url="http://{{ api_endpoint }}"
            fetch(url)
                .then(response => response.json())
                .then(body => {
                    for(i=0; i<body.length; i++){
                        this.job_execs.push({
                            'build_id': JSON.stringify(body[i].build_id),
                            'status': JSON.stringify(body[i].status.name),
                        })
                    }
            })
            .catch( err => {
                console.log('Error Fetching:', url, err);
                return { 'failure': url, 'reason': err };
            });

        },
    });
</code>```

What is the correct way here to access job_execs in the stage-execs component?

答:
In VueJS, you always pass data from the parent (root in your case) to the component (stage-execs component) with props.

So to answer your question

What is the correct way here to access job_execs in the stage-execs
  component?

The answer is: With a prop. Define a prop on your component and pass down a value from the parent.

In your component you defined the props job_execs, but you didn't pass anything down.

```<code><stage-execs></stage-execs>
</code>```

It is missing it's prop. So your html should be:

```<code><div id="vue-job">
<div class="column">
    <div class="row">
        <h3>test</h3>
        <stage-execs :job_execs="job_execs"></stage-execs>
    <br><br>
</div>
</div>
</code>```

Notice the difference in the component.

I bind the job_execs props on your component to the data property job_execs in your root. Please note that the : job_execs= is the equavalent of v-bind:job_execs= and is a reference to your props on your component. The value passed down is the data property from your root. Sorry if I am be overstaitng things, I'm just trying to avoid confusion since the prop on the component and the data property in root have the same name.

In your component there's no need to make a data property named job_execs and in fact you should never name your data properties and props the same name. See: https://forum.vuejs.org/t/questions-regarding-handling-immutable-props-and-mutable-data-props/967/2?u=tarasovych

So now our code looks like

```<code>Vue.component('stage-execs', {
    delimiters: [ '[[', ']]' ],
    props: ['job_execs'],
    template: `
    <ul id="example-1">
      <li v-for="item in job_execs">
        [[ item.build_id ]]
      </li>
    </ul>
    `,
});
</code>```

Since I passed a value to the props. I can now iterate through it.

I've made a working example on codepen: https://codepen.io/bergur/pen/eaPdyv

In that example I've just manually entered some dummy value for the array.

Body:
I am trying to access job_execs from the stage-execs component in the template...

job_execs is created in the vue root and I am trying to access it by calling it in the props of the stage-execs component.

test

        <stage-execs></stage-execs>

Body:
In VueJS, you always pass data from the parent (root in your case) to the component (stage-execs component) with props.

So to answer your question

What is the correct way here to access job_execs in the stage-execs
  component?

The answer is: With a prop. Define a prop on your component and pass down a value from the parent.

In your component you defined the props job_execs, but you didn't pass anything down.

<stage-execs></stage-execs>

It is missing it's prop. So your html should be:

<div id="vue-job">
<div class="column">
    <div class="row">
        <h3>test</h3>
        <stage-execs :job_execs="job_execs"></stage-execs>
    <br><br>
</div>
</div>

Notice the difference in the component.

I bind the job_execs props on your component to the data property job_execs in your root. Please note that the : job_execs= is the equavalent of v-bind:job_execs= and is a reference to your props on your component. The value passed down is the data property from your root. Sorry if I am be overstaitng things, I'm just trying to avoid confusion since the prop on the component and the data property in root have the same name.

In your component there's no need to make a data property named job_execs and in fact you should never name your data properties and props the same name. See: https://forum.vuejs.org/t/questions-regarding-handling-immutable-props-and-mutable-data-props/967/2?u=tarasovych

So now our code looks like

Vue.component('stage-execs', {
    delimiters: [ '[[', ']]' ],
    props: ['job_execs'],
    template: `
    <ul id="example-1">
      <li v-for="item in job_execs">
        [[ item.build_id ]]
      </li>
    </ul>
    `,
});

Since I passed a value to the props. I can now iterate through it.

I've made a working example on codepen: https://codepen.io/bergur/pen/eaPdyv

In that example I've just manually entered some dummy value for the array.


答:
I don't see why you would use python for this if you can do it in a single line of code in the shell.

```<code>svn status | grep "^[AMD]" | sed 's/^.\{8\}//' | xargs zcvf My.tar.gz
</code>```

I used grep to only select lines that are modified, if you want all files that svn status lists (also those that are added / deleted) you can leave that part out. I've used sed here to delete the first part of every line, I'm sure there is an easier way to do that but I can't think of one right now.

Title: write python script to run the shell script?

Body:
I run the svn status got the modified files :

  svn status
  ?       .settings
  ?       .buildpath
  ?       .directory
  A       A.php
  M       B.php
  D       html/C.html
  M       html/D.fr
  M       api/E.api
  M       F.php
  ..

After I want to keep all of these files

zcvf MY.tar.gz all files that svn stat display
(not include ? just M,A,D)

My idea is to create the python script can run the shell,because right now to do this I just copy the file name one by one.

zcvf MY.tar.gz all the files that we run svn stat

Anybody could guide how to do this or some related tutorial? But if you think it difficult than copy && paste I will ignore my trying?

thanks

Body:
I don't see why you would use python for this if you can do it in a single line of code in the shell.

svn status | grep "^[AMD]" | sed 's/^.\{8\}//' | xargs zcvf My.tar.gz

I used grep to only select lines that are modified, if you want all files that svn status lists (also those that are added / deleted) you can leave that part out. I've used sed here to delete the first part of every line, I'm sure there is an easier way to do that but I can't think of one right now.


问:
Three js - Have object move towards camera
I have an object that I want to move directly towards the camera when given the proper input.

I've taken a look at Object3d.translateOnAxis(axis, distance), but I can't seem to set the axis (the object's local axis) to always face the camera. This may be because the object is also rotating.

Since I have multiple objects on the scene, I need the objects to move towards the camera.

答:
For me what's working to move the object 5 meters is:</p>

```<code>var dir = new THREE.Vector3();
dir.subVectors(camera.position, object.getWorldPosition(dir)).normalize();
object.translateOnAxis(dir, 5);
</code>```

Body:
For me what's working to move the object 5 meters is:

var dir = new THREE.Vector3();
dir.subVectors(camera.position, object.getWorldPosition(dir)).normalize();
object.translateOnAxis(dir, 5);


答:
From W3C documentation :

```<code>arr.findIndex(element => element === null);
</code>```

Replace :

```<code>arr[arr.findIndex(element => element === null)] = "potatoes";
</code>```

Title: Returning the index of an empty element inside an array

Body:
From W3C documentation :

arr.findIndex(element => element === null);

Replace :

arr[arr.findIndex(element => element === null)] = "potatoes";