问:
Extracting values from listbox
I created a UserForm in VBA with 2 ListBoxes.

What I want to do is extract values from the right ListBox (and keep them in temp) and delete every row in another sheet which contains these names.

Writing a code to delete rows is not an issues. I have no clue how to use these selected items in another VBA module. Any ideas?

答:
Update to process rows in reverse (since delete will shift rows up). See comments at top of code. </p>

```<code>Option Explicit

Sub cmdDelete_Click()
    ' This subroutine will allow a user to delete selected rows from an Excel sheet.
    ' In a multi-select listbox on a user form, select the items that you want to delete.
    ' Click the 'Delete' button on the form and the following will occur:
    ' a. Each selected item will be delimited and concatenated into one string.
    '    (The reason for doing that is to avoid spinning thru each listbox item for
    '    every row)
    ' b. Each row in the selected range will have it's value checked within the string.
    ' c. If found. the row will be deleted.
    '
    ' Notes: - Need to loop thru the rows from bottom upwards to top because
    '          as each row is deleted, it will shift remainder upwards.
    '        - You don't really need the delimiters if values can never be confused

    Dim sList       As String
    Dim lItem       As Long
    Dim r           As Range
    Dim ws          As Worksheet
    Dim lFirstRow   As Long
    Dim lLastRow    As Long
    Dim lRow        As Long

    For lItem = 0 To lstCountries.ListCount - 1
        If lstCountries.Selected(lItem) = True Then
            sList = sList & "<" & Me.lstCountries.column(0, lItem) & ">"     ' Adjust to the column YOU want (relative to zero)
        End If
    Next
    Debug.Print "Full List to Delete: " & sList

    Set ws = ThisWorkbook.Sheets("Sheet1")      ' Change to YOUR worksheet name
    ' Find the last used row
    lLastRow = Cells.Find(What:="*", after:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    lFirstRow = 2                               ' Set to YOUR first used row

    ' Spin thru all rows in the range of rows
    ' Go in reverse order since the Delete will shift the rows UP
    For lRow = lLastRow To lFirstRow Step -1
        ' See if row value exists in the selections made in the listbox
        If InStr(1, sList, "<" & ws.Cells(lRow, 1) & ">") > 0 Then
            ws.Rows(lRow).Delete            ' Delete row if a match is found
        End If
    Next lRow
End Sub
</code>```

Title: Extracting values from listbox

Body:
Update to process rows in reverse (since delete will shift rows up). See comments at top of code.

Option Explicit

Sub cmdDelete_Click()
    ' This subroutine will allow a user to delete selected rows from an Excel sheet.
    ' In a multi-select listbox on a user form, select the items that you want to delete.
    ' Click the 'Delete' button on the form and the following will occur:
    ' a. Each selected item will be delimited and concatenated into one string.
    '    (The reason for doing that is to avoid spinning thru each listbox item for
    '    every row)
    ' b. Each row in the selected range will have it's value checked within the string.
    ' c. If found. the row will be deleted.
    '
    ' Notes: - Need to loop thru the rows from bottom upwards to top because
    '          as each row is deleted, it will shift remainder upwards.
    '        - You don't really need the delimiters if values can never be confused

    Dim sList       As String
    Dim lItem       As Long
    Dim r           As Range
    Dim ws          As Worksheet
    Dim lFirstRow   As Long
    Dim lLastRow    As Long
    Dim lRow        As Long

    For lItem = 0 To lstCountries.ListCount - 1
        If lstCountries.Selected(lItem) = True Then
            sList = sList & "<" & Me.lstCountries.column(0, lItem) & ">"     ' Adjust to the column YOU want (relative to zero)
        End If
    Next
    Debug.Print "Full List to Delete: " & sList

    Set ws = ThisWorkbook.Sheets("Sheet1")      ' Change to YOUR worksheet name
    ' Find the last used row
    lLastRow = Cells.Find(What:="*", after:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    lFirstRow = 2                               ' Set to YOUR first used row

    ' Spin thru all rows in the range of rows
    ' Go in reverse order since the Delete will shift the rows UP
    For lRow = lLastRow To lFirstRow Step -1
        ' See if row value exists in the selections made in the listbox
        If InStr(1, sList, "<" & ws.Cells(lRow, 1) & ">") > 0 Then
            ws.Rows(lRow).Delete            ' Delete row if a match is found
        End If
    Next lRow
End Sub


来源: stackexchange

问:
C# lock issues when writing to log
I have a class that programmatically creates a log using the Nlog framework. I have several processes running and creating their logs at the same time. I added a lock to the constructor of the class, as before the two threads were attempting to create a file at the same time which resulted in some annoying bugs (like only creating one log).

This seems to have solved that problem. However now i have the same issue with writing to the log, and using a lock has not helped. Here is the class.

```<code>public class CwiLogger
    {
        private Logger _log;
        private static Object createLogLock = new Object();
        private static Object writeLogLock = new Object();
        public CwiLogger(string logPath, string logName, string className)
        {
            lock (createLogLock)
            {
                var config = new LoggingConfiguration();
                var fileTarget = new FileTarget();
                config.AddTarget("file", fileTarget);
                fileTarget.FileName = Path.Combine(logPath, logName);
                fileTarget.Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}";
                var rule = new LoggingRule("*", LogLevel.Debug, fileTarget);
                config.LoggingRules.Add(rule);

                LogManager.Configuration = config;

                this._log = LogManager.GetLogger(className);
            }
        }

        public void AddToLog(string logText, LogLevel level = null)
        {
            lock (writeLogLock)
            {
                level = level ?? LogLevel.Info;
                this._log.Log(level, logText + "\n");
            }
        }
    }
</code>```

In my client code i run two threads each running a process that looks like this:

```<code>var log = new CwiLogger(@"C:\Users\jma\Documents\ProgrammingJunk\logTest", "Log2.txt", "Log2");
for (int i = 0; i < 100; i++)
{
    log.AddToLog("Log2 " + i);
}
</code>```

only i use log1 for one and log2 for the other.

in my output. One of the 2 logs always sucessfully counts to 99, while the other gets 4-5 in and then has no other output.

答:
This is because the lock() syntax compiles to Monitor.Enter and Monitor.Leave - Monitor.Enter will put the current thread to sleep if it cannot lock the object, the thread holding the lock and will then awake all waiting threads when it calls Monitor.Leave.

Your problem is that your second thread has to go through the additional time of waking up before it can attempt to lock the object, by which time the thread that just released the lock has already locked it again.

If you expect your routine to lock only for a very short time (too short to want to sleep waiting threads) use a SpinLock instead. This class gets each thread to keep attempting the lock in a loop until it succeeds rather than sleeping. It means it uses more CPU (and thus more battery power on a laptop), which is why the code you lock must run for very small amounts of time.

ContentLicense: CC BY-SA 3.0

Title: C# lock issues when writing to log

Body:
I have a class that programmatically creates a log using the Nlog framework. I have several processes running and creating their logs at the same time. I added a lock to the constructor of the class, as before the two threads were attempting to create a file at the same time which resulted in some annoying bugs (like only creating one log).

This seems to have solved that problem. However now i have the same issue with writing to the log, and using a lock has not helped. Here is the class.

public class CwiLogger
    {
        private Logger _log;
        private static Object createLogLock = new Object();
        private static Object writeLogLock = new Object();
        public CwiLogger(string logPath, string logName, string className)
        {
            lock (createLogLock)
            {
                var config = new LoggingConfiguration();
                var fileTarget = new FileTarget();
                config.AddTarget("file", fileTarget);
                fileTarget.FileName = Path.Combine(logPath, logName);
                fileTarget.Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}";
                var rule = new LoggingRule("*", LogLevel.Debug, fileTarget);
                config.LoggingRules.Add(rule);

                LogManager.Configuration = config;

                this._log = LogManager.GetLogger(className);
            }
        }

        public void AddToLog(string logText, LogLevel level = null)
        {
            lock (writeLogLock)
            {
                level = level ?? LogLevel.Info;
                this._log.Log(level, logText + "\n");
            }
        }
    }

In my client code i run two threads each running a process that looks like this:

var log = new CwiLogger(@"C:\Users\jma\Documents\ProgrammingJunk\logTest", "Log2.txt", "Log2");
for (int i = 0; i < 100; i++)
{
    log.AddToLog("Log2 " + i);
}

only i use log1 for one and log2 for the other.

in my output. One of the 2 logs always sucessfully counts to 99, while the other gets 4-5 in and then has no other output.


问:
Split string at every Nth occurrence of character
I need to split a string like the following after every fourth pipe -

Input -

userid456|userid457|userid458|userid459|userid460|userid461|userid462|userid463|userid464|userid465|userid466|userid467|userid468|userid469|userid470|userid471|userid472|userid473|userid474|userid475|userid476|userid477|userid478|userid479|userid480|userid481|userid482|userid483

