问:
CSS -> Hover effect dosen't work
My CSS Code don't detect, if my cursor over the div: But if i active "hover" with the browser developer tool, it works.

Explain: The Div shows, if I go over a button, but the div hide out, if i go out of the button...

My code:

.profilanzeige2 {
  width: 20%;
  float: right;
  position: absolute;
  text-align: center;
  padding: 10px;
  top: -250px;
  right: 0px;
  z-index: -1;
  border-radius: 0px 0px 10px 10px;
  color: white;
  /* border: 1px solid #797979; */
  background-image: none;
  background: #16b751;
  background: -moz-linear-gradient(top, #16b751 0%, #19ad46 100%);
  background: -webkit-linear-gradient(top, #16b751 0%,#19ad4619ad46 100%);
  background: linear-gradient(to bottom, #16b751 0%,#19ad46 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#16b751', endColorstr='#19ad46',GradientType=0 );
  transition: top 1s ease-in-out;
  border: 1px solid #e7e7e7;
}

#profilanzeige:hover ~ #profilanzeige2, .profilanzeige2:hover {
    top: 54px !important;
}

#profilanzeige:hover + #profilanzeige2, .profilanzeige2:hover {
    top: 54px !important;
}

.profil:hover ~ #profilanzeige2, #profilanzeige2:hover {
    top: 54px !important;
}

.profil:hover + #profilanzeige2, #profilanzeige2:hover {
    top: 54px !important;
}
```

<pre class="lang-html prettyprint-override"><code><div class="profilanzeige2" id="profilanzeige2">
        <img src="https://ftimg.de/images/2017/03/02/5e2c4f6af5024d26bb95d074a3ed9a86.png">

        <p class="profil-name"><?php echo $user['icname']; ?></p>

        <button type="button" class="btn btn-default" class="Profilanzeigen">
          Profil anzeigen
        </button>

        <button type="button" class="btn btn-default" class="Abmelden" href="logout.php">
          Abmelden
        </button>
      </div>
</code>```

答:
You have

```<code><div class="profilanzeige2" id="profilanzeige2">
</code>```

with class profilanzeige2 but the :hover is on #profilanzeige

Another thing which could be improved, for the sake of readability, is to have different names of the class and the id in the div.

Title: CSS -> Hover effect dosen't work

Body:
My CSS Code don't detect, if my cursor over the div: But if i active "hover" with the browser developer tool, it works.

Explain: The Div shows, if I go over a button, but the div hide out, if i go out of the button...

My code:

.profilanzeige2 {
  width: 20%;
  float: right;
  position: absolute;
  text-align: center;
  padding: 10px;
  top: -250px;
  right: 0px;
  z-index: -1;
  border-radius: 0px 0px 10px 10px;
  color: white;
  /* border: 1px solid #797979; */
  background-image: none;
  background: #16b751;
  background: -moz-linear-gradient(top, #16b751 0%, #19ad46 100%);
  background: -webkit-linear-gradient(top, #16b751 0%,#19ad4619ad46 100%);
  background: linear-gradient(to bottom, #16b751 0%,#19ad46 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#16b751', endColorstr='#19ad46',GradientType=0 );
  transition: top 1s ease-in-out;
  border: 1px solid #e7e7e7;
}

#profilanzeige:hover ~ #profilanzeige2, .profilanzeige2:hover {
    top: 54px !important;
}

#profilanzeige:hover + #profilanzeige2, .profilanzeige2:hover {
    top: 54px !important;
}

.profil:hover ~ #profilanzeige2, #profilanzeige2:hover {
    top: 54px !important;
}

.profil:hover + #profilanzeige2, #profilanzeige2:hover {
    top: 54px !important;
}

<?php echo $user['icname']; ?>

        <button type="button" class="btn btn-default" class="Profilanzeigen">
          Profil anzeigen
        </button>

        <button type="button" class="btn btn-default" class="Abmelden" href="logout.php">
          Abmelden
        </button>

Body:
You have

<div class="profilanzeige2" id="profilanzeige2">

with class profilanzeige2 but the :hover is on #profilanzeige

Another thing which could be improved, for the sake of readability, is to have different names of the class and the id in the div.


来源: stackexchange

问:
Get internal byte array from ByteArrayInputStream
I want to get the internal byte array from ByteArrayInputStream. I don't want to extends that class or write it into another byte array. Is there a utility class that help me do that?

Thanks,

答:
Extend ByteArrayInputStream, then you have access to the protected fields. It's the way to do it. Constructors are provided to take the byte array from an argument.

However, you may find the decorator pattern more helpful.

ContentLicense: CC BY-SA 2.5


问:
Using 'goto' to move from if to else
I know that there's no goto in java, but I ask on general if there are a method to goto from if to else
example :

```<code>public void decToAsci(String decimal) {
    String nb = "";
    int number;
    for (int i = 0; i < decimal.length(); i++) {
        Character c = decimal.charAt(i);
        if (!c.equals(' ')) {
            nb += decimal.charAt(i);
            if (i == decimal.length() - 1)
                //here i want to jump to else
                // i can do it like this :
                // System.out.print( (char) Integer.parseInt(nb) + " ");
                // but i repeat code in else here ..i just want to jump to else
        } else {
            number = Integer.parseInt(nb);
            System.out.print((char) number + " ");
            nb = "";
            number = 0;
        }
    }
}
</code>```

I try this :

```<code>if (!c.equals(' ')) {
    nb += decimal.charAt(i);
    if (i == decimal.length() - 1) continue label;
} else {
    label: the code in else
}
</code>```

But not worked, not worked with break label also. I understand that continue, break. Are used between son and parent like that? :

```<code>label:
for(int i=0 ; i<n ; i++)
    if (cond) break label;
</code>```

I ask about a method that can jump from if to else (2 sons)

(not a son and a parent but jumping between 2 sons )

I think even with goto on c and c++ 4 example we can't do it

答:
Anything that uses "goto like" behavior is a bad idea.  It is widely accepted that goto-like control structures lead to code that is a lot more difficult to read / maintain than if you stick to "structured programming" control structures.

Here are (IMO) two "right approaches" to solving the problem:

Approach #1 - rearrange the logic

```<code>public void decToAsci(String decimal) {
    String nb = "";
    for (int i = 0; i < decimal.length(); i++) {
        Character c = decimal.charAt(i);
        if (!c.equals(' ')) {
            nb += decimal.charAt(i);
        }
        if (c.equals(' ') || i == decimal.length() - 1) {
            int number = Integer.parseInt(nb);
            System.out.print((char) number + " ");
            nb = "";
        }
    }
}
</code>```

(If the c.equals(' ') was expensive you could use a temporary variable to avoid recomputing it.  In this case, it is cheap, and will probably be inlined and further optimized by the JIT compiler.)

Approach #2 - refactor code into a methid

```<code>public void decToAsci(String decimal) {
    String nb = "";
    for (int i = 0; i < decimal.length(); i++) {
        Character c = decimal.charAt(i);
        if (!c.equals(' ')) {
            nb += decimal.charAt(i);
            if (i == decimal.length() - 1)
                nb = processAsInt(nb);
        } else {
            nb = processAsInt(nb);
        }
    }
}

public String processInt(String nb) {
    int number = Integer.parseInt(nb);
    System.out.print((char) number + " ");
    return "";
}
</code>```

In this context, the first approach gives a better code.  (IMO)

ContentLicense: CC BY-SA 3.0

Title: Using 'goto' to move from if to else

Body:
I know that there's no goto in java, but I ask on general if there are a method to goto from if to else
example :

public void decToAsci(String decimal) {
    String nb = "";
    int number;
    for (int i = 0; i < decimal.length(); i++) {
        Character c = decimal.charAt(i);
        if (!c.equals(' ')) {
            nb += decimal.charAt(i);
            if (i == decimal.length() - 1)
                //here i want to jump to else
                // i can do it like this :
                // System.out.print( (char) Integer.parseInt(nb) + " ");
                // but i repeat code in else here ..i just want to jump to else
        } else {
            number = Integer.parseInt(nb);
            System.out.print((char) number + " ");
            nb = "";
            number = 0;
        }
    }
}

I try this :

if (!c.equals(' ')) {
    nb += decimal.charAt(i);
    if (i == decimal.length() - 1) continue label;
} else {
    label: the code in else
}

But not worked, not worked with break label also. I understand that continue, break. Are used between son and parent like that? :

label:
for(int i=0 ; i<n ; i++)
    if (cond) break label;

I ask about a method that can jump from if to else (2 sons)

(not a son and a parent but jumping between 2 sons )

I think even with goto on c and c++ 4 example we can't do it

Body:
Anything that uses "goto like" behavior is a bad idea.  It is widely accepted that goto-like control structures lead to code that is a lot more difficult to read / maintain than if you stick to "structured programming" control structures.

Here are (IMO) two "right approaches" to solving the problem:

Approach #1 - rearrange the logic

public void decToAsci(String decimal) {
    String nb = "";
    for (int i = 0; i < decimal.length(); i++) {
        Character c = decimal.charAt(i);
        if (!c.equals(' ')) {
            nb += decimal.charAt(i);
        }
        if (c.equals(' ') || i == decimal.length() - 1) {
            int number = Integer.parseInt(nb);
            System.out.print((char) number + " ");
            nb = "";
        }
    }
}

(If the c.equals(' ') was expensive you could use a temporary variable to avoid recomputing it.  In this case, it is cheap, and will probably be inlined and further optimized by the JIT compiler.)

Approach #2 - refactor code into a methid

public void decToAsci(String decimal) {
    String nb = "";
    for (int i = 0; i < decimal.length(); i++) {
        Character c = decimal.charAt(i);
        if (!c.equals(' ')) {
            nb += decimal.charAt(i);
            if (i == decimal.length() - 1)
                nb = processAsInt(nb);
        } else {
            nb = processAsInt(nb);
        }
    }
}

public String processInt(String nb) {
    int number = Integer.parseInt(nb);
    System.out.print((char) number + " ");
    return "";
}

In this context, the first approach gives a better code.  (IMO)


问:
Creating multiple directories in 3 directories Ubuntu
I have created 3 folders named Paul, James & Kurt.

In each folder that I've created I must also have 3 folders named (Documents, Pictures, Music).

And also

Each named folder should have a README file containing the following contents:
        "These folders are used to store employee details."

Can some kindly guide me through this

答:
The below will create new directories for all lines in users.txt and a sub-directory in each for Documents with a README in it with the above contents. Hope it helps.

```<code>Sub=Documents
for names in $(cat "users.txt"); do
    mkdir -p "$names"/{"$Sub",} && touch "$names"/"$Sub"/README.txt &&
echo "These folders are used to store employee details." > "$names"/"$Sub"/README.txt
done
</code>```

Body:
The below will create new directories for all lines in users.txt and a sub-directory in each for Documents with a README in it with the above contents. Hope it helps.

Sub=Documents
for names in $(cat "users.txt"); do
    mkdir -p "$names"/{"$Sub",} && touch "$names"/"$Sub"/README.txt &&
echo "These folders are used to store employee details." > "$names"/"$Sub"/README.txt
done


问:
NeuroEvolution of Augmenting Topologies (NEAT) and global innovation number
I was not able to find why we should have a global innovation number for every new connection gene in NEAT.