Output -

```<code>userid456|userid457|userid458|userid459

userid460|userid461|userid462|userid463

userid464|userid465|userid466|userid467

userid468|userid469|userid470|userid471
</code>```

etc.

Was trying to figure out if there is an easy way using regexp and String.split()

答:
Instead of using split you can use a match using this regex:

```<code>(?:[^|]+\|){3}[^|]+
</code>```

RegEx Demo

Java Code:

```<code>final String regex = "(?:[^|]*\\|){3}[^|]*";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Match: " + matcher.group(0));
}
</code>```

Body:
I need to split a string like the following after every fourth pipe -

Input -

userid456|userid457|userid458|userid459|userid460|userid461|userid462|userid463|userid464|userid465|userid466|userid467|userid468|userid469|userid470|userid471|userid472|userid473|userid474|userid475|userid476|userid477|userid478|userid479|userid480|userid481|userid482|userid483

Output -

userid456|userid457|userid458|userid459

userid460|userid461|userid462|userid463

userid464|userid465|userid466|userid467

userid468|userid469|userid470|userid471

etc.

Was trying to figure out if there is an easy way using regexp and String.split()

Body:
Instead of using split you can use a match using this regex:

(?:[^|]+\|){3}[^|]+

RegEx Demo

Java Code:

final String regex = "(?:[^|]*\\|){3}[^|]*";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Match: " + matcher.group(0));
}


问:
How to override physical marker in vuforia AR Camera in runtime?
How can I override the physical marker in unity to just make the physical marker invisible in camera while detecting any object.

Like in this video:
https://m.youtube.com/watch?v=R_F1LvK5gCk
And many other videos.

答:
This maybe isn't the correct answer but, I'll put my ideas here because sadly it doesn't fit in the comment section.

I just watch the video and some of the reels they show as his works.

First, yes, in deed they make the marker a sort of invisible marker, but if you look closely, like a 0.25 speed and pushing space bar very fast to look it in slowmo, you can see a kind of "artifact" in between the girl's fingers that makes me think there's no invisible marker but a texture that are covering the marker. Maybe a cylinder that gets his texture from the video camera input.

Now, how I do that?
There are several ways to get the pixels from the webcamera, even Unity has one function. The trouble is, I dont want all the pixels but a little tiny part of the camera render, specifically the one's around my marker.

In my experience, and in his examples, they are using OpenCV, another unity plugin, so they can track anything, from faces, hands, or markers, so I can't be quite sure they are using Vuforia alone or in combination.

My idea is, with OpenCV you can catch your marker and his contour, then ask for the pixels outside the contour of your marker, those pixels will be the skin tone of the person and latter apply them as a texture over some plane or 3d model that can cover your marker. You can have the pixels at right side and left side of the marker and use a average function betwen them so it could look nice or if you like the adventures you can try to use some kind of digital images processing method to get bether results.

I'm not sure if you can have the pixels arround a marker just using just Vuforia. Honestly I've never try it before.

Well, that's my idea.
If you can get it better I'll like to hear about it.


问:
Flex Layout: can width be 100% of the *visible* area of a larger container
I've got the following situation, where I have an outer Vbox that is set at a fixed width, and then inside it there is a header made from an HBox and a content area (Canvas) that is much wider than the enclosing VBox (and therefore requires scrollbars on the outer VBox to see it all).

I would like to set the width of the header to fill the entire width of the outer container, but only the visible part, and to remain fixed so that when I scroll to view the content, the header doesn't move.

Can anyone tell me how I can acomplish this please

```<code>    ______________________________
   |  _________________________   |
   | |_________________________|  |
   |                     |
   |  ____________________________|_ _ _ _ _
   | |                            |         |
   | |                            |         |
   | |                            |         |
   | |                            |         |
   |  ---------------------------------------
   |                              |
   |______________________________|
   |<|__________________________|>|
</code>```

答:
If you need the header fixed above VBox, just not add it in. Place it above (create wrapper Canvas for VBox and header). Instead of header place UIComponent with corresponding height to take place of header.

BTW, +1 for patience with pseudographics :)

ContentLicense: CC BY-SA 2.5

Body:
I've got the following situation, where I have an outer Vbox that is set at a fixed width, and then inside it there is a header made from an HBox and a content area (Canvas) that is much wider than the enclosing VBox (and therefore requires scrollbars on the outer VBox to see it all).

I would like to set the width of the header to fill the entire width of the outer container, but only the visible part, and to remain fixed so that when I scroll to view the content, the header doesn't move.

Can anyone tell me how I can acomplish this please

    ______________________________
   |  _________________________   |
   | |_________________________|  |
   |                     |
   |  ____________________________|_ _ _ _ _
   | |                            |         |
   | |                            |         |
   | |                            |         |
   | |                            |         |
   |  ---------------------------------------
   |                              |
   |______________________________|
   |<|__________________________|>|


问:
Assign CSS To A
 Element
I am wanting to add CSS to a DIV element so I can align it to the right and have a form directly to the left of it. I am working on making a hacked version of 2048. My HTML code is:

```<code>    <div id="completetwentyfourtyeightgame" align="right">
        <div class="container">
            <div class="heading">
                <div class="scores-container">
                    <div class="score-container">0</div>
                    <div class="best-container">0</div>
                </div>
                <div class="above-game">
                    <a class="restart-button">New Game</a>
                </div>
            </div>
            <div class="game-container">
                <div class="game-message">
                    <p></p>
                    <div class="lower">
                        <a class="keep-playing-button">Keep going</a>
                        <a class="retry-button">Try again</a>
                    </div>
                </div>
                <div class="grid-container">
                    <div class="grid-row">
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                    </div>
                    <div class="grid-row">
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                    </div>
                    <div class="grid-row">
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                    </div>
                    <div class="grid-row">
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                    </div>
                </div>
                <div class="tile-container"></div>
            </div>
        </div>
    </div>

        <div align="left">
        <form id="inputs">
            <table border="1">
                <tr>
                    <th>Tile Value 1</th>
                </tr>
                <tr>
                    <th>
                        <input type="text" id="tilevalueone" value="2">
                    </th>
                </tr>
                <tr>
                    <th>Tile Value 2</th>
                </tr>
                <tr>
                    <th>
                        <input type="text" id="tilevaluetwo" value="4">
                    </th>
                </tr>
                <tr>
                    <th>Starting Score</th>
                </tr>
                <tr>
                    <th>
                        <input type="text" id="score" value="0">
                    </th>
                </tr>
                <tr>
                    <th>Tile Value To Win</th>
                </tr>
                <tr>
                    <th>
                        <input type="text" id="winpoints" value="2048">
                    </th>
                </tr>
            </table>
        </form>
    </div>
</code>```

My css is:

```<code>.completetwentyfourtyeightgame{
position: absolute;
right: 0px;
}
</code>```

What is wrong with the code? Is it in my HTML or in my CSS? Here is a screenshot of what the code is doing:

Instead of the table being directly on the left and the game on the right, the table stays below the game.
After changing the . to a # in the css, this happens

I am not wanting the game to be on the edge if the website and the table to be right next to the left border of the game. Also, is there a way to make javascript reload the game to apply the values without reloading the page itself?

答:
```<code>#completetwentyfourtyeightgame{
  float: right;
}
</code>```

# = id selector
. = class selector

i think float is a better usage here than position: absolute. you typically want to stay away from absolute positioning if you can

#completetwentyfourtyeightgame{
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="completetwentyfourtyeightgame" align="right">
    <div class="container">
        <div class="heading">
            <div class="scores-container">
                <div class="score-container">0</div>
                <div class="best-container">0</div>
            </div>
            <div class="above-game">
                New Game
            </div>
        </div>
        <div class="game-container">
            <div class="game-message">
                <p></p>
                <div class="lower">
                    Keep going
                    Try again
                </div>
            </div>
            <div class="grid-container">
                <div class="grid-row">
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                </div>
                <div class="grid-row">
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                </div>
                <div class="grid-row">
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                </div>
                <div class="grid-row">
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                </div>
            </div>
            <div class="tile-container"></div>
        </div>
    </div>
</div>

    <div align="left">
    <form id="inputs">
        <table border="1">
            <tr>
                <th>Tile Value 1</th>
            </tr>
            <tr>
                <th>
                    <input type="text" id="tilevalueone" value="2">
                </th>
            </tr>
            <tr>
                <th>Tile Value 2</th>
            </tr>
            <tr>
                <th>
                    <input type="text" id="tilevaluetwo" value="4">
                </th>
            </tr>
            <tr>
                <th>Starting Score</th>
            </tr>
            <tr>
                <th>
                    <input type="text" id="score" value="0">
                </th>
            </tr>
            <tr>
                <th>Tile Value To Win</th>
            </tr>
            <tr>
                <th>
                    <input type="text" id="winpoints" value="2048">
                </th>
            </tr>
        </table>
    </form>
</div></code>```

Title: Assign CSS To A <div> Element

Body:
I am wanting to add CSS to a DIV element so I can align it to the right and have a form directly to the left of it. I am working on making a hacked version of 2048. My HTML code is:

0

0

                    New Game

                        Keep going
                        Try again

        <form id="inputs">

                    Tile Value 1

                        <input type="text" id="tilevalueone" value="2">

                    Tile Value 2

                        <input type="text" id="tilevaluetwo" value="4">

                    Starting Score

                        <input type="text" id="score" value="0">

                    Tile Value To Win

                        <input type="text" id="winpoints" value="2048">

        </form>

My css is:

.completetwentyfourtyeightgame{
position: absolute;
right: 0px;
}

What is wrong with the code? Is it in my HTML or in my CSS? Here is a screenshot of what the code is doing:

Instead of the table being directly on the left and the game on the right, the table stays below the game.
After changing the . to a # in the css, this happens

I am not wanting the game to be on the edge if the website and the table to be right next to the left border of the game. Also, is there a way to make javascript reload the game to apply the values without reloading the page itself?

Body:
#completetwentyfourtyeightgame{
  float: right;
}

# = id selector
. = class selector

i think float is a better usage here than position: absolute. you typically want to stay away from absolute positioning if you can

#completetwentyfourtyeightgame{
  float: right;
}

<div id="completetwentyfourtyeightgame" align="right">
    <div class="container">
        <div class="heading">
            <div class="scores-container">
                <div class="score-container">0</div>
                <div class="best-container">0</div>
            </div>
            <div class="above-game">
                <a class="restart-button">New Game</a>
            </div>
        </div>
        <div class="game-container">
            <div class="game-message">
                <p></p>
                <div class="lower">
                    <a class="keep-playing-button">Keep going</a>
                    <a class="retry-button">Try again</a>
                </div>
            </div>
            <div class="grid-container">
                <div class="grid-row">
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                </div>
                <div class="grid-row">
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                </div>
                <div class="grid-row">
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                </div>
                <div class="grid-row">
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                    <div class="grid-cell"></div>
                </div>
            </div>
            <div class="tile-container"></div>
        </div>
    </div>
</div>

    <div align="left">
    <form id="inputs">
        <table border="1">
            <tr>
                <th>Tile Value 1</th>
            </tr>
            <tr>
                <th>
                    <input type="text" id="tilevalueone" value="2">
                </th>
            </tr>
            <tr>
                <th>Tile Value 2</th>
            </tr>
            <tr>
                <th>
                    <input type="text" id="tilevaluetwo" value="4">
                </th>
            </tr>
            <tr>
                <th>Starting Score</th>
            </tr>
            <tr>
                <th>
                    <input type="text" id="score" value="0">
                </th>
            </tr>
            <tr>
                <th>Tile Value To Win</th>
            </tr>
            <tr>
                <th>
                    <input type="text" id="winpoints" value="2048">
                </th>
            </tr>
        </table>
    </form>
</div>


问:
How to have for loop that iterates through indexes as in objective-C (Swift)?
I am developing a Google Maps app and I have the following code:

```<code>func drawPolygon(){
var cord: Array<CLLocationCoordinate2D> = []
let path = GMSMutablePath()
// get path for polygon
for marker in markersArray {
let lat = coord.insert(marker.componentsSeparatedByString(",")[i] as NSString).doubleValue, atIndex:[i][0]
let lng = coord.insert(marker.componentsSeparatedByString(",")[i+1] as NSString).doubleValue, atIndex:[i][1]
path.addCoordinate(CLLocationCoordinate2DMake(coord[i][0]))
path.addCoordinate(CLLocationCoordinate2DMake(coord[i][1]))
}
</code>```

As you can see I would like to increment the index by one every time so all coordinates get inserted. How do I achieve this?

答:
There is a build in mechanism for that.</p>

```<code>func drawPolygon(){
var cord: Array<CLLocationCoordinate2D> = []
let path = GMSMutablePath()
// get path for polygon
for (marker, i) in markersArray.enumerated() {
let lat = coord.insert(marker.componentsSeparatedByString(",")[i] as NSString).doubleValue, atIndex:[i][0]
let lng = coord.insert(marker.componentsSeparatedByString(",")[i+1] as NSString).doubleValue, atIndex:[i][1]
path.addCoordinate(CLLocationCoordinate2DMake(coord[i][0]))
path.addCoordinate(CLLocationCoordinate2DMake(coord[i][1]))
}
</code>```

Body:
I am developing a Google Maps app and I have the following code:

func drawPolygon(){
var cord: Array<CLLocationCoordinate2D> = []
let path = GMSMutablePath()
// get path for polygon
for marker in markersArray {
let lat = coord.insert(marker.componentsSeparatedByString(",")[i] as NSString).doubleValue, atIndex:[i][0]
let lng = coord.insert(marker.componentsSeparatedByString(",")[i+1] as NSString).doubleValue, atIndex:[i][1]
path.addCoordinate(CLLocationCoordinate2DMake(coord[i][0]))
path.addCoordinate(CLLocationCoordinate2DMake(coord[i][1]))
}

As you can see I would like to increment the index by one every time so all coordinates get inserted. How do I achieve this?

Body:
There is a build in mechanism for that.

func drawPolygon(){
var cord: Array<CLLocationCoordinate2D> = []
let path = GMSMutablePath()
// get path for polygon
for (marker, i) in markersArray.enumerated() {
let lat = coord.insert(marker.componentsSeparatedByString(",")[i] as NSString).doubleValue, atIndex:[i][0]
let lng = coord.insert(marker.componentsSeparatedByString(",")[i+1] as NSString).doubleValue, atIndex:[i][1]
path.addCoordinate(CLLocationCoordinate2DMake(coord[i][0]))
path.addCoordinate(CLLocationCoordinate2DMake(coord[i][1]))
}


问:
Progress Bar findviewbyid returns null
Help me please it's getting frustrating!

i'm doing a chat application where i'm adding views to a linear layout programmatically each time a user press the send button the code is below:

```<code>public  void appendToMessageHistory(String id,String uname, String messa,String messageType, final String filepath, String DownloadStatus,boolean internet,int type) {

    //TextView tv=new TextView(Messaging.this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(Width, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(0, 10, 0, 0);

    View v = getLayoutInflater().inflate(R.layout.message_entity, null);

    TextView mess;
    TextView time;
    final ImageView iv;
    final ProgressBar progressBar;
    ImageView statusiv;
    if (friend.userName.equals(uname)) {
        v = getLayoutInflater().inflate(R.layout.message_entity, null);
        v.setId(Integer.parseInt(id));
        mess = (TextView) v.findViewById(R.id.message_entity_message);
        time = (TextView) v.findViewById(R.id.message_entity_time);
        iv = (ImageView) v.findViewById(R.id.message_entity_imageview);
        statusiv = (ImageView) v.findViewById(R.id.imageView);
        progressBar = (ProgressBar) v.findViewById(R.id.message_entity_progressbar);
    } else {
        v = getLayoutInflater().inflate(R.layout.message_entity_right, null);
        lp.gravity = Gravity.RIGHT;
        v.setId(Integer.parseInt(id));
        mess = (TextView) v.findViewById(R.id.message_entity_right_message);
        time = (TextView) v.findViewById(R.id.message_entity_right_time);
        iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
        statusiv = (ImageView)v.findViewById(R.id.imageViewleft);
        progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar);
    }

    try {
        progressBar.setId(Integer.parseInt(id));

    } catch (Exception e) {
        e.printStackTrace();
    }

    if (messageType != null) {
        if (messageType.equals(MessageInfo.MESSAGE_TYPE_PIC)) {
            iv.setImageBitmap(ImageHandlet.GetBitmapFromPath(filepath));
            progressBar.setVisibility(View.GONE);
            iv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse("file://" + filepath), "image/png");
                    startActivity(intent);
                    Log.d("FIlePAth", filepath);
                }
            });

        } else if (messageType.equals(MessageInfo.MESSAGE_TYPE_VIDEO)) {
            if (DownloadStatus.equals(LocalStorageHandler.DOWNLOADED)) {
                if(!(friend.userName.equals(uname))) {
                    if (type != 3) {
                        Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(filepath, MediaStore.Images.Thumbnails.MINI_KIND);
                        iv.setImageBitmap(bitTh);
                        progressBar.setVisibility(View.GONE);
                        iv.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filepath));
                                intent.setDataAndType(Uri.parse(filepath), "video/mp4");
                                startActivity(intent);

                            }
                        });
                    } else {
                        Log.w("Zipping","Progress Bar");
                        progressBar.setVisibility(View.VISIBLE);
                    }
                } else {
                    Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(filepath, MediaStore.Images.Thumbnails.MINI_KIND);
                    iv.setImageBitmap(bitTh);
                    progressBar.setVisibility(View.GONE);
                    iv.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filepath));
                            intent.setDataAndType(Uri.parse(filepath), "video/mp4");
                            startActivity(intent);

                        }
                    });
                }
            } else if (DownloadStatus.equals(LocalStorageHandler.NotDOWNLOADED)) {
                iv.setTag(id);
                iv.setImageResource(R.drawable.download);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        progressBar.setVisibility(View.VISIBLE);
                        Cursor c = localstoragehandler.getIDnfo(iv.getTag().toString());
                        String filepath = "";
                        //Toast.makeText(getApplication(),iv.getTag().toString()+" iD " +iv.getId(),Toast.LENGTH_SHORT).show();

                        while (c.moveToNext()) {
                            String msg0 = c.getString(0);
                            String msg2 = c.getString(2);
                            String msg3 = c.getString(3);
                            String msg4 = c.getString(4);
                            String msg5 = c.getString(5);
                            String msg6 = c.getString(6);

                            filepath = msg5;

                            Log.d("-----------Vedio-----", "------------------");
                            Log.d("DATABASE---------", msg0);
                            Log.d("DATABASE-------", msg2);
                            Log.d("DATABASE---------", msg3);
                            Log.d("DATABASE-----", msg4 + "");
                            Log.d("DATABASE-------", msg5 + "");
                            Log.d("DATABASE----------", msg6 + "");
                            Log.d("--------END-------", "-------END-----------");

                        }

                        Toast.makeText(getApplicationContext(), filepath.toString() + iv.getTag().toString(), Toast.LENGTH_SHORT).show();

                        DownloadFileFromURL downloadFileFromURL = new DownloadFileFromURL(filepath, iv.getTag().toString());
                        downloadFileFromURL.execute("");
                    }
                });
            }
        } else {
            iv.setVisibility(View.GONE);
            progressBar.setVisibility(View.GONE);
        }
    }
    if(!(messageType.equals(MessageInfo.MESSAGE_TYPE_VIDEO))) {
        if (!internet) {
            statusiv.setImageResource(R.drawable.noconnectionl);
        }
    }
    mess.setText(messa);
    //time.setText(sendt);
    v.setLayoutParams(lp);
    final View lastview = v;
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mEssageBox.addView(lastview);

        }
    });
    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(View.FOCUS_DOWN);
            messageText.requestFocus();
        }
    });
}
</code>```

and here is the XML of the dialogbox:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layoutDirection="ltr">

<ImageView
    android:id="@+id/imageViewleft"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/chaticion" />

<RelativeLayout
    android:id="@+id/tests"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#83e3ed"
    android:layoutDirection="rtl"
    android:padding="5dp"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/imageViewleft"
    android:layout_toStartOf="@+id/imageViewleft">

    <TextView
        android:id="@+id/message_entity_right_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="19dp"
        android:layout_marginRight="19dp"
        android:text="Large ffText"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textIsSelectable="true" />

    <TextView
        android:id="@+id/message_entity_right_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/message_entity_right_message"
        android:paddingRight="10dp"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@+id/message_entity_right_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_below="@+id/message_entity_right_time"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"

        android:src="@drawable/ic_launcher" />

    <ProgressBar
        android:id="@+id/message_entity_Right_progressbar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_below="@+id/message_entity_right_time"

        android:indeterminate="false"
        android:visibility="invisible" />

</RelativeLayout>
</code>```