From my little knowledge of NEAT, every innovation number corresponds directly with an node_in, node_out pair, so, why not only use this pair of ids instead of the innovation number? Which new information there is in this innovation number? chronology?

Update

Is it an algorithm optimization?

答:
Note: this more of an extended comment than an answer.

You encountered a problem I also just encountered whilst developing a NEAT version for javascript. The original paper published in ~2002 is very unclear.

The original paper contains the following:

Whenever a new
  gene appears (through structural mutation), a global innovation number is incremented
  and assigned to that gene. The innovation numbers thus represent a chronology of the
  appearance of every gene in the system. [..] ; innovation numbers are never changed. Thus, the historical origin of every
  gene in the system is known throughout evolution.

But the paper is very unclear about the following case, say we have two ; 'identical' (same structure) networks:

The networks above were initial networks; the networks have the same innovation ID, namely [0, 1]. So now the networks randomly mutate an extra connection.

Boom! By chance, they mutated to the same new structure. However, the connection ID's are completely different, namely [0, 2, 3] for parent1 and [0, 4, 5] for parent2 as the ID is globally counted.

But the NEAT algorithm fails to determine that these structures are the same. When one of the parents scores higher than the other, it's not a problem. But when the parents have the same fitness, we have a problem.

Because the paper states:

In composing the offspring, genes are randomly chosen from veither parent at matching genes, whereas all excess or disjoint genes are always included from the more fit parent, or if they are equally fit, from both parents.

So if the parents are equally fit, the offspring will have connections [0, 2, 3, 4, 5]. Which means that some nodes have double connections... Removing global innovation counters, and just assign id's by looking at node_in and node_out, you avoid this problem.

So when you have equally fit parents, yes you have optimized the algorithm. But this is almost never the case.

Quite interesting: in the newer version of the paper, they actually removed that bolded line! Older version here.

By the way, you can solve this problem by instead of assigning innovation ID's, assign ID based on node_in and node_out using pairing functions. This creates quite interesting neural networks when fitness is equal:


问:
Crontab won't execute my script which executes manually
I have a bash script that needs to be executed everyday at 9:30pm. its called fetchIND.sh and I've made the entry for that in my tab with specifying the shell and path parameters as follows. It is supposed to fetch files off another server with sftp and works just fine manually. However, with crontab is doesn't execute.

My crontab entry :

06 21 * * * root /usr/bin/bash /root/IND/fetchIND.sh

results after 'ps aux | grep bash' command:

root      5815  0.0  0.0   8984   808 pts/0    S+   21:06   0:00 grep --color=auto bash

However, my script doesn't actually execute. Any help regarding this would be great. Thanks!!

答:
The cron might be trying to run this in cron shell which might not have permission for running the command in root shell.

Adding sudo might do the work. Refer to this for more https://superuser.com/a/1046126


问:
Counting the position of a character after two or more spaces
I am trying to return a value equal to the position of the first letter coming after two or more spaces.

I have a tool that extract tables with variable column length into TXT docs. I need to get these tables into an Excel sheet without having to put fixed width to each column in each table (that is a lot of coding to be done). I am trying to find something more dynamic to do so based on the position of the first character after two or more spaces.

Bearing in mind that not all rows are fully populated but the first row would make a perfect candidate to get the width of the column.

To give an example, the lines of the text would look like this

John       Robert       Eric       Tom

10          11            143        43

21                       265        56

99          241                     76

All I got so far is to make it work with fixed width as per the code below

```<code>Sub exporttosheet()

Dim fPath As String
fPath = "C:\test.txt"

Const fsoForReading = 1
Const F_LEN_A As Integer = 10
Const F_LEN_B As Integer = 23
Const F_LEN_C As Integer = 7
Const F_LEN_D As Integer = 10

Dim objFSO As Object, objTextStream As Object, txt, f1, f2, f3, f4
Dim start As Integer
Dim fLen As Integer
Dim rw As Long

Set objFSO = CreateObject("scripting.filesystemobject")
Set objTextStream = objFSO.OpenTextFile(fPath, fsoForReading)
rw = 1

Do Until objTextStream.AtEndOfStream
    txt = objTextStream.Readline

    f1 = Trim(Left(txt, F_LEN_A))
    start = F_LEN_A + 1
    f2 = Trim(Mid(txt, start, F_LEN_B))
    start = start + F_LEN_B + 1
    f3 = Trim(Mid(txt, start, F_LEN_C))
    start = start + F_LEN_C + 1
    f4 = Trim(Mid(txt, start, F_LEN_D))

    With ThisWorkbook.Sheets("data").Cells(rw, 1).Resize(1, 4)
        .NumberFormat = "@" 'format cells as text
        .Value = Array(f1, f2, f3, f4)
    End With
    rw = rw + 1
Loop

objTextStream.Close
End Sub
</code>```

答:
you could use the following function to get columns length out of a "header" line:

```<code>Function GetF_LENs(txt As Variant, nCols As Long) As Variant
    Dim t As Variant
    Dim iFLEN As Long

    t = Split(WorksheetFunction.Trim(txt), " ")
    nCols = UBound(t) + 1 '<--| the number of columns equals the number of found values
    ReDim FLENs(1 To nCols - 1) '<--| we need the width of columns till the one before the last column
    For iFLEN = 1 To nCols - 1
        FLENs(iFLEN) = InStr(txt, t(iFLEN))
    Next
    GetF_LENs = FLENs
End Function
</code>```

and you could exploit it in your code as follows:

```<code>Sub exporttosheet()
    Const fsoForReading = 1

    Dim fPath As String
    fPath = "C:\test.txt"

    Dim F_LENs As Variant, txt As Variant
    Dim objFSO As Object, objTextStream As Object
    Dim rw As Long, nCols As Long

    Set objFSO = CreateObject("scripting.filesystemobject")
    Set objTextStream = objFSO.OpenTextFile(fPath, fsoForReading)

    txt = objTextStream.Readline '<--| read the first "header" line
    F_LENs = GetF_LENs(txt, nCols) '<--| get 'F_LENs' array out of "header" line: it stores the widths of all columns
    ReDim values(1 To nCols) '<--| resize the array that will hold each row values accordingly to the number of columns encountered
    rw = 1
    Do Until objTextStream.AtEndOfStream
        ReadValuesAndWriteCells txt, F_LENs, values, nCols, rw
        txt = objTextStream.Readline '<--| read the first "header" line
    Loop
    ReadValuesAndWriteCells txt, F_LENs, values, nCols, rw

    objTextStream.Close
End Sub
</code>```

where I demaned the current line reading and writing to the following sub

```<code>Sub ReadValuesAndWriteCells(txt As Variant, F_LENs As Variant, values As Variant, nCols As Long, rw As Long)
    Dim start As Integer
    Dim fLen As Integer

    start = 1
    For fLen = 1 To nCols - 1 '<--| loop through 'F_LENs' array, i.e.: through current line columns
        values(fLen) = Trim(Mid(txt, start, F_LENs(fLen) - start)) '<-- store current line current column value in corresponding 'Values' index
        start = F_LENs(fLen)
    Next
    values(fLen) = Trim(Mid(txt, start)) '<-- store current line last column value

    With ThisWorkbook.Sheets("data").Cells(rw, 1).Resize(1, nCols)
        .NumberFormat = "@" 'format cells as text
        .Value = values '<--| write current line array values
    End With
    rw = rw + 1
End Sub
</code>```

Body:
I am trying to return a value equal to the position of the first letter coming after two or more spaces.

I have a tool that extract tables with variable column length into TXT docs. I need to get these tables into an Excel sheet without having to put fixed width to each column in each table (that is a lot of coding to be done). I am trying to find something more dynamic to do so based on the position of the first character after two or more spaces.

Bearing in mind that not all rows are fully populated but the first row would make a perfect candidate to get the width of the column.

To give an example, the lines of the text would look like this

John       Robert       Eric       Tom

10          11            143        43

21                       265        56

99          241                     76

All I got so far is to make it work with fixed width as per the code below

Sub exporttosheet()

Dim fPath As String
fPath = "C:\test.txt"

Const fsoForReading = 1
Const F_LEN_A As Integer = 10
Const F_LEN_B As Integer = 23
Const F_LEN_C As Integer = 7
Const F_LEN_D As Integer = 10

Dim objFSO As Object, objTextStream As Object, txt, f1, f2, f3, f4
Dim start As Integer
Dim fLen As Integer
Dim rw As Long

Set objFSO = CreateObject("scripting.filesystemobject")
Set objTextStream = objFSO.OpenTextFile(fPath, fsoForReading)
rw = 1

Do Until objTextStream.AtEndOfStream
    txt = objTextStream.Readline

    f1 = Trim(Left(txt, F_LEN_A))
    start = F_LEN_A + 1
    f2 = Trim(Mid(txt, start, F_LEN_B))
    start = start + F_LEN_B + 1
    f3 = Trim(Mid(txt, start, F_LEN_C))
    start = start + F_LEN_C + 1
    f4 = Trim(Mid(txt, start, F_LEN_D))

    With ThisWorkbook.Sheets("data").Cells(rw, 1).Resize(1, 4)
        .NumberFormat = "@" 'format cells as text
        .Value = Array(f1, f2, f3, f4)
    End With
    rw = rw + 1
Loop

objTextStream.Close
End Sub

Body:
you could use the following function to get columns length out of a "header" line:

Function GetF_LENs(txt As Variant, nCols As Long) As Variant
    Dim t As Variant
    Dim iFLEN As Long

    t = Split(WorksheetFunction.Trim(txt), " ")
    nCols = UBound(t) + 1 '<--| the number of columns equals the number of found values
    ReDim FLENs(1 To nCols - 1) '<--| we need the width of columns till the one before the last column
    For iFLEN = 1 To nCols - 1
        FLENs(iFLEN) = InStr(txt, t(iFLEN))
    Next
    GetF_LENs = FLENs
End Function

and you could exploit it in your code as follows:

Sub exporttosheet()
    Const fsoForReading = 1

    Dim fPath As String
    fPath = "C:\test.txt"

    Dim F_LENs As Variant, txt As Variant
    Dim objFSO As Object, objTextStream As Object
    Dim rw As Long, nCols As Long

    Set objFSO = CreateObject("scripting.filesystemobject")
    Set objTextStream = objFSO.OpenTextFile(fPath, fsoForReading)

    txt = objTextStream.Readline '<--| read the first "header" line
    F_LENs = GetF_LENs(txt, nCols) '<--| get 'F_LENs' array out of "header" line: it stores the widths of all columns
    ReDim values(1 To nCols) '<--| resize the array that will hold each row values accordingly to the number of columns encountered
    rw = 1
    Do Until objTextStream.AtEndOfStream
        ReadValuesAndWriteCells txt, F_LENs, values, nCols, rw
        txt = objTextStream.Readline '<--| read the first "header" line
    Loop
    ReadValuesAndWriteCells txt, F_LENs, values, nCols, rw

    objTextStream.Close
End Sub

where I demaned the current line reading and writing to the following sub

Sub ReadValuesAndWriteCells(txt As Variant, F_LENs As Variant, values As Variant, nCols As Long, rw As Long)
    Dim start As Integer
    Dim fLen As Integer

    start = 1
    For fLen = 1 To nCols - 1 '<--| loop through 'F_LENs' array, i.e.: through current line columns
        values(fLen) = Trim(Mid(txt, start, F_LENs(fLen) - start)) '<-- store current line current column value in corresponding 'Values' index
        start = F_LENs(fLen)
    Next
    values(fLen) = Trim(Mid(txt, start)) '<-- store current line last column value

    With ThisWorkbook.Sheets("data").Cells(rw, 1).Resize(1, nCols)
        .NumberFormat = "@" 'format cells as text
        .Value = values '<--| write current line array values
    End With
    rw = rw + 1
End Sub


问:
java how can i check a file name and open with FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");
Using FileResource from edu.duke, how can I check if the file exists before opening it like this?</p>

```<code>FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");
</code>```

答:
Use File api to check whether file exists or not and then do whatever action you need to do with edu.duke library. Here you go how the code should look like</p>

```<code>String resourceName = "/testing/yob" + auxYear + "short.csv";
File file = new File(resourceName);
if(file.exists()){
   FileResource auxFr = new FileResource(file);
}
</code>```

Body:
Using FileResource from edu.duke, how can I check if the file exists before opening it like this?

FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");

Body:
Use File api to check whether file exists or not and then do whatever action you need to do with edu.duke library. Here you go how the code should look like

String resourceName = "/testing/yob" + auxYear + "short.csv";
File file = new File(resourceName);
if(file.exists()){
   FileResource auxFr = new FileResource(file);
}


问:
itextsharp: get table headers in all the pages
I have this code below please help me to repeat the table headers in each page. I have tried with few options availavle on net but they are not working. I am using ItextSharp for the first time.
Thanks </p>

```<code>    int columns = gv.Columns.Count;
    int rows = gv.Rows.Count;
    int tableRows = rows + 3;
    string flName = "";

    if (gv.ID == "gvShares")
    {
        flName = "Share_Statement.pdf";
    }

    if (gv.ID == "gvSavingAccStmt")
    {
        flName = "Main_Saving_Account_Statement.pdf";
    }

    Document Doc = new Document();
    PdfWriter.GetInstance(Doc, Response.OutputStream);
    Doc.Open();

    BaseFont bfTimes = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
    Font times = new Font(bfTimes, 9, Font.NORMAL, Color.BLACK);

    //string imageFilePath = HttpContext.Current.Server.MapPath("/Image/Sacco_Logo.jpg");

    string test = System.Web.HttpContext.Current.Server.MapPath(".");

    string substr = test.Remove(test.Length - 6);

    //string imageFilePath = "\\app\\Image\\Sacco_Logo.jpg";//"\\app\\Image\\Sacco_Logo.jpg";
    iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(substr + "\\Image\\Sacco_Logo.jpg");

    //Resize image depend upon your need
    jpg.ScaleToFit(75f, 75f);

    jpg.SpacingAfter = 10f;

    jpg.Alignment = Element.ALIGN_LEFT;

    //Doc.Add(jpg);

    PdfPTable table = new PdfPTable(1);
    table.DefaultCell.Border = PdfPCell.NO_BORDER;
    table.WidthPercentage = 100;

    PdfPCell cell = new PdfPCell( table.DefaultCell);
    cell.Border = PdfPCell.BOTTOM_BORDER;
    cell.PaddingBottom = 5;

    Phrase phrase = new Phrase();
    phrase.Add(new Chunk(jpg, 0, 0));
    phrase.Add(new Chunk("Kenya Diaspora Sacco"));
    cell.AddElement( phrase );
    table.AddCell(cell);

    Doc.Add(table);

    Phrase phrNewLine = new Phrase("\n");

    Doc.Add(phrNewLine);

    Paragraph TitlePhrasePh = new Paragraph("Membership Savings Account Statement", times);
    TitlePhrasePh.SetAlignment("Center");
    Doc.Add(TitlePhrasePh);

    Doc.Add(phrNewLine);

    Paragraph PhUsername = new Paragraph("Name: " + Username, times);
    PhUsername.SetAlignment("Left");
    Doc.Add(PhUsername);

    Paragraph PhAccount = new Paragraph("Account Number: " + AccountNumber, times);
    PhAccount.SetAlignment("Left");
    Doc.Add(PhAccount);

    iTextSharp.text.Table gridViewTable = new iTextSharp.text.Table(columns, tableRows);
    gridViewTable.BorderWidth = 1;
    gridViewTable.BorderColor = new Color(0, 0, 255);
    gridViewTable.Cellpadding = 1;
    gridViewTable.Cellspacing = 1;

    gridViewTable.AddCell(new Paragraph("Date", times));
    gridViewTable.AddCell(new Paragraph("Type", times));
    gridViewTable.AddCell(new Paragraph("Description", times));

    if (gv.ID == "gvShares")
    {
        gridViewTable.AddCell(new Paragraph("Sell[KHSH]", times));
    }

    gridViewTable.AddCell(new Paragraph("Debit[KHSH]", times));

    if (gv.ID == "gvShares")
    {
        gridViewTable.AddCell(new Paragraph("Buy[KHSH]", times));
    }

    gridViewTable.AddCell(new Paragraph("Credit[KHSH]", times));

    if (gv.ID == "gvShares")
    {
        gridViewTable.AddCell(new Paragraph("Balance", times));
    }
    else if (gv.ID == "gvSavingAccStmt")
    {
        gridViewTable.AddCell(new Paragraph("Balance[KHSH]", times));
    }

    for (int rowCounter = 0; rowCounter < rows; rowCounter++)
    {
        for (int columnCounter = 0; columnCounter < columns; columnCounter++)
        {
            string strValue = gv.Rows[rowCounter].Cells[columnCounter].Text;
            gridViewTable.AddCell(new Paragraph(strValue, times));
        }
    }

    Doc.Add(gridViewTable);
    Doc.Close();
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment; filename=" + flName);
    Response.End();
</code>```

答:
Like this:</p>

```<code>        PdfPTable table = new PdfPTable(12);
        table.HeaderRows = 1; /*---->> this property repeats the headers of an iTextSharp PdfPTable on each page */
        table.TotalWidth = 900f;
        table.LockedWidth = true;
        //table.HorizontalAlignment = 0;
        float[] widths = new float[] { 20f, 32f, 13f, 24f, 20f, 20f, 30f, 15f, 15f, 20f, 20f, 60f };
        table.SetWidths(widths);
</code>```

Body:
I have this code below please help me to repeat the table headers in each page. I have tried with few options availavle on net but they are not working. I am using ItextSharp for the first time.
Thanks

    int columns = gv.Columns.Count;
    int rows = gv.Rows.Count;
    int tableRows = rows + 3;
    string flName = "";

    if (gv.ID == "gvShares")
    {
        flName = "Share_Statement.pdf";
    }

    if (gv.ID == "gvSavingAccStmt")
    {
        flName = "Main_Saving_Account_Statement.pdf";
    }

    Document Doc = new Document();
    PdfWriter.GetInstance(Doc, Response.OutputStream);
    Doc.Open();

    BaseFont bfTimes = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
    Font times = new Font(bfTimes, 9, Font.NORMAL, Color.BLACK);

    //string imageFilePath = HttpContext.Current.Server.MapPath("/Image/Sacco_Logo.jpg");

    string test = System.Web.HttpContext.Current.Server.MapPath(".");

    string substr = test.Remove(test.Length - 6);

    //string imageFilePath = "\\app\\Image\\Sacco_Logo.jpg";//"\\app\\Image\\Sacco_Logo.jpg";
    iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(substr + "\\Image\\Sacco_Logo.jpg");

    //Resize image depend upon your need
    jpg.ScaleToFit(75f, 75f);

    jpg.SpacingAfter = 10f;

    jpg.Alignment = Element.ALIGN_LEFT;

    //Doc.Add(jpg);

    PdfPTable table = new PdfPTable(1);
    table.DefaultCell.Border = PdfPCell.NO_BORDER;
    table.WidthPercentage = 100;

    PdfPCell cell = new PdfPCell( table.DefaultCell);
    cell.Border = PdfPCell.BOTTOM_BORDER;
    cell.PaddingBottom = 5;

    Phrase phrase = new Phrase();
    phrase.Add(new Chunk(jpg, 0, 0));
    phrase.Add(new Chunk("Kenya Diaspora Sacco"));
    cell.AddElement( phrase );
    table.AddCell(cell);

    Doc.Add(table);

    Phrase phrNewLine = new Phrase("\n");

    Doc.Add(phrNewLine);

    Paragraph TitlePhrasePh = new Paragraph("Membership Savings Account Statement", times);
    TitlePhrasePh.SetAlignment("Center");
    Doc.Add(TitlePhrasePh);

    Doc.Add(phrNewLine);

    Paragraph PhUsername = new Paragraph("Name: " + Username, times);
    PhUsername.SetAlignment("Left");
    Doc.Add(PhUsername);

    Paragraph PhAccount = new Paragraph("Account Number: " + AccountNumber, times);
    PhAccount.SetAlignment("Left");
    Doc.Add(PhAccount);

    iTextSharp.text.Table gridViewTable = new iTextSharp.text.Table(columns, tableRows);
    gridViewTable.BorderWidth = 1;
    gridViewTable.BorderColor = new Color(0, 0, 255);
    gridViewTable.Cellpadding = 1;
    gridViewTable.Cellspacing = 1;

    gridViewTable.AddCell(new Paragraph("Date", times));
    gridViewTable.AddCell(new Paragraph("Type", times));
    gridViewTable.AddCell(new Paragraph("Description", times));

    if (gv.ID == "gvShares")
    {
        gridViewTable.AddCell(new Paragraph("Sell[KHSH]", times));
    }

    gridViewTable.AddCell(new Paragraph("Debit[KHSH]", times));

    if (gv.ID == "gvShares")
    {
        gridViewTable.AddCell(new Paragraph("Buy[KHSH]", times));
    }

    gridViewTable.AddCell(new Paragraph("Credit[KHSH]", times));

    if (gv.ID == "gvShares")
    {
        gridViewTable.AddCell(new Paragraph("Balance", times));
    }
    else if (gv.ID == "gvSavingAccStmt")
    {
        gridViewTable.AddCell(new Paragraph("Balance[KHSH]", times));
    }

    for (int rowCounter = 0; rowCounter < rows; rowCounter++)
    {
        for (int columnCounter = 0; columnCounter < columns; columnCounter++)
        {
            string strValue = gv.Rows[rowCounter].Cells[columnCounter].Text;
            gridViewTable.AddCell(new Paragraph(strValue, times));
        }
    }

    Doc.Add(gridViewTable);
    Doc.Close();
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment; filename=" + flName);
    Response.End();

Body:
Like this:

        PdfPTable table = new PdfPTable(12);
        table.HeaderRows = 1; /*---->> this property repeats the headers of an iTextSharp PdfPTable on each page */
        table.TotalWidth = 900f;
        table.LockedWidth = true;
        //table.HorizontalAlignment = 0;
        float[] widths = new float[] { 20f, 32f, 13f, 24f, 20f, 20f, 30f, 15f, 15f, 20f, 20f, 60f };
        table.SetWidths(widths);