And here is the code to send the video message:

```<code>final String message = messageText.getText().toString();
    final Long rowid = localstoragehandler.insert(imService.getUsername(), friend.userName, message, MessageInfo.MESSAGE_TYPE_VIDEO, ZippedVideoPath, LocalStorageHandler.DOWNLOADED); //insert data into db and get to chat_id
    appendToMessageHistory(rowid + "", imService.getUsername(), message, MessageInfo.MESSAGE_TYPE_VIDEO, ZippedVideoPath, LocalStorageHandler.DOWNLOADED, internet,3);// append the video with type 3 to just display the progress
    messageText.setText("Video");
    String newstr = null;
    // intialize the asynctask to upload the video
    class UploadVideo extends AsyncTask<Void, Void, String> {
        ProgressDialog uploading;
        View V;
        UploadVideo(View v){
            V = v;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //          uploading = ProgressDialog.show(Messaging.this, "Uploading File", "Please wait...", false, false);
        }

        @Override
        protected String doInBackground(Void... params) {
            return imService.sendVideoMessage(imService.getUsername(), friend.userName, message, MessageInfo.MESSAGE_TYPE_VIDEO, "", ZippedVideoPath);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
         //   RelativeLayout v = (RelativeLayout) V.findViewById(rowid.intValue());
        //    Log.w("Zipping",v.toString());
     //       ProgressBar progressBar1 = (ProgressBar) V.findViewById(R.id.message_entity_Right_progressbar);
      //      Log.w("Zipping",progressBar1.toString());
            //          ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
       //     progressBar1.setVisibility(View.GONE);
        //  Log.d("POST Execute", s + "");

            //textViewResponse.setText(Html.fromHtml("<b>Uploaded at <a href='" + s + "'>" + s + "</a></b>"));
            //textViewResponse.setMovementMethod(LinkMovementMethod.getInstance());
    // here i am preparing the path so when the compress is done to save into.
        }
    }
    if (null != absolute && absolute.length() > 0) {
        int endIndex = absolute.lastIndexOf("/");
        if (endIndex != -1) {
            newstr = absolute.substring(endIndex, absolute.length()); // not forgot to put check if(endIndex != -1)
        }
    }
    Log.w("Zipping", newstr);
    final File videosdir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/videos/");
    if (!videosdir.exists()) {
        videosdir.mkdirs();
    }
    ZippedVideoPath = videosdir.getAbsolutePath() + "/" + newstr;
    Log.w("Zipping", ZippedVideoPath);
    // here i got the ffmpeg library from the net to compress the video and i'm preparing the commands
    String[] complexCommand = {"-y", "-i", absolute, "-strict", "experimental", "-r", "25", "-vcodec", "mpeg4", "-b:a", "150k", "-ab", "48000", "-ac", "2", "-ar", "22050", ZippedVideoPath};
    FFmpeg ffmpeg = FFmpeg.getInstance(getBaseContext());
    try {
        // to execute "ffmpeg -version" command you just need to pass "-version"
        ffmpeg.execute(complexCommand, new ExecuteBinaryResponseHandler() {

            @Override
            public void onStart() {
                Log.w("Zipping", "started");
            }

            @Override
            public void onProgress(String message) {
            }

            @Override
            public void onFailure(String message) {
                Log.w("Zipping", message);
            }

            @Override
            public void onSuccess(String message1) {
                Log.w("Zipping","Success");
                RelativeLayout v = (RelativeLayout) mEssageBox.findViewById(rowid.intValue());
                Log.w("VideoView",v.toString());
                ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar);
                ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
            //  progressBar.setVisibility(View.GONE);
                Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(ZippedVideoPath, MediaStore.Images.Thumbnails.MINI_KIND);
                iv.setImageBitmap(bitTh);
                progressBar.setVisibility(View.GONE);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ZippedVideoPath));
                        intent.setDataAndType(Uri.parse(ZippedVideoPath), "video/mp4");
                        startActivity(intent);

                    }
                });
                UploadVideo uv = new UploadVideo(v);
                uv.execute();
            }

            @Override
            public void onFinish() {
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        Log.w("Zipping", e.toString());
    }
}
</code>```

okay now to the problem when i call the findviewbyid for the progress bar in sendvideomessage ffmpeg onsuccess callback it returns null even though the findviewbyid for the the imageview which is in the same layout it returns the view! so please tell me what is the problem

```<code>public void onSuccess(String message1) {
                Log.w("Zipping","Success");
                RelativeLayout v = (RelativeLayout) mEssageBox.findViewById(rowid.intValue()); ;
                ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar); // this keeps returning null!
                ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview); // returns the view
            //  progressBar.setVisibility(View.GONE);
                Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(ZippedVideoPath, MediaStore.Images.Thumbnails.MINI_KIND);
                iv.setImageBitmap(bitTh);
                progressBar.setVisibility(View.GONE);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ZippedVideoPath));
                        intent.setDataAndType(Uri.parse(ZippedVideoPath), "video/mp4");
                        startActivity(intent);

                    }
                });
                UploadVideo uv = new UploadVideo(v);
                uv.execute();
            }
</code>```

Thank you!

答:
Since you are using a final variable:

```<code>final ProgressBar progressBar;
</code>```

It ll be initialized only once. You cannot reassign a new value to it in the same context.

Try removing final or use separate ProgressBar variables for two different layouts and see if it works.

Let me know if it helps!

Title: Progress Bar findviewbyid returns null

Body:
Help me please it's getting frustrating!

i'm doing a chat application where i'm adding views to a linear layout programmatically each time a user press the send button the code is below:

public  void appendToMessageHistory(String id,String uname, String messa,String messageType, final String filepath, String DownloadStatus,boolean internet,int type) {

    //TextView tv=new TextView(Messaging.this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(Width, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(0, 10, 0, 0);

    View v = getLayoutInflater().inflate(R.layout.message_entity, null);

    TextView mess;
    TextView time;
    final ImageView iv;
    final ProgressBar progressBar;
    ImageView statusiv;
    if (friend.userName.equals(uname)) {
        v = getLayoutInflater().inflate(R.layout.message_entity, null);
        v.setId(Integer.parseInt(id));
        mess = (TextView) v.findViewById(R.id.message_entity_message);
        time = (TextView) v.findViewById(R.id.message_entity_time);
        iv = (ImageView) v.findViewById(R.id.message_entity_imageview);
        statusiv = (ImageView) v.findViewById(R.id.imageView);
        progressBar = (ProgressBar) v.findViewById(R.id.message_entity_progressbar);
    } else {
        v = getLayoutInflater().inflate(R.layout.message_entity_right, null);
        lp.gravity = Gravity.RIGHT;
        v.setId(Integer.parseInt(id));
        mess = (TextView) v.findViewById(R.id.message_entity_right_message);
        time = (TextView) v.findViewById(R.id.message_entity_right_time);
        iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
        statusiv = (ImageView)v.findViewById(R.id.imageViewleft);
        progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar);
    }

    try {
        progressBar.setId(Integer.parseInt(id));

    } catch (Exception e) {
        e.printStackTrace();
    }

    if (messageType != null) {
        if (messageType.equals(MessageInfo.MESSAGE_TYPE_PIC)) {
            iv.setImageBitmap(ImageHandlet.GetBitmapFromPath(filepath));
            progressBar.setVisibility(View.GONE);
            iv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse("file://" + filepath), "image/png");
                    startActivity(intent);
                    Log.d("FIlePAth", filepath);
                }
            });

        } else if (messageType.equals(MessageInfo.MESSAGE_TYPE_VIDEO)) {
            if (DownloadStatus.equals(LocalStorageHandler.DOWNLOADED)) {
                if(!(friend.userName.equals(uname))) {
                    if (type != 3) {
                        Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(filepath, MediaStore.Images.Thumbnails.MINI_KIND);
                        iv.setImageBitmap(bitTh);
                        progressBar.setVisibility(View.GONE);
                        iv.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filepath));
                                intent.setDataAndType(Uri.parse(filepath), "video/mp4");
                                startActivity(intent);

                            }
                        });
                    } else {
                        Log.w("Zipping","Progress Bar");
                        progressBar.setVisibility(View.VISIBLE);
                    }
                } else {
                    Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(filepath, MediaStore.Images.Thumbnails.MINI_KIND);
                    iv.setImageBitmap(bitTh);
                    progressBar.setVisibility(View.GONE);
                    iv.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filepath));
                            intent.setDataAndType(Uri.parse(filepath), "video/mp4");
                            startActivity(intent);

                        }
                    });
                }
            } else if (DownloadStatus.equals(LocalStorageHandler.NotDOWNLOADED)) {
                iv.setTag(id);
                iv.setImageResource(R.drawable.download);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        progressBar.setVisibility(View.VISIBLE);
                        Cursor c = localstoragehandler.getIDnfo(iv.getTag().toString());
                        String filepath = "";
                        //Toast.makeText(getApplication(),iv.getTag().toString()+" iD " +iv.getId(),Toast.LENGTH_SHORT).show();

                        while (c.moveToNext()) {
                            String msg0 = c.getString(0);
                            String msg2 = c.getString(2);
                            String msg3 = c.getString(3);
                            String msg4 = c.getString(4);
                            String msg5 = c.getString(5);
                            String msg6 = c.getString(6);

                            filepath = msg5;

                            Log.d("-----------Vedio-----", "------------------");
                            Log.d("DATABASE---------", msg0);
                            Log.d("DATABASE-------", msg2);
                            Log.d("DATABASE---------", msg3);
                            Log.d("DATABASE-----", msg4 + "");
                            Log.d("DATABASE-------", msg5 + "");
                            Log.d("DATABASE----------", msg6 + "");
                            Log.d("--------END-------", "-------END-----------");

                        }

                        Toast.makeText(getApplicationContext(), filepath.toString() + iv.getTag().toString(), Toast.LENGTH_SHORT).show();

                        DownloadFileFromURL downloadFileFromURL = new DownloadFileFromURL(filepath, iv.getTag().toString());
                        downloadFileFromURL.execute("");
                    }
                });
            }
        } else {
            iv.setVisibility(View.GONE);
            progressBar.setVisibility(View.GONE);
        }
    }
    if(!(messageType.equals(MessageInfo.MESSAGE_TYPE_VIDEO))) {
        if (!internet) {
            statusiv.setImageResource(R.drawable.noconnectionl);
        }
    }
    mess.setText(messa);
    //time.setText(sendt);
    v.setLayoutParams(lp);
    final View lastview = v;
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mEssageBox.addView(lastview);

        }
    });
    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(View.FOCUS_DOWN);
            messageText.requestFocus();
        }
    });
}

and here is the XML of the dialogbox:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layoutDirection="ltr">

<ImageView
    android:id="@+id/imageViewleft"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/chaticion" />

<RelativeLayout
    android:id="@+id/tests"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#83e3ed"
    android:layoutDirection="rtl"
    android:padding="5dp"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/imageViewleft"
    android:layout_toStartOf="@+id/imageViewleft">

    <TextView
        android:id="@+id/message_entity_right_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="19dp"
        android:layout_marginRight="19dp"
        android:text="Large ffText"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textIsSelectable="true" />

    <TextView
        android:id="@+id/message_entity_right_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/message_entity_right_message"
        android:paddingRight="10dp"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@+id/message_entity_right_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_below="@+id/message_entity_right_time"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"

        android:src="@drawable/ic_launcher" />

    <ProgressBar
        android:id="@+id/message_entity_Right_progressbar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_below="@+id/message_entity_right_time"

        android:indeterminate="false"
        android:visibility="invisible" />

</RelativeLayout>

And here is the code to send the video message:

final String message = messageText.getText().toString();
    final Long rowid = localstoragehandler.insert(imService.getUsername(), friend.userName, message, MessageInfo.MESSAGE_TYPE_VIDEO, ZippedVideoPath, LocalStorageHandler.DOWNLOADED); //insert data into db and get to chat_id
    appendToMessageHistory(rowid + "", imService.getUsername(), message, MessageInfo.MESSAGE_TYPE_VIDEO, ZippedVideoPath, LocalStorageHandler.DOWNLOADED, internet,3);// append the video with type 3 to just display the progress
    messageText.setText("Video");
    String newstr = null;
    // intialize the asynctask to upload the video
    class UploadVideo extends AsyncTask<Void, Void, String> {
        ProgressDialog uploading;
        View V;
        UploadVideo(View v){
            V = v;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //          uploading = ProgressDialog.show(Messaging.this, "Uploading File", "Please wait...", false, false);
        }

        @Override
        protected String doInBackground(Void... params) {
            return imService.sendVideoMessage(imService.getUsername(), friend.userName, message, MessageInfo.MESSAGE_TYPE_VIDEO, "", ZippedVideoPath);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
         //   RelativeLayout v = (RelativeLayout) V.findViewById(rowid.intValue());
        //    Log.w("Zipping",v.toString());
     //       ProgressBar progressBar1 = (ProgressBar) V.findViewById(R.id.message_entity_Right_progressbar);
      //      Log.w("Zipping",progressBar1.toString());
            //          ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
       //     progressBar1.setVisibility(View.GONE);
        //  Log.d("POST Execute", s + "");

            //textViewResponse.setText(Html.fromHtml("Uploaded at " + s + ""));
            //textViewResponse.setMovementMethod(LinkMovementMethod.getInstance());
    // here i am preparing the path so when the compress is done to save into.
        }
    }
    if (null != absolute && absolute.length() > 0) {
        int endIndex = absolute.lastIndexOf("/");
        if (endIndex != -1) {
            newstr = absolute.substring(endIndex, absolute.length()); // not forgot to put check if(endIndex != -1)
        }
    }
    Log.w("Zipping", newstr);
    final File videosdir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/videos/");
    if (!videosdir.exists()) {
        videosdir.mkdirs();
    }
    ZippedVideoPath = videosdir.getAbsolutePath() + "/" + newstr;
    Log.w("Zipping", ZippedVideoPath);
    // here i got the ffmpeg library from the net to compress the video and i'm preparing the commands
    String[] complexCommand = {"-y", "-i", absolute, "-strict", "experimental", "-r", "25", "-vcodec", "mpeg4", "-b:a", "150k", "-ab", "48000", "-ac", "2", "-ar", "22050", ZippedVideoPath};
    FFmpeg ffmpeg = FFmpeg.getInstance(getBaseContext());
    try {
        // to execute "ffmpeg -version" command you just need to pass "-version"
        ffmpeg.execute(complexCommand, new ExecuteBinaryResponseHandler() {

            @Override
            public void onStart() {
                Log.w("Zipping", "started");
            }

            @Override
            public void onProgress(String message) {
            }

            @Override
            public void onFailure(String message) {
                Log.w("Zipping", message);
            }

            @Override
            public void onSuccess(String message1) {
                Log.w("Zipping","Success");
                RelativeLayout v = (RelativeLayout) mEssageBox.findViewById(rowid.intValue());
                Log.w("VideoView",v.toString());
                ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar);
                ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
            //  progressBar.setVisibility(View.GONE);
                Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(ZippedVideoPath, MediaStore.Images.Thumbnails.MINI_KIND);
                iv.setImageBitmap(bitTh);
                progressBar.setVisibility(View.GONE);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ZippedVideoPath));
                        intent.setDataAndType(Uri.parse(ZippedVideoPath), "video/mp4");
                        startActivity(intent);

                    }
                });
                UploadVideo uv = new UploadVideo(v);
                uv.execute();
            }

            @Override
            public void onFinish() {
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        Log.w("Zipping", e.toString());
    }
}