问:
How to get the path of an Image Field in a pdf form, in Adobe?
I am creating a PDF form using adobe reader. I have added an image field and a text box. The text box is read-only and I want to populate the text box with the path of the image selected by the end-user, in the image field. Following is my code:

```<code>var one = this.getField("Image1");
var two = this.getField("Text1");
two.value='The Path';
</code>```

The above code runs normally but I can't figure out as to what to write instead of 'The Path', to get the actual path of the image selected by the end-user.

P.S.

On the Image1 button there are 2 actions:

Mouse Up(execute Js)

event.target.buttonImportIcon();

On Blur(execute Js)

var one = this.getField("Image1");
var two = this.getField("Text1");
two.value='The Path';

答:
If I am understanding your request correctly... Assuming that Image1 is a button field and Text1 is a text field and you want the selected image file to appear as the button icon, the code would be as follows...</p>

```<code>var one = this.getField("Image1");
var two = this.getField("Text1");
var doc = app.browseForDoc(); // Allows the user to browse for a file
var docPath = doc.cPath; // gets the file path of the selected file
one.buttonImportIcon(docPath); // uses the selected path to import the image as the "normal" or "up" button icon
two.value = docPath; // set the value of the text field to the selected device independent path
</code>```

Body:
I am creating a PDF form using adobe reader. I have added an image field and a text box. The text box is read-only and I want to populate the text box with the path of the image selected by the end-user, in the image field. Following is my code:

var one = this.getField("Image1");
var two = this.getField("Text1");
two.value='The Path';

The above code runs normally but I can't figure out as to what to write instead of 'The Path', to get the actual path of the image selected by the end-user.

P.S.

On the Image1 button there are 2 actions:

Mouse Up(execute Js)

event.target.buttonImportIcon();

On Blur(execute Js)

var one = this.getField("Image1");
var two = this.getField("Text1");
two.value='The Path';

Body:
If I am understanding your request correctly... Assuming that Image1 is a button field and Text1 is a text field and you want the selected image file to appear as the button icon, the code would be as follows...

var one = this.getField("Image1");
var two = this.getField("Text1");
var doc = app.browseForDoc(); // Allows the user to browse for a file
var docPath = doc.cPath; // gets the file path of the selected file
one.buttonImportIcon(docPath); // uses the selected path to import the image as the "normal" or "up" button icon
two.value = docPath; // set the value of the text field to the selected device independent path


问:
why i can't extends SimpleSwingGUIApplication?
i need to extends SimpleSwingGUIApplication for my GUI application but i have an error :
not found : type SimpleSwingGUIApplication

there is my code :

import scala.swing._

class GUI extends SimpleSwingGUIApplication{}
thanks for your answer :)

答: It depends on what version of Scala and scala-swing you use. In scala-swing 2.0.x it's apparently SimpleSwingApplication, see https://github.com/scala/scala-swing/tree/2.0.x/src/main/scala/scala/swing. Note the "mostly-unsupported" in https://github.com/scala/scala-swing.</p>


问:
more intuitive way to fill up three elements right of diagonal vectors
I need to fill up the matrix in the figure. My way is to use the loop which is not east to read. When the dimension is large, it not efficient too.
Is there any way to make it easier to read and probably quicker (say using vectorization or some function I don't know?)

```<code># The code is in python, but I am open to R as well.
    S=6
    p=[0.1,0.3,0.6] # the pi in the figure
    # The reason I use loop for p is that it handles a flexible dimension of p
    mat = np.zeros((S, S))
    p = np.array(p)
    for i in range(S):
        for j, x in enumerate(p):
                if i + j < S-1:
                    mat[i+j][i] = x

                elif i + j == S-1:
                    mat[S-1][i] = p[j:].sum()
                else:
                    pass

    mat.T
</code>```

答:
As always, there are lots of equivalent ways to build a matrix.  When I first saw it, I thought "oh, it's like the top part of a Toeplitz", but summing the diagonals in p should also work (note I've included the bottom-right change).  Some googling revealed yet another way, using scipy.sparse.diags:

```<code>import numpy as np
import scipy.sparse
from scipy.linalg import triu, toeplitz

def build_toep(S, p):
    out = triu(toeplitz(p + [0]*(S-len(p))))
    out[-2:,-1] = [1 - p[1], 1]
    return out

def build_diag(S, p):
    out = sum(np.diag([v]*(S-i), i) for i,v in enumerate(p))
    out[-2:,-1] = [1 - p[1], 1]
    return out

def build_sparse(S, p):
    out = scipy.sparse.diags(p, range(len(p)), shape=(S, S)).toarray()
    out[-2:,-1] = [1 - p[1], 1]
    return out
</code>```

which gives

```<code>In [150]: S, p = 6, [0.1, 0.3, 0.6]

In [151]: build_toep(S, p)
Out[151]:
array([[ 0.1,  0.3,  0.6,  0. ,  0. ,  0. ],
       [ 0. ,  0.1,  0.3,  0.6,  0. ,  0. ],
       [ 0. ,  0. ,  0.1,  0.3,  0.6,  0. ],
       [ 0. ,  0. ,  0. ,  0.1,  0.3,  0.6],
       [ 0. ,  0. ,  0. ,  0. ,  0.1,  0.7],
       [ 0. ,  0. ,  0. ,  0. ,  0. ,  1. ]])

In [152]: np.allclose(build_toep(S, p), build_diag(S, p))
Out[152]: True

In [153]: np.allclose(build_toep(S, p), build_sparse(S, p))
Out[153]: True
</code>```

Body:
I need to fill up the matrix in the figure. My way is to use the loop which is not east to read. When the dimension is large, it not efficient too.
Is there any way to make it easier to read and probably quicker (say using vectorization or some function I don't know?)

# The code is in python, but I am open to R as well.
    S=6
    p=[0.1,0.3,0.6] # the pi in the figure
    # The reason I use loop for p is that it handles a flexible dimension of p
    mat = np.zeros((S, S))
    p = np.array(p)
    for i in range(S):
        for j, x in enumerate(p):
                if i + j < S-1:
                    mat[i+j][i] = x

                elif i + j == S-1:
                    mat[S-1][i] = p[j:].sum()
                else:
                    pass

    mat.T

Body:
As always, there are lots of equivalent ways to build a matrix.  When I first saw it, I thought "oh, it's like the top part of a Toeplitz", but summing the diagonals in p should also work (note I've included the bottom-right change).  Some googling revealed yet another way, using scipy.sparse.diags:

import numpy as np
import scipy.sparse
from scipy.linalg import triu, toeplitz

def build_toep(S, p):
    out = triu(toeplitz(p + [0]*(S-len(p))))
    out[-2:,-1] = [1 - p[1], 1]
    return out

def build_diag(S, p):
    out = sum(np.diag([v]*(S-i), i) for i,v in enumerate(p))
    out[-2:,-1] = [1 - p[1], 1]
    return out

def build_sparse(S, p):
    out = scipy.sparse.diags(p, range(len(p)), shape=(S, S)).toarray()
    out[-2:,-1] = [1 - p[1], 1]
    return out

which gives

In [150]: S, p = 6, [0.1, 0.3, 0.6]

In [151]: build_toep(S, p)
Out[151]:
array([[ 0.1,  0.3,  0.6,  0. ,  0. ,  0. ],
       [ 0. ,  0.1,  0.3,  0.6,  0. ,  0. ],
       [ 0. ,  0. ,  0.1,  0.3,  0.6,  0. ],
       [ 0. ,  0. ,  0. ,  0.1,  0.3,  0.6],
       [ 0. ,  0. ,  0. ,  0. ,  0.1,  0.7],
       [ 0. ,  0. ,  0. ,  0. ,  0. ,  1. ]])

In [152]: np.allclose(build_toep(S, p), build_diag(S, p))
Out[152]: True

In [153]: np.allclose(build_toep(S, p), build_sparse(S, p))
Out[153]: True


问:
JQuery - why does live work but click doesn't?
We have a page with this structure:

```<code><script type="text/javascript" src="/js/lots.of.javascript.js"></script>
<jsp:include page="html.jsp"/>
</code>```

The JavaScript has lots of $(function(){...} blocks.  In one block we tried a $("#mylink").click(...) but this did NOT work.  However the corresponding .live('click' DID work.  Why is this?

Update: More specifically I am assuming the click and live statements ARE running after the link has been added to the DOM as the link is included in the html.jsp file and the statements are executed in $(function(){...} blocks...  So given this I'm not sure why click wouldn't work...

答: Seeing no code, the obvious reason is that the element is created after the event gets defined. That's the main reason to use .live().

Body:
We have a page with this structure:

<jsp:include page="html.jsp"/>

The JavaScript has lots of $(function(){...} blocks.  In one block we tried a $("#mylink").click(...) but this did NOT work.  However the corresponding .live('click' DID work.  Why is this?

Update: More specifically I am assuming the click and live statements ARE running after the link has been added to the DOM as the link is included in the html.jsp file and the statements are executed in $(function(){...} blocks...  So given this I'm not sure why click wouldn't work...


问:
Calling remove on an non existing record crashes program
After calling remove for a record that doesn't exist in the table, the program crashes...i am assuming a null value is being passed in that I am missing in a logical step somewhere.</p>

答: The crash is to be expected. You do not check for nullptr in find. You can easily verify this: execute find after you have created the hash table.</p>


问:
inotifywait not detected in /sys/class/gpio/gpioXX/ (raspberry pi)
I have connected 2 raspberry pi using GPIO :
The first one is the master, and use GPIO2 (and GND...)
The second one is a slave, and use GPIO0 and GPIO1
All are switch on a relay card

I put GPIO1 and GPIO0 on direction "IN" and GPI02 on direction "out" :
    echo in > /sys/class/gpio/gpioXX/direction

On my master, (GPIO2, direction = OUT), when i put the pin GPIO2 to 1, the 2 pins on my slave turn to 1 too. So, no probleme here

I add a shell script, using inotifywait on one folder (for example  /sys/class/gpio/gpio18/  (18 for GPIO1)).

When I'm on my SLAVE, and i try to modify the value of /sys/class/gpio/gpio18/ with an echo 1 > .../value , inotifywait catch a modification, but the value didn't change ( -bash: echo: write error: Operation not permitted , it's normal because direction is on "IN" ).

When I'm on my MASTER, and i modify the value of gpio27 (corresponding to GPI02), both value file (GPIO0, GPIO1 and GPIO2) change, but my inotifywait didn't catch the modification on gpio/gpio18/value (the containt of the file change from 0 to 1 or inversely)

答:
I can't say for sure what is wrong. But I would try running a simple script like this and see what happens:</p>

```<code>while inotifywait -e modify /sys/class/gpio/gpio18/; do echo "Hello"; done
</code>```

Body:
I can't say for sure what is wrong. But I would try running a simple script like this and see what happens:

while inotifywait -e modify /sys/class/gpio/gpio18/; do echo "Hello"; done


问:
Avoid collision in importing data in R
I faced an error trying to import a CSV into R which had multiple duplicate columns, is there a way I can ignore those columns?
It's easy to do that in case of small files and small number of columns but mine is a big one ~3k columns and 10M rows.</p>

答: Alternatively, set the check.names arg to FALSE. </p>

Title: Avoid collision in importing data in R


问:
Convert array of objects into object
This is my object:

```<code>initialState:any = [{'checked':true}, {'checked':false}, {'checked':true}, {'checked':false}, {'checked':true}, {'checked':false}];
</code>```

This is the output that I expect:

```<code>var params = {
    "device0":"true",
    "device1":"true",
    "device2":"false",
    "device3":"true",
    "device4":"false",
    "device5":"true",
    "device6":"false",
    "device7":"true"
}
</code>```

I have an array of objects. I want to take value from an object and want to build single object as mentioned above.

答:
You could use Object.assign and Array#map for the sinlge objects.

var any = [{ checked: true }, { checked: false }, { checked: true }, { checked: false }, { checked: true }, { checked: false }],
    params = Object.assign({}, ...any.map((a, i) => ({ ['device' + i]: a.checked.toString() })));

console.log(params);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Convert array of objects into object

Body:
This is my object:

initialState:any = [{'checked':true}, {'checked':false}, {'checked':true}, {'checked':false}, {'checked':true}, {'checked':false}];

This is the output that I expect:

var params = {
    "device0":"true",
    "device1":"true",
    "device2":"false",
    "device3":"true",
    "device4":"false",
    "device5":"true",
    "device6":"false",
    "device7":"true"
}

I have an array of objects. I want to take value from an object and want to build single object as mentioned above.

Body:
You could use Object.assign and Array#map for the sinlge objects.

var any = [{ checked: true }, { checked: false }, { checked: true }, { checked: false }, { checked: true }, { checked: false }],
    params = Object.assign({}, ...any.map((a, i) => ({ ['device' + i]: a.checked.toString() })));

console.log(params);

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


问:
Code Push breaking jest tests for react-native
I have configured an app for code-push, it works well except for jest tests. It fails in rendering app for this error:

```<code>TypeError: Cannot read property 'CheckFrequency' of undefined

  at Object.<anonymous> (app/index.js:7:66)
  at Object.<anonymous> (index.ios.js:5:12)
  at Object.<anonymous> (__tests__/index.ios.js:4:12)
</code>```

in this line:

```<code>const codePushOptions = { checkFrequency: codePush.CheckFrequency.MANUAL };
</code>```

The test code is:

```<code>import App from '../index.ios';

it('renders correctly', () => {
  const tree = renderer.create(
      <App />,
  );
});
</code>```

答: You need a mock up for code-push to work, this line CodePush.CheckFrequency.MANUAL will always produce the null.

Body:
I have configured an app for code-push, it works well except for jest tests. It fails in rendering app for this error:

TypeError: Cannot read property 'CheckFrequency' of undefined

  at Object.<anonymous> (app/index.js:7:66)
  at Object.<anonymous> (index.ios.js:5:12)
  at Object.<anonymous> (__tests__/index.ios.js:4:12)

in this line:

const codePushOptions = { checkFrequency: codePush.CheckFrequency.MANUAL };

The test code is:

import App from '../index.ios';

it('renders correctly', () => {
  const tree = renderer.create(
      <App />,
  );
});


问:
Get internal byte array from ByteArrayInputStream
I want to get the internal byte array from ByteArrayInputStream. I don't want to extends that class or write it into another byte array. Is there a utility class that help me do that?

Thanks,

答:
You can not get access to the same byte array, but you can easily copy the contents of the stream:</p>

```<code>public byte[] read(ByteArrayInputStream bais) {
     byte[] array = new byte[bais.available()];
     bais.read(array);

     return array;
}
</code>```

Body:
You can not get access to the same byte array, but you can easily copy the contents of the stream:

public byte[] read(ByteArrayInputStream bais) {
     byte[] array = new byte[bais.available()];
     bais.read(array);

     return array;
}


问:
What is the date format for this string?
I've got the following date as a string

```<code>2017-03-01T10:15:41-0800
</code>```

that I'm trying to use with

```<code>new Date().parse('dd/mm/yyyy', dateString)
</code>```

However, I can't figure out the format.

答:
If you can, and you're on Java 8, avoid java.util.Date, and parse it into one of the new java.time classes:

```<code>import java.time.*
import java.time.format.DateTimeFormatter

def dateString =  "2017-03-01T10:15:41-0800"

def date = OffsetDateTime.parse(dateString,
                                DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"))
</code>```

If you then want this time in another zone (ie: UTC), you can do:

```<code>def utcDate = date.atZoneSameInstant(ZoneOffset.UTC)
</code>```

Body:
I've got the following date as a string

2017-03-01T10:15:41-0800

that I'm trying to use with

new Date().parse('dd/mm/yyyy', dateString)

However, I can't figure out the format.

Body:
If you can, and you're on Java 8, avoid java.util.Date, and parse it into one of the new java.time classes:

import java.time.*
import java.time.format.DateTimeFormatter

def dateString =  "2017-03-01T10:15:41-0800"

def date = OffsetDateTime.parse(dateString,
                                DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"))

If you then want this time in another zone (ie: UTC), you can do:

def utcDate = date.atZoneSameInstant(ZoneOffset.UTC)


问:
Access Context Menu
I'm trying to access the Context Menu UI AutomationElement of Notepad, however I am struggling to do so:

```<code>Imports System.Windows.Automation
Imports System.Windows.Forms
Module AutomateNotepad
    Sub Main()
        Dim wNotepad, document As AutomationElement
        wNotepad = AutomationElement.RootElement.FindFirst(TreeScope.Children, New PropertyCondition(AutomationElement.NameProperty, "Untitled - Notepad"))

        document = wNotepad.FindFirst(TreeScope.Children, New PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "document"))
        document.SetFocus()

        SendKeys.SendWait("+{F10}")

        context = AutomationElement.RootElement.FindFirst(TreeScope.Children, New PropertyCondition(AutomationElement.NameProperty, "context"))
        While context Is Nothing
            Console.WriteLine("Trying to get context again")
            Threading.Thread.Sleep(100)
            context = AutomationElement.RootElement.FindFirst(TreeScope.Children, New PropertyCondition(AutomationElement.NameProperty, "context"))
        End While

        MsgBox("Found it!")

    End Sub
End Module
</code>```

My problem is that when I run the application, the notepad context menu opens but UIAutomation never appears to get the AutomationElement of it...

This is a screenshot from Inspect.exe:

Given the inspect picture and the structure it presents, I see no reason why this would be occurring... Does anyone know where I might be going wrong?

P.S. I'm very new to VB.NET but have been working with VBA for 2-3 years so I apologise for any bad habits I may have...

答:
I've found a solution to my issue. The trick is to subscribe to UIAutomation OpenMenuEvent. To do this I created a ContextWatcher class:

```<code>Public Class ContextWatcher
    Public Shared Menu As AutomationElement
    Private Shared _EventHandler As AutomationEventHandler
    Public Shared Sub trackContext()
        _EventHandler = New AutomationEventHandler(AddressOf OnContextOpened)
        Automation.AddAutomationEventHandler(AutomationElement.MenuOpenedEvent, AutomationElement.RootElement, TreeScope.Descendants, _EventHandler)
    End Sub
    Public Shared Sub untrackContext()
        Automation.RemoveAutomationEventHandler(AutomationElement.MenuOpenedEvent, AutomationElement.RootElement, _EventHandler)
    End Sub
    Private Shared Sub OnContextOpened(src As Object, args As AutomationEventArgs)
        Console.WriteLine("Menu opened.")
        Dim element = TryCast(src, AutomationElement)
        If element Is Nothing Then
            Return
        Else
            Menu = element
        End If
    End Sub
End Class
</code>```

To access the context menu I can use this:

```<code>ContextWatcher.trackContext()

SendKeys.SendWait("+{F10}")

Dim context As AutomationElement
context = ContextWatcher.Menu
While context Is Nothing
    Console.WriteLine("Trying to get context again")
    Threading.Thread.Sleep(100)
    context = ContextWatcher.Menu
End While

' Do Stuff with context menu

ContextWatcher.untrackContext()
Imports System.Windows.Automation
Imports System.Windows.Forms
Module AutomateNotepad
    Sub Main()
        Dim wNotepad, document As AutomationElement

        'Get 'Untitled - Notepad' main window
        wNotepad = AutomationElement.RootElement.FindFirst(TreeScope.Children, New PropertyCondition(AutomationElement.NameProperty, "Untitled - Notepad"))

        'Get Notepad document element
        document = wNotepad.FindFirst(TreeScope.Children, New PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "document"))

        'Set focus to document
        document.SetFocus()

        'Start watching for context menu
        ContextWatcher.trackContext()

        'Open context menu
        SendKeys.SendWait("+{F10}")

        'Get context menu from ContextWatcher class
        Dim context As AutomationElement
        context = ContextWatcher.Menu
        While context Is Nothing
            Console.WriteLine("Trying to get context again")
            Threading.Thread.Sleep(100)
            context = ContextWatcher.Menu
        End While

        'trigger undo
        invokeContextMenuItem(context, "Undo")

        'Stop watching for context menu
        ContextWatcher.untrackContext()
    End Sub

    Sub invokeContextMenuItem(context As AutomationElement, sMenuItem As String)
        'Get context menu children
        Dim controls As AutomationElementCollection = context.FindAll(TreeScope.Children, Condition.TrueCondition)

        'Loop over controls to find control with name sMenuItem
        Dim control As AutomationElement
        For Each control In controls
            If control.Current.Name = sMenuItem Then
                'Invoke control
                getInvokePattern(control).Invoke()
                Exit Sub
            End If
        Next
    End Sub

    'Helper function to get InvokePattern from UI Element
    Function getInvokePattern(element As AutomationElement) As InvokePattern
        Return element.GetCurrentPattern(InvokePattern.Pattern)
    End Function

    Public Class ContextWatcher
        Public Shared Menu As AutomationElement
        Private Shared _EventHandler As AutomationEventHandler
        Public Shared Sub trackContext()
            _EventHandler = New AutomationEventHandler(AddressOf OnContextOpened)
            Automation.AddAutomationEventHandler(AutomationElement.MenuOpenedEvent, AutomationElement.RootElement, TreeScope.Descendants, _EventHandler)
        End Sub
        Public Shared Sub untrackContext()
            Automation.RemoveAutomationEventHandler(AutomationElement.MenuOpenedEvent, AutomationElement.RootElement, _EventHandler)
        End Sub
        Private Shared Sub OnContextOpened(src As Object, args As AutomationEventArgs)
            Console.WriteLine("Menu opened.")
            Dim element = TryCast(src, AutomationElement)
            If element Is Nothing Then
                Return
            Else
                Menu = element
            End If
        End Sub
    End Class
End Module
</code>```

Title: Access Context Menu

Body:
I'm trying to access the Context Menu UI AutomationElement of Notepad, however I am struggling to do so:

Imports System.Windows.Automation
Imports System.Windows.Forms
Module AutomateNotepad
    Sub Main()
        Dim wNotepad, document As AutomationElement
        wNotepad = AutomationElement.RootElement.FindFirst(TreeScope.Children, New PropertyCondition(AutomationElement.NameProperty, "Untitled - Notepad"))

        document = wNotepad.FindFirst(TreeScope.Children, New PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "document"))
        document.SetFocus()

        SendKeys.SendWait("+{F10}")

        context = AutomationElement.RootElement.FindFirst(TreeScope.Children, New PropertyCondition(AutomationElement.NameProperty, "context"))
        While context Is Nothing
            Console.WriteLine("Trying to get context again")
            Threading.Thread.Sleep(100)
            context = AutomationElement.RootElement.FindFirst(TreeScope.Children, New PropertyCondition(AutomationElement.NameProperty, "context"))
        End While

        MsgBox("Found it!")

    End Sub
End Module

My problem is that when I run the application, the notepad context menu opens but UIAutomation never appears to get the AutomationElement of it...

This is a screenshot from Inspect.exe:

Given the inspect picture and the structure it presents, I see no reason why this would be occurring... Does anyone know where I might be going wrong?

P.S. I'm very new to VB.NET but have been working with VBA for 2-3 years so I apologise for any bad habits I may have...

Body:
I've found a solution to my issue. The trick is to subscribe to UIAutomation OpenMenuEvent. To do this I created a ContextWatcher class:

Public Class ContextWatcher
    Public Shared Menu As AutomationElement
    Private Shared _EventHandler As AutomationEventHandler
    Public Shared Sub trackContext()
        _EventHandler = New AutomationEventHandler(AddressOf OnContextOpened)
        Automation.AddAutomationEventHandler(AutomationElement.MenuOpenedEvent, AutomationElement.RootElement, TreeScope.Descendants, _EventHandler)
    End Sub
    Public Shared Sub untrackContext()
        Automation.RemoveAutomationEventHandler(AutomationElement.MenuOpenedEvent, AutomationElement.RootElement, _EventHandler)
    End Sub
    Private Shared Sub OnContextOpened(src As Object, args As AutomationEventArgs)
        Console.WriteLine("Menu opened.")
        Dim element = TryCast(src, AutomationElement)
        If element Is Nothing Then
            Return
        Else
            Menu = element
        End If
    End Sub
End Class

To access the context menu I can use this:

ContextWatcher.trackContext()

SendKeys.SendWait("+{F10}")

Dim context As AutomationElement
context = ContextWatcher.Menu
While context Is Nothing
    Console.WriteLine("Trying to get context again")
    Threading.Thread.Sleep(100)
    context = ContextWatcher.Menu
End While

' Do Stuff with context menu

ContextWatcher.untrackContext()
Imports System.Windows.Automation
Imports System.Windows.Forms
Module AutomateNotepad
    Sub Main()
        Dim wNotepad, document As AutomationElement

        'Get 'Untitled - Notepad' main window
        wNotepad = AutomationElement.RootElement.FindFirst(TreeScope.Children, New PropertyCondition(AutomationElement.NameProperty, "Untitled - Notepad"))

        'Get Notepad document element
        document = wNotepad.FindFirst(TreeScope.Children, New PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "document"))

        'Set focus to document
        document.SetFocus()

        'Start watching for context menu
        ContextWatcher.trackContext()

        'Open context menu
        SendKeys.SendWait("+{F10}")

        'Get context menu from ContextWatcher class
        Dim context As AutomationElement
        context = ContextWatcher.Menu
        While context Is Nothing
            Console.WriteLine("Trying to get context again")
            Threading.Thread.Sleep(100)
            context = ContextWatcher.Menu
        End While

        'trigger undo
        invokeContextMenuItem(context, "Undo")

        'Stop watching for context menu
        ContextWatcher.untrackContext()
    End Sub

    Sub invokeContextMenuItem(context As AutomationElement, sMenuItem As String)
        'Get context menu children
        Dim controls As AutomationElementCollection = context.FindAll(TreeScope.Children, Condition.TrueCondition)

        'Loop over controls to find control with name sMenuItem
        Dim control As AutomationElement
        For Each control In controls
            If control.Current.Name = sMenuItem Then
                'Invoke control
                getInvokePattern(control).Invoke()
                Exit Sub
            End If
        Next
    End Sub

    'Helper function to get InvokePattern from UI Element
    Function getInvokePattern(element As AutomationElement) As InvokePattern
        Return element.GetCurrentPattern(InvokePattern.Pattern)
    End Function

    Public Class ContextWatcher
        Public Shared Menu As AutomationElement
        Private Shared _EventHandler As AutomationEventHandler
        Public Shared Sub trackContext()
            _EventHandler = New AutomationEventHandler(AddressOf OnContextOpened)
            Automation.AddAutomationEventHandler(AutomationElement.MenuOpenedEvent, AutomationElement.RootElement, TreeScope.Descendants, _EventHandler)
        End Sub
        Public Shared Sub untrackContext()
            Automation.RemoveAutomationEventHandler(AutomationElement.MenuOpenedEvent, AutomationElement.RootElement, _EventHandler)
        End Sub
        Private Shared Sub OnContextOpened(src As Object, args As AutomationEventArgs)
            Console.WriteLine("Menu opened.")
            Dim element = TryCast(src, AutomationElement)
            If element Is Nothing Then
                Return
            Else
                Menu = element
            End If
        End Sub
    End Class
End Module


问:
How to create folder based on first and second part of file name and move files into the folder?
I created the following batch script to create a folder based on today's date and then group files into folders based on the file name.

For example the files

```<code>JIM_BRICKMAN_QPS.avi
JIM_BRICKMAN_Slice.avi
JIM_BRICKMAN_Slice.jpg
</code>```

are moved to the folder BRICKMAN.

This works fine, however, attempts to modify the batch file to move the newly created folders into the newly created date folder fail or overwrite the folders when going through the loop.

```<code>for /F "tokens=1-4 delims=/" %%A in ('date /t') do (
    set DateDay=%%A
    set DateMonth=%%B
    set DateYear=%%C
)
set CurrentDate=%DateDay%-%DateMonth%-%DateYear%
if not exist "%CurrentDate%" md %CurrentDate%

for %%A in (*.avi *.jpg) do (
    for /f "tokens=1,* delims=_" %%D in ("%%~nA") do (
        md "%%D" 2>nul
        echo Moving file %%A to folder %%D
        move "%%A" "%%D" >nul
    )
)

echo Finished
</code>```

Additionally, I can't seem to get the token to ignore the first delimiter so that the folder is titled JIM_BRICKMAN and not just BRICKMAN.

EDIT:

I rewrote the batch file after the suggestions in the comments:

```<code>set "CurrentDate=%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%"
if not exist "%CurrentDate%" md %CurrentDate%
for %%A in (*.avi *.jpg) do (
    for /f "tokens=1,2 delims=_" %%D_%%E in ("%%~nA") do (
        md "%%D_%%E" 2>nul
        move "%%A" "%%D_%%E" >nul
    )
)
</code>```

But the script seems to bomb out. I tried to capture the error, but it closes despite me putting PAUSE in the script.

答:
Double clicking on a batch file in development is no good idea because this results in starting

```<code>%SystemRoot%\System32\cmd.exe /c "batch file name with full path and extension"
</code>```

As it can be read on running cmd /? from within a command prompt window, the option /C means close the command process and its console window immediately after execution of command, executable or script finished independent on the reason for ending the execution.

For debugging a batch file in development it is much better to

open a command prompt window,

change the current directory with command CD to directory of batch file and

run the batch file by typing its name and hitting key RETURN or ENTER.

For batch files which should work independent on which directory is the current directory, it is advisable to omit point 2 and run the batch file with entering its full path, file name and file extension enclosed in double quotes with current directory being not the directory of the batch file.

A batch file is executed from within a command prompt window with:

```<code>%SystemRoot%\System32\cmd.exe /K BatchFileNameAsTyped
</code>```

The option /K means keep command process running which results in keeping also command prompt window opened after execution of command/executable/script which makes it possible to read error messages.

The keys UP ARROW and DOWN ARROW can be used to reload command lines once entered in command prompt window making it easy to run the batch file once again after making a modification in GUI text editor.

And with having @echo off removed from first line of batch file, or changed to @echo ON, or commented out this line with command REM or with :: (invalid label) at beginning, it is also possible to see which lines Windows command interpreter really executes after applying immediate environment variable expansion and where an error occurs in case of a syntax error.

Wrong on second batch code is the line:

```<code>for /f "tokens=1,2 delims=_" %%D_%%E in ("%%~nA") do (
</code>```

Specified as loop variable must be always 1 character. Right would be:

```<code>for /f "tokens=1,2 delims=_" %%D in ("%%~nA") do (
</code>```

The command echo %DATE% outputs on my computer with my account and my region settings today the date 01.04.2017.

The command echo %DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4% outputs 01-04-2017.

So this part of the script works.

Hint: A list of directories in format YYYY-MM-DD is better than in format DD-MM-YYYY. The list of directories with format YYYY-MM-DD sorted alphabetically as by default is automatically with this date format also sorted from oldest to newest. Date format DD-MM-YYYY results in a weird list of the directories on being sorted alphabetically as by default.

A batch file for this task could be:

```<code>@echo off
set "CurrentDate=%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%"
for %%A in (*.avi *.jpg) do (
    for /F "tokens=1,2 delims=_" %%D in ("%%~nA") do (
        if not "%%E" == "" (
            md "%CurrentDate%\%%D_%%E" 2>nul
            move /Y "%%A" "%CurrentDate%\%%D_%%E\"
        ) else (
            md "%CurrentDate%\%%D" 2>nul
            move /Y "%%A" "%CurrentDate%\%%D\"
        )
    )
)
set "CurrentDate="
</code>```

How the inner loop works is most interesting for this task.

for /F and "%%~nA" means the command FOR should process just the file name of the *.avi or *.jpg file without file extension found by outer FOR loop.

delims=_ means the FOR command should split up the string into multiple parts (tokens) using underscore as delimiter. The first file name is JIM_BRICKMAN_QPS which would be split up to:

JIM assigned to loop variable D being specified in FOR command line,

BRICKMAN assigned to loop variable E which is the next character in ASCII table after D and

QPS assigned to loop variable F.

This string split feature is the reason why loop variables are interpreted case-sensitive while environment variables are interpreted not case-sensitive.

With tokens=1,2 is specified that just first and second string parts are of interest. So inner FOR can stop string splitting after having already determined the first two underscore delimited strings and having assigned them to the loop variables D and E.

FOR executes the command block if it could determine at least 1 string delimited by an underscore. So it is possible that loop variable D has a string value, but loop variable E is an empty string, for example if the file name does not contain any underscore. That is the reason for the IF condition.

The command MD creates with command extensions enabled as by default the entire directory tree. Therefore it is not necessary to create the date subdirectory explicitly before searching for *.avi and *.jpg files. That is good as it avoids creating empty date directories when there are no *.avi and *.jpg files in current directory.

As the *.avi and *.jpg files in current directory should be moved to DD-MM-YYYY\Token1_Token2 it is of course necessary to specify also the environment variable with todays date string on creating the directory and moving the file.

The error message output by MD if the directory exists (or when it fails to create the directory because of missing permissions) to handle STDERR is redirected with 2>nul to device NUL to suppress it.

The MOVE command is used with option /Y to move the file to target folder even if the current file exists already in target folder.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

for /?

if /?

md /?

move /?

set /?

Read also the Microsoft article about Using Command Redirection Operators.

Body:
I created the following batch script to create a folder based on today's date and then group files into folders based on the file name.

For example the files

JIM_BRICKMAN_QPS.avi
JIM_BRICKMAN_Slice.avi
JIM_BRICKMAN_Slice.jpg

are moved to the folder BRICKMAN.

This works fine, however, attempts to modify the batch file to move the newly created folders into the newly created date folder fail or overwrite the folders when going through the loop.

for /F "tokens=1-4 delims=/" %%A in ('date /t') do (
    set DateDay=%%A
    set DateMonth=%%B
    set DateYear=%%C
)
set CurrentDate=%DateDay%-%DateMonth%-%DateYear%
if not exist "%CurrentDate%" md %CurrentDate%

for %%A in (*.avi *.jpg) do (
    for /f "tokens=1,* delims=_" %%D in ("%%~nA") do (
        md "%%D" 2>nul
        echo Moving file %%A to folder %%D
        move "%%A" "%%D" >nul
    )
)

echo Finished

Additionally, I can't seem to get the token to ignore the first delimiter so that the folder is titled JIM_BRICKMAN and not just BRICKMAN.

EDIT:

I rewrote the batch file after the suggestions in the comments:

set "CurrentDate=%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%"
if not exist "%CurrentDate%" md %CurrentDate%
for %%A in (*.avi *.jpg) do (
    for /f "tokens=1,2 delims=_" %%D_%%E in ("%%~nA") do (
        md "%%D_%%E" 2>nul
        move "%%A" "%%D_%%E" >nul
    )
)

But the script seems to bomb out. I tried to capture the error, but it closes despite me putting PAUSE in the script.

Body:
Double clicking on a batch file in development is no good idea because this results in starting

%SystemRoot%\System32\cmd.exe /c "batch file name with full path and extension"

As it can be read on running cmd /? from within a command prompt window, the option /C means close the command process and its console window immediately after execution of command, executable or script finished independent on the reason for ending the execution.

For debugging a batch file in development it is much better to

open a command prompt window,

change the current directory with command CD to directory of batch file and

run the batch file by typing its name and hitting key RETURN or ENTER.

For batch files which should work independent on which directory is the current directory, it is advisable to omit point 2 and run the batch file with entering its full path, file name and file extension enclosed in double quotes with current directory being not the directory of the batch file.

A batch file is executed from within a command prompt window with:

%SystemRoot%\System32\cmd.exe /K BatchFileNameAsTyped

The option /K means keep command process running which results in keeping also command prompt window opened after execution of command/executable/script which makes it possible to read error messages.

The keys UP ARROW and DOWN ARROW can be used to reload command lines once entered in command prompt window making it easy to run the batch file once again after making a modification in GUI text editor.

And with having @echo off removed from first line of batch file, or changed to @echo ON, or commented out this line with command REM or with :: (invalid label) at beginning, it is also possible to see which lines Windows command interpreter really executes after applying immediate environment variable expansion and where an error occurs in case of a syntax error.

Wrong on second batch code is the line:

for /f "tokens=1,2 delims=_" %%D_%%E in ("%%~nA") do (

Specified as loop variable must be always 1 character. Right would be:

for /f "tokens=1,2 delims=_" %%D in ("%%~nA") do (

The command echo %DATE% outputs on my computer with my account and my region settings today the date 01.04.2017.

The command echo %DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4% outputs 01-04-2017.

So this part of the script works.

Hint: A list of directories in format YYYY-MM-DD is better than in format DD-MM-YYYY. The list of directories with format YYYY-MM-DD sorted alphabetically as by default is automatically with this date format also sorted from oldest to newest. Date format DD-MM-YYYY results in a weird list of the directories on being sorted alphabetically as by default.

A batch file for this task could be:

@echo off
set "CurrentDate=%DATE:~-10,2%-%DATE:~-7,2%-%DATE:~-4%"
for %%A in (*.avi *.jpg) do (
    for /F "tokens=1,2 delims=_" %%D in ("%%~nA") do (
        if not "%%E" == "" (
            md "%CurrentDate%\%%D_%%E" 2>nul
            move /Y "%%A" "%CurrentDate%\%%D_%%E\"
        ) else (
            md "%CurrentDate%\%%D" 2>nul
            move /Y "%%A" "%CurrentDate%\%%D\"
        )
    )
)
set "CurrentDate="

How the inner loop works is most interesting for this task.

for /F and "%%~nA" means the command FOR should process just the file name of the *.avi or *.jpg file without file extension found by outer FOR loop.

delims=_ means the FOR command should split up the string into multiple parts (tokens) using underscore as delimiter. The first file name is JIM_BRICKMAN_QPS which would be split up to:

JIM assigned to loop variable D being specified in FOR command line,

BRICKMAN assigned to loop variable E which is the next character in ASCII table after D and

QPS assigned to loop variable F.

This string split feature is the reason why loop variables are interpreted case-sensitive while environment variables are interpreted not case-sensitive.

With tokens=1,2 is specified that just first and second string parts are of interest. So inner FOR can stop string splitting after having already determined the first two underscore delimited strings and having assigned them to the loop variables D and E.

FOR executes the command block if it could determine at least 1 string delimited by an underscore. So it is possible that loop variable D has a string value, but loop variable E is an empty string, for example if the file name does not contain any underscore. That is the reason for the IF condition.

The command MD creates with command extensions enabled as by default the entire directory tree. Therefore it is not necessary to create the date subdirectory explicitly before searching for *.avi and *.jpg files. That is good as it avoids creating empty date directories when there are no *.avi and *.jpg files in current directory.

As the *.avi and *.jpg files in current directory should be moved to DD-MM-YYYY\Token1_Token2 it is of course necessary to specify also the environment variable with todays date string on creating the directory and moving the file.

The error message output by MD if the directory exists (or when it fails to create the directory because of missing permissions) to handle STDERR is redirected with 2>nul to device NUL to suppress it.

The MOVE command is used with option /Y to move the file to target folder even if the current file exists already in target folder.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

for /?

if /?

md /?

move /?

set /?

Read also the Microsoft article about Using Command Redirection Operators.


问:
Fork the pipeline of aggregation
I have several similar aggregation operations at the same time, for example

```<code>db.cases.aggregate([
   {$match : query},
   {$unwind : "factors"},

   //operation 1 of the above result
   // ...
])

db.cases.aggregate([
   {$match : query},
   {$unwind : "factors"},

   //operation 2 of the above result
   // ...
])
</code>```

The first two stages of aggregation( $match, $unwind ) are the same, and I think it would be a waste to repeat the duplicate stages. So I am asking if there exists a way to forking the pipeline, so that it can share the result from the first two stages, as follows,

```<code>db.cases.aggregation([
   {$match : query},
   {$unwind : "factors"},
   forks : [
      {... operation 1},
      {... operation 2}
   ]
])
</code>```

答:
This was a while ago but just so you know it was implemented:

https://docs.mongodb.com/manual/reference/operator/aggregation/facet/

```<code>{ $facet:
   {
      <outputField1>: [ <stage1>, <stage2>, ... ],
      <outputField2>: [ <stage1>, <stage2>, ... ],
      ...

   }
}
</code>```

Title: Fork the pipeline of aggregation

Body:
I have several similar aggregation operations at the same time, for example

db.cases.aggregate([
   {$match : query},
   {$unwind : "factors"},

   //operation 1 of the above result
   // ...
])

db.cases.aggregate([
   {$match : query},
   {$unwind : "factors"},

   //operation 2 of the above result
   // ...
])

The first two stages of aggregation( $match, $unwind ) are the same, and I think it would be a waste to repeat the duplicate stages. So I am asking if there exists a way to forking the pipeline, so that it can share the result from the first two stages, as follows,

db.cases.aggregation([
   {$match : query},
   {$unwind : "factors"},
   forks : [
      {... operation 1},
      {... operation 2}
   ]
])

Body:
This was a while ago but just so you know it was implemented:

https://docs.mongodb.com/manual/reference/operator/aggregation/facet/

{ $facet:
   {
      <outputField1>: [ <stage1>, <stage2>, ... ],
      <outputField2>: [ <stage1>, <stage2>, ... ],
      ...

   }
}


问:
Archived Tasks in jBPM 6.4
I would like to know if there is a REST API call to list an archived set of Tasks in jBPM 6.x

As far as I know, there are just two query calls available:

```<code>[GET] /query/runtime/task
[GET] /query/task
</code>```

Neither of those can retrieve all archived tasks. I saw in the BPM Suite dashboard that all tasks can be listed somehow. I'm wondering if there is an API available for that operation.

答:
To list completed tasks try with below REST API:

[GET] /query/runtime/task?taskstatus=Completed

Title: Archived Tasks in jBPM 6.4

Body:
I would like to know if there is a REST API call to list an archived set of Tasks in jBPM 6.x

As far as I know, there are just two query calls available:

[GET] /query/runtime/task
[GET] /query/task

Neither of those can retrieve all archived tasks. I saw in the BPM Suite dashboard that all tasks can be listed somehow. I'm wondering if there is an API available for that operation.


问:
JUnit tests in eclipse failing when run together
I have a set of 44 JUnit tests that I run using Eclipse (I got those tests from someone else - I am new to JUnit tests). When I run them all together, 24 of them fail. However, if I then run the failing ones individually, some of them do pass after all. The tests do take a little time - one of the failing ones for example takes about one or two minutes to complete, while just letting all of them run finishes in just a few seconds.

I am starting multiple tests by right-clicking on the folder they are in and selecting "Run As -> JUnit Test". I am using JUnit 3. Am I doing something wrong in starting them / is there some kind of option I am missing?

答:
To expand on Gary's answer, when right-clicking and doing the Run As -> JUnit, you can't guarantee the order in which the tests are run, which could also help to corrupt a shared resource.

I would start by looking at your setup() and teardown() methods to ensure that shared resources are being reset properly. Also, since you inherited these tests, you may want to look at whether any of the tests are dependent upon one another. While this is a bad practice and should be changed, you could perhaps create a test suite() to ensure the order in which they're run (at least until you can re-factor and decouple the tests).


问:
How can I pre-increment at an empty array index without throwing a notice?
I'd like to do this:

$matched_tags[$tag]++

As a simple way of keeping track of how many times a given $tag is found during a loop.

This appears to be throwing a NOTICE the first time any new $tag is encountered, because the index is undefined. PHP kindly autovivifies it, sets it to 0 and post-increments it, but throws the NOTICE anyway.

Now I like to develop with Notices on as a best practice, so I don't want to suppress them. But to me what I'm doing isn't notice-worthy.

Do I really have to:

```<code>if ( ! isset ( $matched_tags[$tag] ) ) $matched_tags[$tag] = 0;
$matched_tags[$tag]++;
</code>```

Oh that is so painful. Please tell me there's a more elegant way, or I swear I'll switch to Perl so help me.

答:
I found another way to increment undefined array items. It looks like a kind of a hack, but it's obvious and still short.

Suppose you need to increment a leaf value of the few nested arrays. Using isset() it may be too annoying:

```<code><?php
error_reporting(E_ALL);

$array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'] =
    isset($array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'])
    ? ($array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'] + 1)
    : 1;
</code>```

Name of an array item repeated there three times, rippling in your eyes.

Try to use & operator to get an array item reference. Acting with a reference not causing any notices or errors:

```<code><?php
error_reporting(E_ALL);

$item = &$array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'];
// $item is null here
$item++;
unset($item);

echo $array['root']['node'][10]['node'][20]['leaf'][30]['totalCount']; // 1
</code>```

It works just fine, but you can also avoid null to 0 casting:

```<code><?php
error_reporting(E_ALL);

$item = &$array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'];
// $item is null here
$item = isset($item) ? ($item + 1) : 1;
unset($item);

echo $array['root']['node'][10]['node'][20]['leaf'][30]['totalCount']; // 1
</code>```

If you're already on PHP7, use coalesce operator instead of isset():

```<code>$item = ($item ?? 0) + 1;
</code>```

Body:
I'd like to do this:

$matched_tags[$tag]++

As a simple way of keeping track of how many times a given $tag is found during a loop.

This appears to be throwing a NOTICE the first time any new $tag is encountered, because the index is undefined. PHP kindly autovivifies it, sets it to 0 and post-increments it, but throws the NOTICE anyway.

Now I like to develop with Notices on as a best practice, so I don't want to suppress them. But to me what I'm doing isn't notice-worthy.

Do I really have to:

if ( ! isset ( $matched_tags[$tag] ) ) $matched_tags[$tag] = 0;
$matched_tags[$tag]++;

Oh that is so painful. Please tell me there's a more elegant way, or I swear I'll switch to Perl so help me.

Body:
I found another way to increment undefined array items. It looks like a kind of a hack, but it's obvious and still short.

Suppose you need to increment a leaf value of the few nested arrays. Using isset() it may be too annoying:

<?php
error_reporting(E_ALL);

$array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'] =
    isset($array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'])
    ? ($array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'] + 1)
    : 1;

Name of an array item repeated there three times, rippling in your eyes.

Try to use & operator to get an array item reference. Acting with a reference not causing any notices or errors:

<?php
error_reporting(E_ALL);

$item = &$array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'];
// $item is null here
$item++;
unset($item);

echo $array['root']['node'][10]['node'][20]['leaf'][30]['totalCount']; // 1

It works just fine, but you can also avoid null to 0 casting:

<?php
error_reporting(E_ALL);

$item = &$array['root']['node'][10]['node'][20]['leaf'][30]['totalCount'];
// $item is null here
$item = isset($item) ? ($item + 1) : 1;
unset($item);

echo $array['root']['node'][10]['node'][20]['leaf'][30]['totalCount']; // 1

If you're already on PHP7, use coalesce operator instead of isset():

$item = ($item ?? 0) + 1;


问:
Can you use a concept similar to keyword args for python in Java to minimize the number of accessor methods?
I recently learn that in Python 3, to minimize the number of accessor methods for a class, you can use a dictionaries to essentially just have one set of accessor methods as follows:

```<code>def __init__(self, **kwargs):
    self.properties = kwargs

def get_properties(self):
    return self.properties

def get_property(self, key):
    return self.properties.get(key, None)
</code>```

This seems really useful and I want to apply something similar in Java. I have been working on applications that may have multiple attributes, and creating and keeping track of all the accessor methods can be a pain. Is there a similar strategy that I could use for Java?

答: Im not sure if this is helpful to you, but Ill try to answer anyway. I'd first make a class Variable. Then I'd make a class Dictionary with one lists:Variables. Then I'd make the function take a Dictionary as argument.</p>

Body:
I recently learn that in Python 3, to minimize the number of accessor methods for a class, you can use a dictionaries to essentially just have one set of accessor methods as follows:

def __init__(self, **kwargs):
    self.properties = kwargs

def get_properties(self):
    return self.properties

def get_property(self, key):
    return self.properties.get(key, None)

This seems really useful and I want to apply something similar in Java. I have been working on applications that may have multiple attributes, and creating and keeping track of all the accessor methods can be a pain. Is there a similar strategy that I could use for Java?


问:
Cannot see "font" resource type in Android studio
I was going through the new Android O features, and one of the new thing is now app can add fonts directly into res folder. As per the android documentation for working with fonts, one of the 1st step is to create a new resource type named "font" using Right-click the res folder and go to New > Android resource directory.

But I could not see "font" option available for resource type in the drop down in android studio.

Below is the image attached.

I am not able to see "font" option in the drop down, and hence I am unable to create font android resource directory.

My Android studio details:

Android Studio 2.3
Build #AI-162.3764568, built on February 24, 2017
JRE: 1.8.0_112-release-b06 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

答:
As said by Mike in comments, currently Android Studio 2.4 includes support for all the new developer features available with Android O.

I used Android Studio 2.4 Preview from Canary Channel, & I could see the option for "font" when choosing the Android resource directory.

Below is the image for the same.


问:
Error in python Crawler
I am trying to use a python scawler script to get the address information from baidu map. The following is the code:

```<code># -*- coding: utf-8 -*-
import requests
import re
import csv
import time
def BusinessFromBaiduDitu(citycode = '287',key_word='筛网',pageno=0):
    parameter = {
    "newmap": "1",
    "reqflag": "pcmap",
    "biz": "1",
    "from": "webmap",
    "da_par": "direct",
    "pcevaname": "pc4.1",
    "qt": "con",
    "c": citycode,        # 城市代码
    "wd": key_word,       # 搜索关键词
    "wd2": "",
    "pn": pageno,         # 页数
    "nn": pageno * 10,
    "db": "0",
    "sug": "0",
    "addr": "0",
    "da_src": "pcmappg.poi.page",
    "on_gel": "1",
    "src": "7",
    "gr": "3",
    "l": "12",
    "tn": "B_NORMAL_MAP",
        # "u_loc": "12621219.536556,2630747.285024",
    "ie": "utf-8",
    # "b": "(11845157.18,3047692.2;11922085.18,3073932.2)",  #这个应该是地理位置坐标，可以忽略
    "t": "1468896652886"}

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36(KHTML, like Gecko) Chrome/56.0.2924.87Safari/537.36'}
url = 'http://map.baidu.com/'
htm = requests.get(url, params=parameter, headers=headers)
htm = htm.text.encode('latin-1').decode('unicode_escape')  # 转码
pattern = r'(?<=\baddress_norm":"\[).+?(?="ty":)'
htm = re.findall(pattern, htm)  # 按段落匹配

for r in htm:
    pattern = r'(?<=\b"\},"name":").+?(?=")'
    name = re.findall(pattern, r)
    #if not name:
    pattern = r'(?<=\b,"name":").+?(?=")'
    name = re.findall(pattern, r)
    print(name[0])  # 名称

    pattern = r'.+?(?=")'
    adr = re.findall(pattern, r)
    pattern = r'\(.+?\['
    address = re.sub(pattern, ' ', adr[0])
    pattern = r'\(.+?\]'
    address = re.sub(pattern, ' ', address)
    print(address)  # 地址

    pattern = r'(?<="phone":").+?(?=")'
    phone = re.findall(pattern, r)
    try:
        if phone[0] and '",' != phone[0]:
            phone_list = phone[0].split(sep=',')
        for number in phone_list:
            if re.match('1', number):
                print(citycode+name[0]+','+address+','+number)
                writer.writerow((name[0], address, number))
except:
    continue
print(citycode + '  ' + key_word + '  ' + str(pageno))
</code>```

when running this script, I receives the following error:

```<code>Traceback (most recent call last): File "E:\map.py", line 41, in <module> htm = requests.get(url, params=parameter, headers=headers) NameError: name 'parameter' is not defined
</code>```

As I see it the 'parameter' is define in the def module. why does this error occur?
I am new to python and I'll appreciate any help.

Best regards.

Yeping Sun

答:
Parameter is undefined because of a couple reasons. You are defining the function BusinessFromBaiduDitu, but you are not calling it or return data from the function.

Here's an example to return data from a function:

```<code>def test():
     a = {"Test1":"1"}
     return a

outside_a = test()
print(outside_a)
</code>```

Title: Error in python Crawler

Body:
I am trying to use a python scawler script to get the address information from baidu map. The following is the code:

# -*- coding: utf-8 -*-
import requests
import re
import csv
import time
def BusinessFromBaiduDitu(citycode = '287',key_word='筛网',pageno=0):
    parameter = {
    "newmap": "1",
    "reqflag": "pcmap",
    "biz": "1",
    "from": "webmap",
    "da_par": "direct",
    "pcevaname": "pc4.1",
    "qt": "con",
    "c": citycode,        # 城市代码
    "wd": key_word,       # 搜索关键词
    "wd2": "",
    "pn": pageno,         # 页数
    "nn": pageno * 10,
    "db": "0",
    "sug": "0",
    "addr": "0",
    "da_src": "pcmappg.poi.page",
    "on_gel": "1",
    "src": "7",
    "gr": "3",
    "l": "12",
    "tn": "B_NORMAL_MAP",
        # "u_loc": "12621219.536556,2630747.285024",
    "ie": "utf-8",
    # "b": "(11845157.18,3047692.2;11922085.18,3073932.2)",  #这个应该是地理位置坐标，可以忽略
    "t": "1468896652886"}

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36(KHTML, like Gecko) Chrome/56.0.2924.87Safari/537.36'}
url = 'http://map.baidu.com/'
htm = requests.get(url, params=parameter, headers=headers)
htm = htm.text.encode('latin-1').decode('unicode_escape')  # 转码
pattern = r'(?<=\baddress_norm":"\[).+?(?="ty":)'
htm = re.findall(pattern, htm)  # 按段落匹配

for r in htm:
    pattern = r'(?<=\b"\},"name":").+?(?=")'
    name = re.findall(pattern, r)
    #if not name:
    pattern = r'(?<=\b,"name":").+?(?=")'
    name = re.findall(pattern, r)
    print(name[0])  # 名称

    pattern = r'.+?(?=")'
    adr = re.findall(pattern, r)
    pattern = r'\(.+?\['
    address = re.sub(pattern, ' ', adr[0])
    pattern = r'\(.+?\]'
    address = re.sub(pattern, ' ', address)
    print(address)  # 地址

    pattern = r'(?<="phone":").+?(?=")'
    phone = re.findall(pattern, r)
    try:
        if phone[0] and '",' != phone[0]:
            phone_list = phone[0].split(sep=',')
        for number in phone_list:
            if re.match('1', number):
                print(citycode+name[0]+','+address+','+number)
                writer.writerow((name[0], address, number))
except:
    continue
print(citycode + '  ' + key_word + '  ' + str(pageno))

when running this script, I receives the following error:

Traceback (most recent call last): File "E:\map.py", line 41, in <module> htm = requests.get(url, params=parameter, headers=headers) NameError: name 'parameter' is not defined

As I see it the 'parameter' is define in the def module. why does this error occur?
I am new to python and I'll appreciate any help.

Best regards.

Yeping Sun

Body:
Parameter is undefined because of a couple reasons. You are defining the function BusinessFromBaiduDitu, but you are not calling it or return data from the function.

Here's an example to return data from a function:

def test():
     a = {"Test1":"1"}
     return a

outside_a = test()
print(outside_a)