okay now to the problem when i call the findviewbyid for the progress bar in sendvideomessage ffmpeg onsuccess callback it returns null even though the findviewbyid for the the imageview which is in the same layout it returns the view! so please tell me what is the problem

public void onSuccess(String message1) {
                Log.w("Zipping","Success");
                RelativeLayout v = (RelativeLayout) mEssageBox.findViewById(rowid.intValue()); ;
                ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar); // this keeps returning null!
                ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview); // returns the view
            //  progressBar.setVisibility(View.GONE);
                Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(ZippedVideoPath, MediaStore.Images.Thumbnails.MINI_KIND);
                iv.setImageBitmap(bitTh);
                progressBar.setVisibility(View.GONE);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ZippedVideoPath));
                        intent.setDataAndType(Uri.parse(ZippedVideoPath), "video/mp4");
                        startActivity(intent);

                    }
                });
                UploadVideo uv = new UploadVideo(v);
                uv.execute();
            }

Thank you!

Body:
Since you are using a final variable:

final ProgressBar progressBar;

It ll be initialized only once. You cannot reassign a new value to it in the same context.

Try removing final or use separate ProgressBar variables for two different layouts and see if it works.

Let me know if it helps!


问:
React/Redux animations based on actions
Having more or less completed my first React+Redux application, I have come to the point where I would like to apply animations to various parts of the application. Looking at existing solutions, I find that there is nothing even close to what I would like. The whole ReactCSSTransitionGroup seems to be both an intrusive and naive way to handle animations. Animation concerns bleed out of the component you want to animate and you have no way to know anything about what happens in the application. From my initial analysis I have come up with the following requirements for what I would consider a good animation API:

The parent component should be ignorant of how the child component fades in/out (maybe with the exception of staggered animations).

The animations should integrate with React such that components are allowed to fade out (or otherwise complete their animations) before they are removed.

It should be possible to apply an animation to a component without modifying the component. It is ok that the component is styled such as to be compatible with the animation, but there should be no props, state, contexts or components related to the animation, nor should the animation dictate how the component is created.

It should be possible to perform an animation based on an action and the application state - in other words, when I have the full semantic context of what happened. For example, I might fade in a component when a thing has been created, but not when the page loads with the item in it. Alternatively, I might select the proper fade out animation, based on the user's settings.

It should be possible to either enqueue or combine an animation for a component.

It should be possible to enqueue an animation with a parent component. For example, if a component has two sub components and opening one would first trigger the other to close before opening itself.

The specifics of enqueuing animations can be handled by an existing animation library, but it should be possible to tie it in with the react and redux system.

One approach I have tried out is to create a decorator function like this (it is TypeScript, but I don't think that matters too much with regards to the problem):

```<code>export function slideDown<T>(Component: T) {
  return class FadesUp extends React.Component<any, any> {
        private options = { duration: 0.3 };

        public componentWillEnter (callback) {
            const el = findDOMNode(this).childNodes[0] as Element;
            if (!el.classList.contains("animated-element")) {
                el.classList.add("animated-element");
            }

            TweenLite.set(el, { y: -el.clientHeight });
            TweenLite.to(el, this.options.duration, {y: 0, ease: Cubic.easeIn, onComplete: callback });
        }

        public componentWillLeave (callback) {
            const el = findDOMNode(this).childNodes[0] as Element;
            if (!el.classList.contains("animated-element")) {
                el.classList.add("animated-element");
            }

            TweenLite.to(el, this.options.duration, {y: -el.clientHeight, ease: Cubic.easeIn, onComplete: callback});
        }

        public render () {
            const Comp = Component as any;
            return <div style={{ overflow: "hidden", padding: 5, paddingTop: 0}}><Comp ref="child" {...this.props} /></div>;
        }

    } as any;
}
</code>```

...which can be applied like this...

```<code>@popIn
export class Term extends React.PureComponent<ITermStateProps & ITermDispatchProps, void> {
    public render(): JSX.Element {
        const { term, isSelected, onSelectTerm } = this.props;
        return <ListItem rightIcon={<PendingReviewIndicator termId={term.id} />} style={isSelected ? { backgroundColor: "#ddd" } : {}} onClick={onSelectTerm}>{term.canonicalName}</ListItem>;
    }
}
</code>```

Unfortunately it requires the component to be defined as a class, but it does make it possible to declaratively add an animation to a component without modifying it. I like this approach but hate that I have to wrap the component in a transition group - nor does it address any of the other requirements.

I don't know enough about the internal and extension points of React and Redux to have a good idea how to approach this. I figured thunk actions would be a good place to manage the animation flows but I don't want to send the action components into the actions. Rather, I would like to be able to retrieve the source component for an action or something like that. Another angle could be a specialized reducer which passes in both the action and the source component, allowing you to match them somehow and schedule animations.

So I guess what I'm after is one or more of the following:

Ways to hook into React and/or Redux, preferably without destroying performance or violating the basic assumptions of the libraries.

Whether there are any existing libraries that solves some or all of these issues and which would be easy to integrate into the application.

Techniques or approaches to achieve all or most of these goals by either working with the normal animation tools or integrating well into the normal building blocks.

答:
I hope I understood everything right… Dealing with React + Redux means, that in best case your components are pure functional. So a component that should be animated should (IMHO) at least take one parameter: p, which represents the state of the animation. p should be in the interval [0,1] and zero stands for the start, 1 for the end and everything in between for the current progress.

```<code>const Accordion = ({p}) => {
  return (
    …list of items, each getting p
  );
}
</code>```

So the question is, how to dispatch actions over time (what is an asynchronous thing),  after the animation started, until the animation is over, after a certain event triggered that process.

Middleware comes in handy here, since it can »process« dispatched actions, transform them into another, or into multiple

```<code>//middleware/animatror.js

const animator = store => next => action => {
  if (action.type === 'animator/start') {

    //retrieve animation settings
    const { duration, start, … } = action.payload;

    animationEngine.add({
      dispatch,
      action: {
       progress: () => { … },
       start: () => { … },
       end: () => { … }
      }
    })
  } else {
    return next(action);
  }
}

export default animator;
</code>```

Whereby the animationEngine is an Instance of AnimatoreEngine, an Object that listens to the window.requestAnimationFrame event and dispatches appropriate Actions. The creation of the middleware can be used the instantiate the animationEngine.

```<code>const createAnimationMiddleware = () => {
  const animatoreEngine = new AnimatorEngine;

  return const animator = store => next => action => { … }

}

export default createAnimationMiddleware;

//store.js
const animatorMiddleware = createAnimationMiddleware();

…

const store = createStore(
  …,
 applyMiddleware(animatorMiddleware, …)
)
</code>```

The basic Idea is, to »swallow« actions of type animator/start, or something else, and transform them into a bunch of »subactions«, which are configured in the action.payload.

Within the middleware, you can access dispatch and the action, so you can dispatch other actions from there, and those can be called with a progress parameter as well.

The code showed here is far from complete, but tried to figure out the idea. I have build »remote« middleware, which handles all my request like that. If the actions type is get:/some/path, it basically triggers a start action, which is defined in the payload and so on. In the action it looks like so:

```<code>const modulesOnSuccessAction => data {
  return {
    type: 'modules/listing-success',
    payload: { data }
  }
}

const modulesgetListing = id => dispatch({
  type: `get:/listing/${id}`,
  payload: {
    actions: {
      start: () => {},
      …
      success: data => modulesOnSuccessAction(data)
    }
  }
});

export { getListing }
</code>```

So I hope I could transport the Idea, even if the code is not ready for Copy/Paste.

Title: React/Redux animations based on actions

Body:
Having more or less completed my first React+Redux application, I have come to the point where I would like to apply animations to various parts of the application. Looking at existing solutions, I find that there is nothing even close to what I would like. The whole ReactCSSTransitionGroup seems to be both an intrusive and naive way to handle animations. Animation concerns bleed out of the component you want to animate and you have no way to know anything about what happens in the application. From my initial analysis I have come up with the following requirements for what I would consider a good animation API:

The parent component should be ignorant of how the child component fades in/out (maybe with the exception of staggered animations).

The animations should integrate with React such that components are allowed to fade out (or otherwise complete their animations) before they are removed.

It should be possible to apply an animation to a component without modifying the component. It is ok that the component is styled such as to be compatible with the animation, but there should be no props, state, contexts or components related to the animation, nor should the animation dictate how the component is created.

It should be possible to perform an animation based on an action and the application state - in other words, when I have the full semantic context of what happened. For example, I might fade in a component when a thing has been created, but not when the page loads with the item in it. Alternatively, I might select the proper fade out animation, based on the user's settings.

It should be possible to either enqueue or combine an animation for a component.

It should be possible to enqueue an animation with a parent component. For example, if a component has two sub components and opening one would first trigger the other to close before opening itself.

The specifics of enqueuing animations can be handled by an existing animation library, but it should be possible to tie it in with the react and redux system.

One approach I have tried out is to create a decorator function like this (it is TypeScript, but I don't think that matters too much with regards to the problem):

export function slideDown<T>(Component: T) {
  return class FadesUp extends React.Component<any, any> {
        private options = { duration: 0.3 };

        public componentWillEnter (callback) {
            const el = findDOMNode(this).childNodes[0] as Element;
            if (!el.classList.contains("animated-element")) {
                el.classList.add("animated-element");
            }

            TweenLite.set(el, { y: -el.clientHeight });
            TweenLite.to(el, this.options.duration, {y: 0, ease: Cubic.easeIn, onComplete: callback });
        }

        public componentWillLeave (callback) {
            const el = findDOMNode(this).childNodes[0] as Element;
            if (!el.classList.contains("animated-element")) {
                el.classList.add("animated-element");
            }

            TweenLite.to(el, this.options.duration, {y: -el.clientHeight, ease: Cubic.easeIn, onComplete: callback});
        }

        public render () {
            const Comp = Component as any;
            return
<Comp ref="child" {...this.props} />
;
        }

    } as any;
}

...which can be applied like this...

@popIn
export class Term extends React.PureComponent<ITermStateProps & ITermDispatchProps, void> {
    public render(): JSX.Element {
        const { term, isSelected, onSelectTerm } = this.props;
        return <ListItem rightIcon={<PendingReviewIndicator termId={term.id} />} style={isSelected ? { backgroundColor: "#ddd" } : {}} onClick={onSelectTerm}>{term.canonicalName}</ListItem>;
    }
}

Unfortunately it requires the component to be defined as a class, but it does make it possible to declaratively add an animation to a component without modifying it. I like this approach but hate that I have to wrap the component in a transition group - nor does it address any of the other requirements.

I don't know enough about the internal and extension points of React and Redux to have a good idea how to approach this. I figured thunk actions would be a good place to manage the animation flows but I don't want to send the action components into the actions. Rather, I would like to be able to retrieve the source component for an action or something like that. Another angle could be a specialized reducer which passes in both the action and the source component, allowing you to match them somehow and schedule animations.

So I guess what I'm after is one or more of the following:

Ways to hook into React and/or Redux, preferably without destroying performance or violating the basic assumptions of the libraries.

Whether there are any existing libraries that solves some or all of these issues and which would be easy to integrate into the application.

Techniques or approaches to achieve all or most of these goals by either working with the normal animation tools or integrating well into the normal building blocks.

Body:
I hope I understood everything right… Dealing with React + Redux means, that in best case your components are pure functional. So a component that should be animated should (IMHO) at least take one parameter: p, which represents the state of the animation. p should be in the interval [0,1] and zero stands for the start, 1 for the end and everything in between for the current progress.

const Accordion = ({p}) => {
  return (
    …list of items, each getting p
  );
}

So the question is, how to dispatch actions over time (what is an asynchronous thing),  after the animation started, until the animation is over, after a certain event triggered that process.

Middleware comes in handy here, since it can »process« dispatched actions, transform them into another, or into multiple

//middleware/animatror.js

const animator = store => next => action => {
  if (action.type === 'animator/start') {

    //retrieve animation settings
    const { duration, start, … } = action.payload;

    animationEngine.add({
      dispatch,
      action: {
       progress: () => { … },
       start: () => { … },
       end: () => { … }
      }
    })
  } else {
    return next(action);
  }
}

export default animator;

Whereby the animationEngine is an Instance of AnimatoreEngine, an Object that listens to the window.requestAnimationFrame event and dispatches appropriate Actions. The creation of the middleware can be used the instantiate the animationEngine.

const createAnimationMiddleware = () => {
  const animatoreEngine = new AnimatorEngine;

  return const animator = store => next => action => { … }

}

export default createAnimationMiddleware;

//store.js
const animatorMiddleware = createAnimationMiddleware();

…

const store = createStore(
  …,
 applyMiddleware(animatorMiddleware, …)
)

The basic Idea is, to »swallow« actions of type animator/start, or something else, and transform them into a bunch of »subactions«, which are configured in the action.payload.

Within the middleware, you can access dispatch and the action, so you can dispatch other actions from there, and those can be called with a progress parameter as well.

The code showed here is far from complete, but tried to figure out the idea. I have build »remote« middleware, which handles all my request like that. If the actions type is get:/some/path, it basically triggers a start action, which is defined in the payload and so on. In the action it looks like so:

const modulesOnSuccessAction => data {
  return {
    type: 'modules/listing-success',
    payload: { data }
  }
}

const modulesgetListing = id => dispatch({
  type: `get:/listing/${id}`,
  payload: {
    actions: {
      start: () => {},
      …
      success: data => modulesOnSuccessAction(data)
    }
  }
});

export { getListing }

So I hope I could transport the Idea, even if the code is not ready for Copy/Paste.


问:
Beautiful soup xml formatting in python
I have an xml dataset tag in the following format:

```<code><catchphrase "id=c0">unconscionable conduct</catchphrase>
</code>```

I think when they made the dataset they didn't format the id attribute as it has to be:

```<code><catchphrase id="c0">unconscionable conduct</catchphrase>
</code>```

However, when this goes through Beautiful Soap lib in python it comes out as follows:

```<code> soup = BeautifulSoup(content, 'xml')
</code>```

results in

```<code> <catchphrase>
   "id=c0">application for leave to appeal
  </catchphrase>
</code>```

or

```<code>soup = BeautifulSoup(content, 'lxml')
</code>```

results in

```<code><html>
   <body>
    ...
     <catchphrase>
         application for leave to appeal
     </catchphrase>
    ....
</code>```

I want to look like the second one but without the html and body tags (this is an XML document). I don't need the id attribute. I also use soup.prettify('utf-8') before writing it in the file but I think it is already wrongly formatted when I do it.

答:
There is no such standard way of doing this, but what you can do is replacing the faulty part with the correct way, something like this :

```<code>from bs4 import BeautifulSoup
content = '<catchphrase "id=c0">unconscionable conduct</catchphrase>'

soup = BeautifulSoup(content.replace('"id=', 'id="'), 'xml')
print soup
</code>```

This results in :

```<code><catchphrase id="c0">unconscionable conduct</catchphrase>
</code>```

This is definitely a bit of a hack as there is no standard way to handle this mainly because XML is supposed to be correct before parsing by BeautifulSoup.

Title: Beautiful soup xml formatting in python

Body:
I have an xml dataset tag in the following format:

<catchphrase "id=c0">unconscionable conduct</catchphrase>

I think when they made the dataset they didn't format the id attribute as it has to be:

<catchphrase id="c0">unconscionable conduct</catchphrase>

However, when this goes through Beautiful Soap lib in python it comes out as follows:

 soup = BeautifulSoup(content, 'xml')

results in

 <catchphrase>
   "id=c0">application for leave to appeal
  </catchphrase>

or

soup = BeautifulSoup(content, 'lxml')

results in

    ...
     <catchphrase>
         application for leave to appeal
     </catchphrase>
    ....

I want to look like the second one but without the html and body tags (this is an XML document). I don't need the id attribute. I also use soup.prettify('utf-8') before writing it in the file but I think it is already wrongly formatted when I do it.

Body:
There is no such standard way of doing this, but what you can do is replacing the faulty part with the correct way, something like this :

from bs4 import BeautifulSoup
content = '<catchphrase "id=c0">unconscionable conduct</catchphrase>'

soup = BeautifulSoup(content.replace('"id=', 'id="'), 'xml')
print soup

This results in :

<catchphrase id="c0">unconscionable conduct</catchphrase>

This is definitely a bit of a hack as there is no standard way to handle this mainly because XML is supposed to be correct before parsing by BeautifulSoup.


问:
Angular2 Observable not get called if there is access to result attribute
I have an HTTP service like this to retrieve a user list:

```<code>@Injectable()
export class UserService {
    private _dataStore: {
         users: User[]
    };
    private _users: BehaviorSubject<User[]> = new BehaviorSubject<User[]>();
    public usersObservable: Observable<User[]> = this._users.asObservable();

    ...

    public list(): void {
    this
        .http
        .get('/users')
        .subscribe((res) => {
            this._dataStore.users = res.json() as User[];
            this._users.next(Object.assign({}, this._dataStore).users);
        });
    }
}
</code>```

Then in my component:

```<code>export class UsersComponent {
    public users: User[] = [];
    private usersObservable: Observable<User[]>;

    constructor(private userService: UserService) {
        this.usersObservable = this.userService.usersObservable;
    }

    public listUsers(): void {
        this.usersObservable.subscribe(data => {
            this.users = data;
            console.log(this.users.length); // <- this line cause the mysterious bug,
            // a replace with console.log(this.users) makes the app works correctly
        }));
        this.userService.list();
    }
}
</code>```

And the view of this component is just a table with rows like

```<code><tr *ngFor='let user of users'>
........ <!-- Display data here -->
</tr>
</code>```

The problem is, if I call any function that access to the attributes of data or this.users, the observable won't get called. If I just console.log(this.users) or console.log(data), everything went fine.

Do you have any idea where the problem is ?
Thank you in advance.

答:
You doing 2 async operations but you are mixing them up.

First you subscribe to usersObservable which is initially just a BehaviorSubject with no value.

Then you call the async list() method to fill up your Subject so that your observable can have values.

Before your observable receive its values you are trying to display the length of the values which it doesn't have.

Body:
I have an HTTP service like this to retrieve a user list:

@Injectable()
export class UserService {
    private _dataStore: {
         users: User[]
    };
    private _users: BehaviorSubject<User[]> = new BehaviorSubject<User[]>();
    public usersObservable: Observable<User[]> = this._users.asObservable();

    ...

    public list(): void {
    this
        .http
        .get('/users')
        .subscribe((res) => {
            this._dataStore.users = res.json() as User[];
            this._users.next(Object.assign({}, this._dataStore).users);
        });
    }
}

Then in my component:

export class UsersComponent {
    public users: User[] = [];
    private usersObservable: Observable<User[]>;

    constructor(private userService: UserService) {
        this.usersObservable = this.userService.usersObservable;
    }

    public listUsers(): void {
        this.usersObservable.subscribe(data => {
            this.users = data;
            console.log(this.users.length); // <- this line cause the mysterious bug,
            // a replace with console.log(this.users) makes the app works correctly
        }));
        this.userService.list();
    }
}

And the view of this component is just a table with rows like

........

The problem is, if I call any function that access to the attributes of data or this.users, the observable won't get called. If I just console.log(this.users) or console.log(data), everything went fine.

Do you have any idea where the problem is ?
Thank you in advance.


问:
How can I add padding to divs without using a inner div with 960gs?
I'm using 960gs, and am trying to add padding to divs without using an inner div.

You see, if you add padding to the actual div it will break the layout created by 960gs, and the only way I have found to solve this is to create another div within and apply the padding to that.

I guess there's no problem with this method, I just find the second div unnecessary and I'd rather not use it... any ideas?

答:
That's one of the main drawbacks of any grid system. Unfortunately, to my knowledge, there's no way around the padding problem other than to add extra markup. As such, adding an inner div is recommended method (one that doesn't have a "grid_xx" class attributed to it).

However, if you're feeling brave (and ready for alot of coding), you could attribute padding directly to the child elements. Here's the code for the two solutions:

```<code><div class="grid_12">
 <div class="inner_div" style="padding:10px">
  <p>This is some sample text</p>
 </div>
</div>
</code>```

Or you could leave out the inner div, and use the styles directly on the child elements like this:

```<code><div class="grid_12">
 <p style="padding:10px">This is some sample text</p>
</div>
</code>```

Obviously you could use CSS instead of inline CSS, but the principles would be the same :)

Hope it helps.

You could also have a look at the Blueprint or YUI CSS framework, but as far as I know they've got exactly the same issue.

Body:
That's one of the main drawbacks of any grid system. Unfortunately, to my knowledge, there's no way around the padding problem other than to add extra markup. As such, adding an inner div is recommended method (one that doesn't have a "grid_xx" class attributed to it).

However, if you're feeling brave (and ready for alot of coding), you could attribute padding directly to the child elements. Here's the code for the two solutions:

<div class="grid_12">
 <div class="inner_div" style="padding:10px">
  <p>This is some sample text</p>
 </div>
</div>

Or you could leave out the inner div, and use the styles directly on the child elements like this:

<div class="grid_12">
 <p style="padding:10px">This is some sample text</p>
</div>

Obviously you could use CSS instead of inline CSS, but the principles would be the same :)

Hope it helps.

You could also have a look at the Blueprint or YUI CSS framework, but as far as I know they've got exactly the same issue.


问:
Django - Best way to create tables
I am displaying data from my database following a certain pattern.

To do so, I'm using a template with {% for %} loop to create the lines / columns of the table.

First question: I'm not sure is this is the right way to do this and if there is a more efficient way.

Second question: How to sort. I would like to know how I could sort the table. Because of the {% for %} loop building the table, I don't know how to properly sort my table columns by clicking on the headers. I've seen many solutions but none would work with the loop in the table missing things up.

Indeed, with things like django-table2, I don't know how if I can incorporate my specific loop (instead of printing the entire table, which I can sort using django-table2 but w/o being capable of adapting both design and information displayed.

Below an example of how I'm building things in the template - with a table included in a table:

```<code>        <table>
          <thead>
            <tr>
              <th>Status</th>
              <th>Some</th>
              <th>Something</th>
              <th>Other</th>
            </tr>
          </thead>
          <tbody>

            {% block content %}
            {% for x in xx %}
                <tr>
                    <td> {{ x.status }} </td>
                    <td> {{ x.some}} </td>
                    <td> {{ x.something }} </td>
                    <td>

                        <table>
                            <thead>
                              <th> Br </th>
                              <th> Sc </th>
                              <th> Ic </th>
                             </thead>
                             <tbody>
                             <tr>
                                <td>{% if itemA|get_item:varX.name >= 1 %} Good {% else %} Bad {% endif %} </td>
                                <td>{% if itemB|get_item:varY.name >= 1 %} Good {% else %} Bad {% endif %} </td>
                                <td>{% if itemC|get_item:varY.name >= 1 %} Good {% else %} Bad {% endif %} </td>
                             </tr>
                         </table>

                     </td>
                </tr>
         </table>
                </td>
                </tr>

            {% endfor %}
            {% endblock %}
</code>```

Many thanks in advance for your help !

答:
First question: I'm not sure is this is the right way to do this and
  if there is a more efficient way.

Yes this is a good solution.

Second question: How to sort. I would like to know how I could sort
  the table. Because of the {% for %} loop building the table, I don't
  know how to properly sort my table columns by clicking on the headers.
  I've seen many solutions but none would work with the loop in the
  table missing things up.

You can either sort on the backend (render your template with sorted data from Django), or you can sort on the frontend (javascript). The loop shouldn't have anything to do with sorting on the frontend. Once your template is rendered, your html is just html, nothing special about it.

Title: Django - Best way to create tables

Body:
I am displaying data from my database following a certain pattern.

To do so, I'm using a template with {% for %} loop to create the lines / columns of the table.

First question: I'm not sure is this is the right way to do this and if there is a more efficient way.

Second question: How to sort. I would like to know how I could sort the table. Because of the {% for %} loop building the table, I don't know how to properly sort my table columns by clicking on the headers. I've seen many solutions but none would work with the loop in the table missing things up.

Indeed, with things like django-table2, I don't know how if I can incorporate my specific loop (instead of printing the entire table, which I can sort using django-table2 but w/o being capable of adapting both design and information displayed.

Below an example of how I'm building things in the template - with a table included in a table:

              Status
              Some
              Something
              Other

            {% block content %}
            {% for x in xx %}

                     {{ x.status }}
                     {{ x.some}}
                     {{ x.something }}

                               Br
                               Sc
                               Ic

                                {% if itemA|get_item:varX.name >= 1 %} Good {% else %} Bad {% endif %}
                                {% if itemB|get_item:varY.name >= 1 %} Good {% else %} Bad {% endif %}
                                {% if itemC|get_item:varY.name >= 1 %} Good {% else %} Bad {% endif %}

            {% endfor %}
            {% endblock %}

Many thanks in advance for your help !